source stringlengths 3 92 | c stringlengths 26 2.25M |
|---|---|
main.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define N 1000
int main()
{
int i;
#pragma omp parallel for private(i) num_threads(5) schedule(guided)
for(i = 0; i < N; i++)
{
sleep(i);
printf("Il thread %d ha completato iterazione %d.\n", omp_get_thread_num() , i);
}
printf("Tutti i thread hanno terminato! \n");
return 0;
}
|
GB_AxB_saxpy3_template.c | //------------------------------------------------------------------------------
// GB_AxB_saxpy3_template: C=A*B, C<M>=A*B, or C<!M>=A*B via saxpy3 method
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_template.c computes C=A*B for any semiring and matrix types,
// where C is sparse or hypersparse.
#include "GB_unused.h"
//------------------------------------------------------------------------------
// template code for C=A*B via the saxpy3 method
//------------------------------------------------------------------------------
{
// double ttt = omp_get_wtime ( ) ;
//--------------------------------------------------------------------------
// get the chunk size
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
//--------------------------------------------------------------------------
// get M, A, B, and C
//--------------------------------------------------------------------------
int64_t *GB_RESTRICT Cp = C->p ;
// const int64_t *GB_RESTRICT Ch = C->h ;
const int64_t cvlen = C->vlen ;
const int64_t cnvec = C->nvec ;
const int64_t *GB_RESTRICT Bp = B->p ;
const int64_t *GB_RESTRICT Bh = B->h ;
const int8_t *GB_RESTRICT Bb = B->b ;
const int64_t *GB_RESTRICT Bi = B->i ;
const GB_BTYPE *GB_RESTRICT Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ;
const int64_t bvlen = B->vlen ;
const bool B_jumbled = B->jumbled ;
const bool B_is_sparse = GB_IS_SPARSE (B) ;
const bool B_is_hyper = GB_IS_HYPERSPARSE (B) ;
const bool B_is_bitmap = GB_IS_BITMAP (B) ;
const bool B_is_sparse_or_hyper = B_is_sparse || B_is_hyper ;
const int64_t *GB_RESTRICT Ap = A->p ;
const int64_t *GB_RESTRICT Ah = A->h ;
const int8_t *GB_RESTRICT Ab = A->b ;
const int64_t *GB_RESTRICT Ai = A->i ;
const int64_t anvec = A->nvec ;
const int64_t avlen = A->vlen ;
const bool A_is_sparse = GB_IS_SPARSE (A) ;
const bool A_is_hyper = GB_IS_HYPERSPARSE (A) ;
const bool A_is_bitmap = GB_IS_BITMAP (A) ;
const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) (A_is_pattern ? NULL : A->x) ;
const bool A_jumbled = A->jumbled ;
const bool A_ok_for_binary_search =
((A_is_sparse || A_is_hyper) && !A_jumbled) ;
const int64_t *GB_RESTRICT Mp = NULL ;
const int64_t *GB_RESTRICT Mh = NULL ;
const int8_t *GB_RESTRICT Mb = NULL ;
const int64_t *GB_RESTRICT Mi = NULL ;
const GB_void *GB_RESTRICT Mx = NULL ;
size_t msize = 0 ;
int64_t mnvec = 0 ;
int64_t mvlen = 0 ;
const bool M_is_hyper = GB_IS_HYPERSPARSE (M) ;
const bool M_is_bitmap = GB_IS_BITMAP (M) ;
const bool M_jumbled = GB_JUMBLED (M) ;
if (M != NULL)
{
Mp = M->p ;
Mh = M->h ;
Mb = M->b ;
Mi = M->i ;
Mx = (GB_void *) (Mask_struct ? NULL : (M->x)) ;
msize = M->type->size ;
mnvec = M->nvec ;
mvlen = M->vlen ;
}
// 3 cases:
// M not present and Mask_comp false: compute C=A*B
// M present and Mask_comp false: compute C<M>=A*B
// M present and Mask_comp true : compute C<!M>=A*B
// If M is NULL on input, then Mask_comp is also false on input.
const bool mask_is_M = (M != NULL && !Mask_comp) ;
// ignore the mask if present, not complemented, dense and
// used in place, structural, and not bitmap. In this case,
// all entries in M are true, so M can be ignored.
const bool ignore_mask = mask_is_M && M_dense_in_place &&
Mask_struct && !M_is_bitmap ;
//==========================================================================
// phase2: numeric work for fine tasks
//==========================================================================
// Coarse tasks: nothing to do in phase2.
// Fine tasks: compute nnz (C(:,j)), and values in Hx via atomics.
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < nfine ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
int64_t kk = TaskList [taskid].vector ;
int team_size = TaskList [taskid].team_size ;
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
int64_t pB = TaskList [taskid].start ;
int64_t pB_end = TaskList [taskid].end + 1 ;
int64_t pleft = 0, pright = anvec-1 ;
int64_t j = GBH (Bh, kk) ;
GB_GET_T_FOR_SECONDJ ;
#if !GB_IS_ANY_PAIR_SEMIRING
GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ;
#endif
#if GB_IS_PLUS_FC32_MONOID
float *GB_RESTRICT Hx_real = (float *) Hx ;
float *GB_RESTRICT Hx_imag = Hx_real + 1 ;
#elif GB_IS_PLUS_FC64_MONOID
double *GB_RESTRICT Hx_real = (double *) Hx ;
double *GB_RESTRICT Hx_imag = Hx_real + 1 ;
#endif
if (use_Gustavson)
{
//------------------------------------------------------------------
// phase2: fine Gustavson task
//------------------------------------------------------------------
// Hf [i] == 0: unlocked, i has not been seen in C(:,j).
// Hx [i] is not initialized.
// M(i,j) is 0, or M is not present.
// if M: Hf [i] stays equal to 0 (or 3 if locked)
// if !M, or no M: C(i,j) is a new entry seen for 1st time
// Hf [i] == 1: unlocked, i has not been seen in C(:,j).
// Hx [i] is not initialized. M is present.
// M(i,j) is 1. (either M or !M case)
// if M: C(i,j) is a new entry seen for the first time.
// if !M: Hf [i] stays equal to 1 (or 3 if locked)
// Hf [i] == 2: unlocked, i has been seen in C(:,j).
// Hx [i] is initialized. This case is independent of M.
// Hf [i] == 3: locked. Hx [i] cannot be accessed.
int8_t *GB_RESTRICT Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf;
if (M == NULL)
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is initially 0.
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int8_t f ;
#if GB_IS_ANY_MONOID
//--------------------------------------------------
// C(i,j) += t ; with the ANY monoid
//--------------------------------------------------
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
if (f == 2) continue ; // check if already updated
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
#else
//--------------------------------------------------
// C(i,j) += t ; with all other monoids
//--------------------------------------------------
#if GB_HAS_ATOMIC
// if C(i,j) is already present (f==2), and the
// monoid can be done atomically, then do the
// atomic update. No need to modify Hf [i].
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
if (f == 2) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
continue ; // C(i,j) has been updated
}
#endif
do // lock the entry
{
// do this atomically:
// { f = Hf [i] ; Hf [i] = 3 ; }
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ;
} while (f == 3) ; // lock owner gets f=0 or 2
if (f == 0)
{
// C(i,j) is a new entry
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
else // f == 2
{
// C(i,j) already appears in C(:,j)
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
}
#endif
GB_ATOMIC_WRITE
Hf [i] = 2 ; // flag/unlock the entry
}
}
}
else if (mask_is_M)
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)<M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is 0 if M(i,j) not present or M(i,j)=0.
// 0 -> 1 : has already been done in phase0 if M(i,j)=1.
// 0 -> 0 : to ignore, if M(i,j)=0
// 1 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#if GB_IS_ANY_MONOID
//------------------------------------------------------
// C(i,j) += A(i,k)*B(k,j) ; with the ANY monoid
//------------------------------------------------------
#define GB_IKJ \
int8_t f ; \
GB_ATOMIC_READ \
f = Hf [i] ; /* grab the entry */ \
if (f == 0 || f == 2) continue ; \
GB_ATOMIC_WRITE \
Hf [i] = 2 ; /* unlock the entry */ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */
#else
//------------------------------------------------------
// C(i,j) += A(i,k)*B(k,j) ; all other monoids
//------------------------------------------------------
#define GB_IKJ \
{ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
int8_t f ; \
GB_ATOMIC_READ \
f = Hf [i] ; /* grab the entry */ \
if (GB_HAS_ATOMIC && (f == 2)) \
{ \
/* C(i,j) already seen; update it */ \
GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \
continue ; /* C(i,j) has been updated */ \
} \
if (f == 0) continue ; /* M(i,j)=0; ignore C(i,j)*/\
do /* lock the entry */ \
{ \
/* do this atomically: */ \
/* { f = Hf [i] ; Hf [i] = 3 ; } */ \
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ; \
} while (f == 3) ; /* lock owner gets f=1 or 2 */ \
if (f == 1) \
{ \
/* C(i,j) is a new entry */ \
GB_ATOMIC_WRITE_HX (i, t) ; /* Hx [i] = t */ \
} \
else /* f == 2 */ \
{ \
/* C(i,j) already appears in C(:,j) */ \
GB_ATOMIC_UPDATE_HX (i, t) ; /* Hx [i] += t */ \
} \
GB_ATOMIC_WRITE \
Hf [i] = 2 ; /* unlock the entry */ \
}
#endif
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
}
else
{
//--------------------------------------------------------------
// phase2: fine Gustavson task, C(:,j)<!M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
// Hf [i] is 0 if M(i,j) not present or M(i,j)=0.
// 0 -> 1 : has already been done in phase0 if M(i,j)=1
// 1 -> 1 : to ignore, if M(i,j)=1
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j ; // get M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int8_t f ;
#if GB_IS_ANY_MONOID
//--------------------------------------------------
// ANY monoid
//--------------------------------------------------
// lock state (3) not needed
// 0: not seen: update with new value, f becomes 2
// 1: masked, do nothing, f stays 1
// 2: already updated, do nothing, f stays 2
// 3: state not used, f can be 2
GB_ATOMIC_READ
f = Hf [i] ;
if (!f)
{
GB_ATOMIC_WRITE
Hf [i] = 2 ;
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
#else
GB_ATOMIC_READ
f = Hf [i] ; // grab the entry
#if GB_HAS_ATOMIC
if (f == 2) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
continue ; // C(i,j) has been updated
}
#endif
if (f == 1) continue ; // M(i,j)=1; ignore C(i,j)
do // lock the entry
{
// do this atomically:
// { f = Hf [i] ; Hf [i] = 3 ; }
GB_ATOMIC_CAPTURE_INT8 (f, Hf [i], 3) ;
} while (f == 3) ; // lock owner of gets f=0 or 2
if (f == 0)
{
// C(i,j) is a new entry
GB_ATOMIC_WRITE_HX (i, t) ; // Hx [i] = t
}
else // f == 2
{
// C(i,j) already seen
GB_ATOMIC_UPDATE_HX (i, t) ; // Hx [i] += t
}
GB_ATOMIC_WRITE
Hf [i] = 2 ; // unlock the entry
#endif
}
}
}
}
else
{
//------------------------------------------------------------------
// phase2: fine hash task
//------------------------------------------------------------------
// Each hash entry Hf [hash] splits into two parts, (h,f). f
// is in the 2 least significant bits. h is 62 bits, and is
// the 1-based index i of the C(i,j) entry stored at that
// location in the hash table.
// If M is present (M or !M), and M(i,j)=1, then (i+1,1)
// has been inserted into the hash table, in phase0.
// Given Hf [hash] split into (h,f)
// h == 0, f == 0: unlocked and unoccupied.
// note that if f=0, h must be zero too.
// h == i+1, f == 1: unlocked, occupied by M(i,j)=1.
// C(i,j) has not been seen, or is ignored.
// Hx is not initialized. M is present.
// if !M: this entry will be ignored in C.
// h == i+1, f == 2: unlocked, occupied by C(i,j).
// Hx is initialized. M is no longer
// relevant.
// h == (anything), f == 3: locked.
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t hash_bits = (hash_size-1) ;
if (M == NULL || ignore_mask)
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)=A*B(:,j)
//--------------------------------------------------------------
// no mask present, or mask ignored
#undef GB_CHECK_MASK_ij
#include "GB_AxB_saxpy3_fineHash_phase2.c"
}
else if (mask_is_M)
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)<M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
GB_GET_M_j ; // get M(:,j)
if (M_dense_in_place)
{
//----------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//----------------------------------------------------------
ASSERT (!Mask_struct || M_is_bitmap) ;
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (!mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (!mij) continue ;
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
}
// the task is finished: go to the next task
continue ;
}
//--------------------------------------------------------------
// M is sparse and scattered into Hf
//--------------------------------------------------------------
// Given Hf [hash] split into (h,f)
// h == 0 , f == 0 : unlocked, unoccupied. C(i,j) ignored
// h == i+1, f == 1 : unlocked, occupied by M(i,j)=1.
// C(i,j) has not been seen.
// Hx is not initialized.
// h == i+1, f == 2 : unlocked, occupied by C(i,j), M(i,j)=1
// Hx is initialized.
// h == ..., f == 3 : locked.
// 0 -> 0 : to ignore, if M(i,j)=0
// 1 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
GB_GET_M_j_RANGE (16) ; // get first and last in M(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
GB_MULT_A_ik_B_kj ; /* t = A(i,k) * B(k,j) */ \
int64_t i1 = i + 1 ; /* i1 = one-based index */ \
int64_t i_unlocked = (i1 << 2) + 2 ; /* (i+1,2) */ \
for (GB_HASH (i)) /* find i in hash table */ \
{ \
int64_t hf ; \
GB_ATOMIC_READ \
hf = Hf [hash] ; /* grab the entry */ \
if (GB_HAS_ATOMIC && (hf == i_unlocked)) \
{ \
/* Hx [hash] += t */ \
GB_ATOMIC_UPDATE_HX (hash, t) ; \
break ; /* C(i,j) has been updated */ \
} \
if (hf == 0) break ; /* M(i,j)=0; ignore Cij */ \
if ((hf >> 2) == i1) /* if true, i found */ \
{ \
do /* lock the entry */ \
{ \
/* do this atomically: */ \
/* { hf = Hf [hash] ; Hf [hash] |= 3 ; }*/ \
GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3);\
} while ((hf & 3) == 3) ; /* own: f=1,2 */ \
if ((hf & 3) == 1) /* f == 1 */ \
{ \
/* C(i,j) is a new entry in C(:,j) */ \
/* Hx [hash] = t */ \
GB_ATOMIC_WRITE_HX (hash, t) ; \
} \
else /* f == 2 */ \
{ \
/* C(i,j) already appears in C(:,j) */ \
/* Hx [hash] += t */ \
GB_ATOMIC_UPDATE_HX (hash, t) ; \
} \
GB_ATOMIC_WRITE \
Hf [hash] = i_unlocked ; /* unlock entry */ \
break ; \
} \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
}
else
{
//--------------------------------------------------------------
// phase2: fine hash task, C(:,j)<!M(:,j)>=A*B(:,j)
//--------------------------------------------------------------
GB_GET_M_j ; // get M(:,j)
if (M_dense_in_place)
{
//----------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//----------------------------------------------------------
if (Mask_struct && !M_is_bitmap)
{
// structural mask, complemented, and not bitmap.
// No work to do.
continue ;
}
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (mij) continue ;
#include "GB_AxB_saxpy3_fineHash_phase2.c"
break ;
}
// the task is finished: go to the next task
continue ;
}
//--------------------------------------------------------------
// M is sparse and scattered into Hf
//--------------------------------------------------------------
// Given Hf [hash] split into (h,f)
// h == 0 , f == 0 : unlocked and unoccupied.
// h == i+1, f == 1 : unlocked, occupied by M(i,j)=1.
// C(i,j) is ignored.
// h == i+1, f == 2 : unlocked, occupied by C(i,j).
// Hx is initialized.
// h == (anything), f == 3: locked.
// 1 -> 1 : to ignore, if M(i,j)=1
// 0 -> 3 : to lock, if i seen for first time
// 2 -> 3 : to lock, if i seen already
// 3 -> 2 : to unlock; now i has been seen
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
GB_MULT_A_ik_B_kj ; // t = A(i,k) * B(k,j)
int64_t i1 = i + 1 ; // i1 = one-based index
int64_t i_unlocked = (i1 << 2) + 2 ; // (i+1,2)
int64_t i_masked = (i1 << 2) + 1 ; // (i+1,1)
for (GB_HASH (i)) // find i in hash table
{
int64_t hf ;
GB_ATOMIC_READ
hf = Hf [hash] ; // grab the entry
#if GB_HAS_ATOMIC
if (hf == i_unlocked) // if true, update C(i,j)
{
GB_ATOMIC_UPDATE_HX (hash, t) ;// Hx [.]+=t
break ; // C(i,j) has been updated
}
#endif
if (hf == i_masked) break ; // M(i,j)=1; ignore
int64_t h = (hf >> 2) ;
if (h == 0 || h == i1)
{
// h=0: unoccupied, h=i1: occupied by i
do // lock the entry
{
// do this atomically:
// { hf = Hf [hash] ; Hf [hash] |= 3 ; }
GB_ATOMIC_CAPTURE_INT64_OR (hf,Hf[hash],3) ;
} while ((hf & 3) == 3) ; // owner: f=0,1,2
if (hf == 0) // f == 0
{
// C(i,j) is a new entry in C(:,j)
// Hx [hash] = t
GB_ATOMIC_WRITE_HX (hash, t) ;
GB_ATOMIC_WRITE
Hf [hash] = i_unlocked ; // unlock entry
break ;
}
if (hf == i_unlocked) // f == 2
{
// C(i,j) already appears in C(:,j)
// Hx [hash] += t
GB_ATOMIC_UPDATE_HX (hash, t) ;
GB_ATOMIC_WRITE
Hf [hash] = i_unlocked ; // unlock entry
break ;
}
// hash table occupied, but not with i,
// or with i but M(i,j)=1 so C(i,j) ignored
GB_ATOMIC_WRITE
Hf [hash] = hf ; // unlock with prior value
}
}
}
}
}
}
}
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (9, ttt) ;
// ttt = omp_get_wtime ( ) ;
//==========================================================================
// phase3/phase4: count nnz(C(:,j)) for fine tasks, cumsum of Cp
//==========================================================================
GB_AxB_saxpy3_cumsum (C, TaskList, nfine, chunk, nthreads) ;
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (10, ttt) ;
// ttt = omp_get_wtime ( ) ;
//==========================================================================
// phase5: numeric phase for coarse tasks, gather for fine tasks
//==========================================================================
// allocate Ci and Cx
int64_t cnz = Cp [cnvec] ;
GrB_Info info = GB_bix_alloc (C, cnz, false, false, true, true, Context) ;
if (info != GrB_SUCCESS)
{
// out of memory
return (GrB_OUT_OF_MEMORY) ;
}
int64_t *GB_RESTRICT Ci = C->i ;
GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ;
#if GB_IS_ANY_PAIR_SEMIRING
// TODO: create C as a constant-value matrix.
// ANY_PAIR semiring: result is purely symbolic
int64_t pC ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (pC = 0 ; pC < cnz ; pC++)
{
Cx [pC] = GB_CTYPE_CAST (1, 0) ;
}
// Just a precaution; these variables are not used below. Any attempt
// to access them will lead to a compile error.
#define Cx is not used
#define Hx is not used
// these have been renamed to ANY_PAIR:
// EQ_PAIR
// LAND_PAIR
// LOR_PAIR
// MAX_PAIR
// MIN_PAIR
// TIMES_PAIR
#endif
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (11, ttt) ;
// ttt = omp_get_wtime ( ) ;
bool C_jumbled = false ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \
reduction(||:C_jumbled)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
#if !GB_IS_ANY_PAIR_SEMIRING
GB_CTYPE *GB_RESTRICT Hx = (GB_CTYPE *) TaskList [taskid].Hx ;
#endif
int64_t hash_size = TaskList [taskid].hsize ;
bool use_Gustavson = (hash_size == cvlen) ;
bool task_C_jumbled = false ;
if (taskid < nfine)
{
//------------------------------------------------------------------
// fine task: gather pattern and values
//------------------------------------------------------------------
int64_t kk = TaskList [taskid].vector ;
int team_size = TaskList [taskid].team_size ;
int leader = TaskList [taskid].leader ;
int my_teamid = taskid - leader ;
int64_t pC = Cp [kk] ;
if (use_Gustavson)
{
//--------------------------------------------------------------
// phase5: fine Gustavson task, C=A*B, C<M>=A*B, or C<!M>=A*B
//--------------------------------------------------------------
// Hf [i] == 2 if C(i,j) is an entry in C(:,j)
int8_t *GB_RESTRICT
Hf = (int8_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t cjnz = Cp [kk+1] - pC ;
int64_t istart, iend ;
GB_PARTITION (istart, iend, cvlen, my_teamid, team_size) ;
if (cjnz == cvlen)
{
// C(:,j) is dense
for (int64_t i = istart ; i < iend ; i++)
{
Ci [pC + i] = i ;
}
#if !GB_IS_ANY_PAIR_SEMIRING
// copy Hx [istart:iend-1] into Cx [pC+istart:pC+iend-1]
GB_CIJ_MEMCPY (pC + istart, istart, iend - istart) ;
#endif
}
else
{
// C(:,j) is sparse
pC += TaskList [taskid].my_cjnz ;
for (int64_t i = istart ; i < iend ; i++)
{
if (Hf [i] == 2)
{
GB_CIJ_GATHER (pC, i) ; // Cx [pC] = Hx [i]
Ci [pC++] = i ;
}
}
}
}
else
{
//--------------------------------------------------------------
// phase5: fine hash task, C=A*B, C<M>=A*B, C<!M>=A*B
//--------------------------------------------------------------
// (Hf [hash] & 3) == 2 if C(i,j) is an entry in C(:,j),
// and the index i of the entry is (Hf [hash] >> 2) - 1.
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t mystart, myend ;
GB_PARTITION (mystart, myend, hash_size, my_teamid, team_size) ;
pC += TaskList [taskid].my_cjnz ;
for (int64_t hash = mystart ; hash < myend ; hash++)
{
int64_t hf = Hf [hash] ;
if ((hf & 3) == 2)
{
int64_t i = (hf >> 2) - 1 ; // found C(i,j) in hash
Ci [pC] = i ;
GB_CIJ_GATHER (pC, hash) ; // Cx [pC] = Hx [hash]
pC++ ;
}
}
task_C_jumbled = true ;
}
}
else
{
//------------------------------------------------------------------
// numeric coarse task: compute C(:,kfirst:klast)
//------------------------------------------------------------------
int64_t *GB_RESTRICT
Hf = (int64_t *GB_RESTRICT) TaskList [taskid].Hf ;
int64_t kfirst = TaskList [taskid].start ;
int64_t klast = TaskList [taskid].end ;
int64_t nk = klast - kfirst + 1 ;
int64_t mark = 2*nk + 1 ;
if (use_Gustavson)
{
//--------------------------------------------------------------
// phase5: coarse Gustavson task
//--------------------------------------------------------------
if (M == NULL)
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C=A*B
//----------------------------------------------------------
#if GB_IS_PERFORMANCE_CRITICAL_SEMIRING
#define GB_SAXPY_COARSE_GUSTAVSON_NOMASK_PHASE5
#include "GB_meta16_factory.c"
#undef GB_SAXPY_COARSE_GUSTAVSON_NOMASK_PHASE5
#else
#include "GB_AxB_saxpy3_coarseGus_noM_phase5.c"
#endif
}
else if (mask_is_M)
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C<M>=A*B
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Hf [i] < mark : M(i,j)=0, C(i,j) is ignored.
// Hf [i] == mark : M(i,j)=1, and C(i,j) not yet seen.
// Hf [i] == mark+1 : M(i,j)=1, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_B_j ; // get B(:,j)
#ifdef GB_IDENTITY
if (cjnz == cvlen) // C(:,j) is dense
{
// this requires the monoid identity. It is not
// defined for the generic saxpy3.
GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j)
continue ;
}
#endif
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (64) ; // get first and last in M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
// scatter M(:,j)
GB_SCATTER_M_j (pM_start, pM_end, mark) ;
if (16 * cjnz > cvlen) // C(:,j) is not very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
int64_t hf = Hf [i] ; \
if (hf == mark) \
{ \
/* C(i,j) = A(i,k) * B(k,j) */ \
Hf [i] = mark1 ; /* mark as seen */\
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \
} \
else if (hf == mark1) \
{ \
/* C(i,j) += A(i,k) * B(k,j) */ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j)
}
else // C(:,j) is very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
int64_t hf = Hf [i] ; \
if (hf == mark) \
{ \
/* C(i,j) = A(i,k) * B(k,j) */ \
Hf [i] = mark1 ; /* mark as seen */\
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_WRITE (i, t) ; /* Hx [i] = t */ \
Ci [pC++] = i ; /* C(:,j) pattern */ \
} \
else if (hf == mark1) \
{ \
/* C(i,j) += A(i,k) * B(k,j) */ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
GB_HX_UPDATE (i, t) ;/* Hx [i] += t */ \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_SORT_AND_GATHER_C_j ; // gather into C(:,j)
}
}
}
else
{
//----------------------------------------------------------
// phase5: coarse Gustavson task, C<!M>=A*B
//----------------------------------------------------------
// Since the mask is !M:
// Hf [i] < mark : M(i,j)=0, C(i,j) is not yet seen.
// Hf [i] == mark : M(i,j)=1, so C(i,j) is ignored.
// Hf [i] == mark+1 : M(i,j)=0, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_B_j ; // get B(:,j)
#ifdef GB_IDENTITY
if (cjnz == cvlen) // C(:,j) is dense
{
// this requires the monoid identity. It is not
// defined for the generic saxpy3.
GB_COMPUTE_DENSE_C_j ; // C(:,j) = A*B(:,j)
continue ;
}
#endif
GB_GET_M_j ; // get M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
// scatter M(:,j)
GB_SCATTER_M_j (pM_start, pM_end, mark) ;
if (16 * cjnz > cvlen) // C(:,j) is not very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get i of A(i,j)
int64_t hf = Hf [i] ;
if (hf < mark)
{
// C(i,j) = A(i,k) * B(k,j)
Hf [i] = mark1 ; // mark as seen
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_WRITE (i, t) ; // Hx [i] = t
}
else if (hf == mark1)
{
// C(i,j) += A(i,k) * B(k,j)
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_UPDATE (i, t) ;// Hx [i] += t
}
}
}
GB_GATHER_ALL_C_j(mark1) ; // gather into C(:,j)
}
else // C(:,j) is very sparse
{
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get i of A(i,j)
int64_t hf = Hf [i] ;
if (hf < mark)
{
// C(i,j) = A(i,k) * B(k,j)
Hf [i] = mark1 ; // mark as seen
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_WRITE (i, t) ; // Hx [i] = t
Ci [pC++] = i ; // create C(:,j) pattern
}
else if (hf == mark1)
{
// C(i,j) += A(i,k) * B(k,j)
GB_MULT_A_ik_B_kj ; // t =A(i,k)*B(k,j)
GB_HX_UPDATE (i, t) ; // Hx [i] += t
}
}
}
GB_SORT_AND_GATHER_C_j ; // gather into C(:,j)
}
}
}
}
else
{
//--------------------------------------------------------------
// phase5: coarse hash task
//--------------------------------------------------------------
int64_t *GB_RESTRICT Hi = TaskList [taskid].Hi ;
int64_t hash_bits = (hash_size-1) ;
if (M == NULL || ignore_mask)
{
//----------------------------------------------------------
// phase5: coarse hash task, C=A*B
//----------------------------------------------------------
// no mask present, or mask ignored (see below)
#undef GB_CHECK_MASK_ij
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
}
else if (mask_is_M)
{
//----------------------------------------------------------
// phase5: coarse hash task, C<M>=A*B
//----------------------------------------------------------
if (M_dense_in_place)
{
ASSERT (!Mask_struct || M_is_bitmap) ;
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (!mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (!mij) continue ;
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
}
}
else
{
//----------------------------------------------------------
// M is sparse and scattered into Hf
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Let h = Hi [hash] and f = Hf [hash].
// f < mark : M(i,j)=0, C(i,j) is ignored.
// h == i, f == mark : M(i,j)=1, and C(i,j) not yet seen.
// h == i, f == mark+1 : M(i,j)=1, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_M_j ; // get M(:,j)
GB_GET_M_j_RANGE (64) ; // get 1st & last in M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
GB_HASH_M_j ; // hash M(:,j)
GB_GET_B_j ; // get B(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
#define GB_IKJ \
{ \
for (GB_HASH (i)) /* find i in hash */ \
{ \
int64_t f = Hf [hash] ; \
if (f < mark) break ; /* M(i,j)=0, ignore*/\
if (Hi [hash] == i) \
{ \
GB_MULT_A_ik_B_kj ; /* t = aik*bkj */ \
if (f == mark) /* if true, i is new */ \
{ \
/* C(i,j) is new */ \
Hf [hash] = mark1 ; /* mark seen */\
GB_HX_WRITE (hash, t) ;/*Hx[.]=t */\
Ci [pC++] = i ; \
} \
else \
{ \
/* C(i,j) has been seen; update */ \
GB_HX_UPDATE (hash, t) ; \
} \
break ; \
} \
} \
}
GB_SCAN_M_j_OR_A_k (A_ok_for_binary_search) ;
#undef GB_IKJ
}
GB_SORT_AND_GATHER_HASHED_C_j (mark1) ;
}
}
}
else
{
//----------------------------------------------------------
// phase5: coarse hash task, C<!M>=A*B
//----------------------------------------------------------
if (M_dense_in_place)
{
//------------------------------------------------------
// M(:,j) is dense. M is not scattered into Hf.
//------------------------------------------------------
if (Mask_struct && !M_is_bitmap)
{
// structural mask, complemented, not bitmap.
// No work to do; C is empty.
continue ;
}
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : (Mjx [i] != 0)) ; \
if (mij) continue ;
switch (msize)
{
default:
case 1 :
#define M_TYPE uint8_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 2 :
#define M_TYPE uint16_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 4 :
#define M_TYPE uint32_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 8 :
#define M_TYPE uint64_t
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
case 16 :
#define M_TYPE uint64_t
#define M_SIZE 2
#undef GB_CHECK_MASK_ij
#define GB_CHECK_MASK_ij \
bool mij = \
(M_is_bitmap ? Mjb [i] : 1) && \
(Mask_struct ? 1 : \
(Mjx [2*i] != 0) || \
(Mjx [2*i+1] != 0)) ; \
if (mij) continue ;
#include "GB_AxB_saxpy3_coarseHash_phase5.c"
break ;
}
}
else
{
//----------------------------------------------------------
// M is sparse and scattered into Hf
//----------------------------------------------------------
// Initially, Hf [...] < mark for all of Hf.
// Let h = Hi [hash] and f = Hf [hash].
// f < mark: unoccupied, M(i,j)=0, and C(i,j) not yet seen.
// h == i, f == mark : M(i,j)=1. C(i,j) ignored.
// h == i, f == mark+1 : M(i,j)=0, and C(i,j) has been seen.
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t pC = Cp [kk] ;
int64_t cjnz = Cp [kk+1] - pC ;
if (cjnz == 0) continue ; // nothing to do
GB_GET_M_j ; // get M(:,j)
mark += 2 ;
int64_t mark1 = mark+1 ;
GB_HASH_M_j ; // hash M(:,j)
GB_GET_B_j ; // get B(:,j)
for ( ; pB < pB_end ; pB++) // scan B(:,j)
{
GB_GET_B_kj_INDEX ; // get index k of B(k,j)
GB_GET_A_k ; // get A(:,k)
if (aknz == 0) continue ;
GB_GET_B_kj ; // bkj = B(k,j)
// scan A(:,k)
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
GB_GET_A_ik_INDEX ; // get index i of A(i,j)
for (GB_HASH (i)) // find i in hash
{
int64_t f = Hf [hash] ;
if (f < mark) // if true, i is new
{
// C(i,j) is new
Hf [hash] = mark1 ; // mark C(i,j) seen
Hi [hash] = i ;
GB_MULT_A_ik_B_kj ; // t = A(i,k)*B(k,j)
GB_HX_WRITE (hash, t) ; // Hx [hash] = t
Ci [pC++] = i ;
break ;
}
if (Hi [hash] == i)
{
if (f == mark1)
{
// C(i,j) has been seen; update it.
GB_MULT_A_ik_B_kj ;//t=A(i,k)*B(k,j)
GB_HX_UPDATE (hash, t) ;//Hx[ ] += t
}
break ;
}
}
}
}
GB_SORT_AND_GATHER_HASHED_C_j (mark1) ;
}
}
}
}
}
C_jumbled = C_jumbled || task_C_jumbled ;
}
//--------------------------------------------------------------------------
// log the state of C->jumbled
//--------------------------------------------------------------------------
C->jumbled = C_jumbled ; // C is jumbled if any task left it jumbled
// ttt = omp_get_wtime ( ) - ttt ;
// GB_Global_timing_add (12, ttt) ;
}
#undef Cx
#undef Hx
|
Example_target_reverse_offload.7.c | /*
* @@name: target_reverse_offload.1c
* @@type: C
* @@compilable: yes
* @@linkable: yes
* @@expect: success
* @@version: omp_5.0
*/
#include <stdio.h>
#include <stdlib.h>
#define N 100
#pragma omp requires reverse_offload
void error_handler(int wrong_value, int index)
{
printf(" Error in offload: A[%d]=%d\n", index,wrong_value);
printf(" Expecting: A[i ]=i\n");
exit(1);
// output: Error in offload: A[99]=-1
// Expecting: A[i ]=i
}
#pragma omp declare target device_type(host) to(error_handler)
int main()
{
int A[N];
for (int i=0; i<N; i++) A[i] = i;
A[N-1]=-1;
#pragma omp target map(A)
{
for (int i=0; i<N; i++)
{
if (A[i] != i)
{
#pragma omp target device(ancestor: 1) map(always,to: A[i:1])
error_handler(A[i], i);
}
}
}
return 0;
}
|
GB_unop__abs_uint64_uint64.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop_apply__abs_uint64_uint64
// op(A') function: GB_unop_tran__abs_uint64_uint64
// C type: uint64_t
// A type: uint64_t
// cast: uint64_t cij = aij
// unaryop: cij = aij
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint64_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint64_t z = aij ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
uint64_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint64_t z = aij ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ABS || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_apply__abs_uint64_uint64
(
uint64_t *Cx, // Cx and Ax may be aliased
const uint64_t *Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
uint64_t aij = Ax [p] ;
uint64_t z = aij ;
Cx [p] = z ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop_tran__abs_uint64_uint64
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *GB_RESTRICT *Rowcounts,
GBI_single_iterator Iter,
const int64_t *GB_RESTRICT A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unaryop__minv_uint16_uint64.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__minv_uint16_uint64
// op(A') function: GB_tran__minv_uint16_uint64
// C type: uint16_t
// A type: uint64_t
// cast: uint16_t cij = (uint16_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 16)
#define GB_ATYPE \
uint64_t
#define GB_CTYPE \
uint16_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint64_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IMINV_UNSIGNED (x, 16) ;
// casting
#define GB_CASTING(z, x) \
uint16_t z = (uint16_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT16 || GxB_NO_UINT64)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint16_uint64
(
uint16_t *restrict Cx,
const uint64_t *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__minv_uint16_uint64
(
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
|
stencil_opt3.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "malloc2D.h"
#include "timer.h"
#define SWAP_PTR(xnew,xold,xtmp) (xtmp=xnew, xnew=xold, xold=xtmp)
int main(int argc, char *argv[])
{
#pragma omp parallel
if (omp_get_thread_num() == 0) printf("Running with %d thread(s)\n",omp_get_num_threads());
struct timespec tstart_init, tstart_flush, tstart_stencil, tstart_total;
double init_time, flush_time, stencil_time, total_time;
int imax=2002, jmax = 2002;
double** xtmp;
double** x = malloc2D(jmax, imax);
double** xnew = malloc2D(jmax, imax);
int *flush = (int *)malloc(jmax*imax*sizeof(int)*40);
cpu_timer_start(&tstart_total);
cpu_timer_start(&tstart_init);
#pragma omp parallel for
for (int j = 0; j < jmax; j++){
for (int i = 0; i < imax; i++){
xnew[j][i] = 0.0;
x[j][i] = 5.0;
}
}
#pragma omp parallel for
for (int j = jmax/2 - 5; j < jmax/2 + 5; j++){
for (int i = imax/2 - 5; i < imax/2 -1; i++){
x[j][i] = 400.0;
}
}
init_time += cpu_timer_stop(tstart_init);
for (int iter = 0; iter < 10000; iter++){
cpu_timer_start(&tstart_flush);
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
#pragma omp for nowait
for (int l = 1; l < jmax*imax*4; l++){
flush[l] = 1.0;
}
if (thread_id == 0){
flush_time += cpu_timer_stop(tstart_flush);
cpu_timer_start(&tstart_stencil);
}
#pragma omp for
for (int j = 1; j < jmax-1; j++){
for (int i = 1; i < imax-1; i++){
xnew[j][i] = ( x[j][i] + x[j][i-1] + x[j][i+1] + x[j-1][i] + x[j+1][i] )/5.0;
}
}
} // end omp parallel
stencil_time += cpu_timer_stop(tstart_stencil);
SWAP_PTR(xnew, x, xtmp);
if (iter%1000 == 0) printf("Iter %d\n",iter);
}
total_time += cpu_timer_stop(tstart_total);
printf("Timing is init %f flush %f stencil %f total %f\n",init_time,flush_time,stencil_time,total_time);
free(x);
free(xnew);
free(flush);
}
|
pr27388-2.c | /* PR middle-end/27388 */
/* { dg-do compile } */
/* { dg-options "-fopenmp -fdump-tree-omplower" } */
extern void baz (int);
void
foo (void)
{
int i;
#pragma omp parallel for shared (i)
for (i = 0; i < 2; i++)
baz (i);
}
void
bar (void)
{
int j = 0;
#pragma omp parallel shared (j)
{
j++;
#pragma omp for
for (j = 0; j < 2; j++)
baz (j);
}
}
/* { dg-final { scan-tree-dump-times "shared\\\(i\\\)\[^\\n\]*private\\\(i\\\)" 0 "omplower" } } */
/* { dg-final { scan-tree-dump-times "private\\\(i\\\)\[^\\n\]*shared\\\(i\\\)" 0 "omplower" } } */
/* { dg-final { scan-tree-dump-times "omp for\[^\\n\]*private\\\(i\\\)" 1 "omplower" } } */
/* { dg-final { scan-tree-dump-times "shared\\\(j\\\)\[^\\n\]*private\\\(j\\\)" 0 "omplower" } } */
/* { dg-final { scan-tree-dump-times "private\\\(j\\\)\[^\\n\]*shared\\\(j\\\)" 0 "omplower" } } */
/* { dg-final { scan-tree-dump-times "omp for\[^\\n\]*private\\\(j\\\)" 1 "omplower" } } */
|
lbm.c | /* $Id: lbm.c,v 1.6 2004/05/03 08:23:51 pohlt Exp $ */
/*############################################################################*/
#include "lbm.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
/*############################################################################*/
#define DFL1 (1.0/ 3.0)
#define DFL2 (1.0/18.0)
#define DFL3 (1.0/36.0)
extern size_t gridSize;
extern size_t marginSize;
#define GRID_SIZE (SIZE_Z*SIZE_Y*SIZE_X*N_CELL_ENTRIES)
/*############################################################################*/
void LBM_allocateGrid( double** ptr, double ** org_ptr ) {
const size_t margin = 2*SIZE_X*SIZE_Y*N_CELL_ENTRIES,
size = sizeof( LBM_Grid ) + 2*margin*sizeof( double );
*ptr = (double*) malloc( size );
if( ! *ptr ) {
printf( "LBM_allocateGrid: could not allocate %.1f MByte\n",
size / (1024.0*1024.0) );
exit( 1 );
}
*org_ptr = *ptr;
*ptr += margin;
marginSize = margin;
gridSize= size/sizeof(double);
}
/*############################################################################*/
void LBM_freeGrid( double** ptr ) {
const size_t margin = 2*SIZE_X*SIZE_Y*N_CELL_ENTRIES;
free( *ptr-margin );
*ptr = NULL;
}
/*############################################################################*/
void LBM_initializeGrid( LBM_Grid grid ) {
SWEEP_VAR
/*voption indep*/
SWEEP_START( 0, 0, -2, 0, 0, SIZE_Z+2 )
LOCAL( grid, C ) = DFL1;
LOCAL( grid, N ) = DFL2;
LOCAL( grid, S ) = DFL2;
LOCAL( grid, E ) = DFL2;
LOCAL( grid, W ) = DFL2;
LOCAL( grid, T ) = DFL2;
LOCAL( grid, B ) = DFL2;
LOCAL( grid, NE ) = DFL3;
LOCAL( grid, NW ) = DFL3;
LOCAL( grid, SE ) = DFL3;
LOCAL( grid, SW ) = DFL3;
LOCAL( grid, NT ) = DFL3;
LOCAL( grid, NB ) = DFL3;
LOCAL( grid, ST ) = DFL3;
LOCAL( grid, SB ) = DFL3;
LOCAL( grid, ET ) = DFL3;
LOCAL( grid, EB ) = DFL3;
LOCAL( grid, WT ) = DFL3;
LOCAL( grid, WB ) = DFL3;
CLEAR_ALL_FLAGS_SWEEP( grid );
SWEEP_END
}
/*############################################################################*/
void LBM_swapGrids( LBM_GridPtr* grid1, LBM_GridPtr* grid2 ) {
LBM_GridPtr aux = *grid1;
*grid1 = *grid2;
*grid2 = aux;
}
/*############################################################################*/
void LBM_loadObstacleFile( LBM_Grid grid, const char* filename ) {
int x, y, z;
FILE* file = fopen( filename, "rb" );
for( z = 0; z < SIZE_Z; z++ ) {
for( y = 0; y < SIZE_Y; y++ ) {
for( x = 0; x < SIZE_X; x++ ) {
if( fgetc( file ) != '.' ) SET_FLAG( grid, x, y, z, OBSTACLE );
}
fgetc( file );
}
fgetc( file );
}
fclose( file );
}
/*############################################################################*/
void LBM_initializeSpecialCellsForLDC( LBM_Grid grid ) {
int x, y, z;
/*voption indep*/
for( z = -2; z < SIZE_Z+2; z++ ) {
for( y = 0; y < SIZE_Y; y++ ) {
for( x = 0; x < SIZE_X; x++ ) {
if( x == 0 || x == SIZE_X-1 ||
y == 0 || y == SIZE_Y-1 ||
z == 0 || z == SIZE_Z-1 ) {
SET_FLAG( grid, x, y, z, OBSTACLE );
}
else {
if( (z == 1 || z == SIZE_Z-2) &&
x > 1 && x < SIZE_X-2 &&
y > 1 && y < SIZE_Y-2 ) {
SET_FLAG( grid, x, y, z, ACCEL );
}
}
}
}
}
}
/*############################################################################*/
void LBM_initializeSpecialCellsForChannel( LBM_Grid grid ) {
int x, y, z;
/*voption indep*/
for( z = -2; z < SIZE_Z+2; z++ ) {
for( y = 0; y < SIZE_Y; y++ ) {
for( x = 0; x < SIZE_X; x++ ) {
if( x == 0 || x == SIZE_X-1 ||
y == 0 || y == SIZE_Y-1 ) {
SET_FLAG( grid, x, y, z, OBSTACLE );
if( (z == 0 || z == SIZE_Z-1) &&
! TEST_FLAG( grid, x, y, z, OBSTACLE ))
SET_FLAG( grid, x, y, z, IN_OUT_FLOW );
}
}
}
}
}
/*############################################################################*/
void LBM_performStreamCollide( LBM_Grid srcGrid, LBM_Grid dstGrid ) {
SWEEP_VAR
double ux, uy, uz, u2, rho;
/*voption indep*/
#if defined(SPEC_NEED_EXPLICIT_SIZE)
#pragma omp target map(alloc:srcGrid[0:GRID_SIZE]), map(alloc:dstGrid[0:GRID_SIZE])
#else
#pragma omp target map(alloc:srcGrid[:]), map(alloc:dstGrid[:])
#endif
{
#pragma omp teams distribute parallel for simd private( ux, uy, uz, u2, rho )
SWEEP_START( 0, 0, 0, 0, 0, SIZE_Z )
if( TEST_FLAG_SWEEP( srcGrid, OBSTACLE )) {
DST_C ( dstGrid ) = SRC_C ( srcGrid );
DST_S ( dstGrid ) = SRC_N ( srcGrid );
DST_N ( dstGrid ) = SRC_S ( srcGrid );
DST_W ( dstGrid ) = SRC_E ( srcGrid );
DST_E ( dstGrid ) = SRC_W ( srcGrid );
DST_B ( dstGrid ) = SRC_T ( srcGrid );
DST_T ( dstGrid ) = SRC_B ( srcGrid );
DST_SW( dstGrid ) = SRC_NE( srcGrid );
DST_SE( dstGrid ) = SRC_NW( srcGrid );
DST_NW( dstGrid ) = SRC_SE( srcGrid );
DST_NE( dstGrid ) = SRC_SW( srcGrid );
DST_SB( dstGrid ) = SRC_NT( srcGrid );
DST_ST( dstGrid ) = SRC_NB( srcGrid );
DST_NB( dstGrid ) = SRC_ST( srcGrid );
DST_NT( dstGrid ) = SRC_SB( srcGrid );
DST_WB( dstGrid ) = SRC_ET( srcGrid );
DST_WT( dstGrid ) = SRC_EB( srcGrid );
DST_EB( dstGrid ) = SRC_WT( srcGrid );
DST_ET( dstGrid ) = SRC_WB( srcGrid );
continue;
}
rho = + SRC_C ( srcGrid ) + SRC_N ( srcGrid )
+ SRC_S ( srcGrid ) + SRC_E ( srcGrid )
+ SRC_W ( srcGrid ) + SRC_T ( srcGrid )
+ SRC_B ( srcGrid ) + SRC_NE( srcGrid )
+ SRC_NW( srcGrid ) + SRC_SE( srcGrid )
+ SRC_SW( srcGrid ) + SRC_NT( srcGrid )
+ SRC_NB( srcGrid ) + SRC_ST( srcGrid )
+ SRC_SB( srcGrid ) + SRC_ET( srcGrid )
+ SRC_EB( srcGrid ) + SRC_WT( srcGrid )
+ SRC_WB( srcGrid );
ux = + SRC_E ( srcGrid ) - SRC_W ( srcGrid )
+ SRC_NE( srcGrid ) - SRC_NW( srcGrid )
+ SRC_SE( srcGrid ) - SRC_SW( srcGrid )
+ SRC_ET( srcGrid ) + SRC_EB( srcGrid )
- SRC_WT( srcGrid ) - SRC_WB( srcGrid );
uy = + SRC_N ( srcGrid ) - SRC_S ( srcGrid )
+ SRC_NE( srcGrid ) + SRC_NW( srcGrid )
- SRC_SE( srcGrid ) - SRC_SW( srcGrid )
+ SRC_NT( srcGrid ) + SRC_NB( srcGrid )
- SRC_ST( srcGrid ) - SRC_SB( srcGrid );
uz = + SRC_T ( srcGrid ) - SRC_B ( srcGrid )
+ SRC_NT( srcGrid ) - SRC_NB( srcGrid )
+ SRC_ST( srcGrid ) - SRC_SB( srcGrid )
+ SRC_ET( srcGrid ) - SRC_EB( srcGrid )
+ SRC_WT( srcGrid ) - SRC_WB( srcGrid );
ux /= rho;
uy /= rho;
uz /= rho;
if( TEST_FLAG_SWEEP( srcGrid, ACCEL )) {
ux = 0.005;
uy = 0.002;
uz = 0.000;
}
u2 = 1.5 * (ux*ux + uy*uy + uz*uz);
DST_C ( dstGrid ) = (1.0-OMEGA)*SRC_C ( srcGrid ) + DFL1*OMEGA*rho*(1.0 - u2);
DST_N ( dstGrid ) = (1.0-OMEGA)*SRC_N ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + uy*(4.5*uy + 3.0) - u2);
DST_S ( dstGrid ) = (1.0-OMEGA)*SRC_S ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + uy*(4.5*uy - 3.0) - u2);
DST_E ( dstGrid ) = (1.0-OMEGA)*SRC_E ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + ux*(4.5*ux + 3.0) - u2);
DST_W ( dstGrid ) = (1.0-OMEGA)*SRC_W ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + ux*(4.5*ux - 3.0) - u2);
DST_T ( dstGrid ) = (1.0-OMEGA)*SRC_T ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + uz*(4.5*uz + 3.0) - u2);
DST_B ( dstGrid ) = (1.0-OMEGA)*SRC_B ( srcGrid ) + DFL2*OMEGA*rho*(1.0 + uz*(4.5*uz - 3.0) - u2);
DST_NE( dstGrid ) = (1.0-OMEGA)*SRC_NE( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+ux+uy)*(4.5*(+ux+uy) + 3.0) - u2);
DST_NW( dstGrid ) = (1.0-OMEGA)*SRC_NW( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-ux+uy)*(4.5*(-ux+uy) + 3.0) - u2);
DST_SE( dstGrid ) = (1.0-OMEGA)*SRC_SE( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+ux-uy)*(4.5*(+ux-uy) + 3.0) - u2);
DST_SW( dstGrid ) = (1.0-OMEGA)*SRC_SW( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-ux-uy)*(4.5*(-ux-uy) + 3.0) - u2);
DST_NT( dstGrid ) = (1.0-OMEGA)*SRC_NT( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+uy+uz)*(4.5*(+uy+uz) + 3.0) - u2);
DST_NB( dstGrid ) = (1.0-OMEGA)*SRC_NB( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+uy-uz)*(4.5*(+uy-uz) + 3.0) - u2);
DST_ST( dstGrid ) = (1.0-OMEGA)*SRC_ST( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-uy+uz)*(4.5*(-uy+uz) + 3.0) - u2);
DST_SB( dstGrid ) = (1.0-OMEGA)*SRC_SB( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-uy-uz)*(4.5*(-uy-uz) + 3.0) - u2);
DST_ET( dstGrid ) = (1.0-OMEGA)*SRC_ET( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+ux+uz)*(4.5*(+ux+uz) + 3.0) - u2);
DST_EB( dstGrid ) = (1.0-OMEGA)*SRC_EB( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (+ux-uz)*(4.5*(+ux-uz) + 3.0) - u2);
DST_WT( dstGrid ) = (1.0-OMEGA)*SRC_WT( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-ux+uz)*(4.5*(-ux+uz) + 3.0) - u2);
DST_WB( dstGrid ) = (1.0-OMEGA)*SRC_WB( srcGrid ) + DFL3*OMEGA*rho*(1.0 + (-ux-uz)*(4.5*(-ux-uz) + 3.0) - u2);
SWEEP_END
} // end target region
}
/*############################################################################*/
void LBM_handleInOutFlow( LBM_Grid srcGrid ) {
double ux , uy , uz , rho ,
ux1, uy1, uz1, rho1,
ux2, uy2, uz2, rho2,
u2, px, py;
SWEEP_VAR
/* inflow */
/*voption indep*/
#ifdef DBG
printf("srcGrid = %x, %d\n",srcGrid, GRID_SIZE);
#endif
#if defined(SPEC_NEED_EXPLICIT_SIZE)
#pragma omp target data map(alloc:srcGrid[0:GRID_SIZE])
#else
#pragma omp target data map(alloc:srcGrid[:])
#endif
{
#pragma omp target map(srcGrid[:0])
#pragma omp teams distribute parallel for simd private( ux, uy, uz, rho, ux1, uy1, uz1, rho1, \
ux2, uy2, uz2, rho2, u2, px, py )
SWEEP_START( 0, 0, 0, 0, 0, 1 )
rho1 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, C ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, N )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, S ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, E )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, W ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, T )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, B ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, NE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, NW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, SE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, SW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, NT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, NB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, ST )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, SB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, ET )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, EB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, WT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 1, WB );
rho2 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, C ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, N )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, S ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, E )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, W ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, T )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, B ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, NE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, NW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, SE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, SW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, NT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, NB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, ST )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, SB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, ET )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, EB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, WT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, 2, WB );
rho = 2.0*rho1 - rho2;
px = (SWEEP_X / (0.5*(SIZE_X-1))) - 1.0;
py = (SWEEP_Y / (0.5*(SIZE_Y-1))) - 1.0;
ux = 0.00;
uy = 0.00;
uz = 0.01 * (1.0-px*px) * (1.0-py*py);
u2 = 1.5 * (ux*ux + uy*uy + uz*uz);
LOCAL( srcGrid, C ) = DFL1*rho*(1.0 - u2);
LOCAL( srcGrid, N ) = DFL2*rho*(1.0 + uy*(4.5*uy + 3.0) - u2);
LOCAL( srcGrid, S ) = DFL2*rho*(1.0 + uy*(4.5*uy - 3.0) - u2);
LOCAL( srcGrid, E ) = DFL2*rho*(1.0 + ux*(4.5*ux + 3.0) - u2);
LOCAL( srcGrid, W ) = DFL2*rho*(1.0 + ux*(4.5*ux - 3.0) - u2);
LOCAL( srcGrid, T ) = DFL2*rho*(1.0 + uz*(4.5*uz + 3.0) - u2);
LOCAL( srcGrid, B ) = DFL2*rho*(1.0 + uz*(4.5*uz - 3.0) - u2);
LOCAL( srcGrid, NE) = DFL3*rho*(1.0 + (+ux+uy)*(4.5*(+ux+uy) + 3.0) - u2);
LOCAL( srcGrid, NW) = DFL3*rho*(1.0 + (-ux+uy)*(4.5*(-ux+uy) + 3.0) - u2);
LOCAL( srcGrid, SE) = DFL3*rho*(1.0 + (+ux-uy)*(4.5*(+ux-uy) + 3.0) - u2);
LOCAL( srcGrid, SW) = DFL3*rho*(1.0 + (-ux-uy)*(4.5*(-ux-uy) + 3.0) - u2);
LOCAL( srcGrid, NT) = DFL3*rho*(1.0 + (+uy+uz)*(4.5*(+uy+uz) + 3.0) - u2);
LOCAL( srcGrid, NB) = DFL3*rho*(1.0 + (+uy-uz)*(4.5*(+uy-uz) + 3.0) - u2);
LOCAL( srcGrid, ST) = DFL3*rho*(1.0 + (-uy+uz)*(4.5*(-uy+uz) + 3.0) - u2);
LOCAL( srcGrid, SB) = DFL3*rho*(1.0 + (-uy-uz)*(4.5*(-uy-uz) + 3.0) - u2);
LOCAL( srcGrid, ET) = DFL3*rho*(1.0 + (+ux+uz)*(4.5*(+ux+uz) + 3.0) - u2);
LOCAL( srcGrid, EB) = DFL3*rho*(1.0 + (+ux-uz)*(4.5*(+ux-uz) + 3.0) - u2);
LOCAL( srcGrid, WT) = DFL3*rho*(1.0 + (-ux+uz)*(4.5*(-ux+uz) + 3.0) - u2);
LOCAL( srcGrid, WB) = DFL3*rho*(1.0 + (-ux-uz)*(4.5*(-ux-uz) + 3.0) - u2);
SWEEP_END
#pragma omp target map(srcGrid[:0])
#pragma omp teams distribute parallel for simd private( ux, uy, uz, rho, ux1, uy1, uz1, rho1, \
ux2, uy2, uz2, rho2, u2, px, py )
SWEEP_START( 0, 0, SIZE_Z-1, 0, 0, SIZE_Z )
rho1 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, C ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, N )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, S ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, E )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, W ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, T )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, B ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ST )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ET )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, EB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WB );
ux1 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, E ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, W )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ET ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, EB )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WB );
uy1 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, N ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, S )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NE ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NW )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NT ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NB )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ST ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SB );
uz1 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, T ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, B )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, NB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ST ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, SB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, ET ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, EB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -1, WB );
ux1 /= rho1;
uy1 /= rho1;
uz1 /= rho1;
rho2 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, C ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, N )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, S ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, E )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, W ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, T )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, B ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SE )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SW ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ST )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ET )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, EB ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WT )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WB );
ux2 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, E ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, W )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ET ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, EB )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WB );
uy2 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, N ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, S )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NE ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NW )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SE ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SW )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NT ) + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NB )
- GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ST ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SB );
uz2 = + GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, T ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, B )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, NB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ST ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, SB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, ET ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, EB )
+ GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WT ) - GRID_ENTRY_SWEEP( srcGrid, 0, 0, -2, WB );
ux2 /= rho2;
uy2 /= rho2;
uz2 /= rho2;
rho = 1.0;
ux = 2*ux1 - ux2;
uy = 2*uy1 - uy2;
uz = 2*uz1 - uz2;
u2 = 1.5 * (ux*ux + uy*uy + uz*uz);
LOCAL( srcGrid, C ) = DFL1*rho*(1.0 - u2);
LOCAL( srcGrid, N ) = DFL2*rho*(1.0 + uy*(4.5*uy + 3.0) - u2);
LOCAL( srcGrid, S ) = DFL2*rho*(1.0 + uy*(4.5*uy - 3.0) - u2);
LOCAL( srcGrid, E ) = DFL2*rho*(1.0 + ux*(4.5*ux + 3.0) - u2);
LOCAL( srcGrid, W ) = DFL2*rho*(1.0 + ux*(4.5*ux - 3.0) - u2);
LOCAL( srcGrid, T ) = DFL2*rho*(1.0 + uz*(4.5*uz + 3.0) - u2);
LOCAL( srcGrid, B ) = DFL2*rho*(1.0 + uz*(4.5*uz - 3.0) - u2);
LOCAL( srcGrid, NE) = DFL3*rho*(1.0 + (+ux+uy)*(4.5*(+ux+uy) + 3.0) - u2);
LOCAL( srcGrid, NW) = DFL3*rho*(1.0 + (-ux+uy)*(4.5*(-ux+uy) + 3.0) - u2);
LOCAL( srcGrid, SE) = DFL3*rho*(1.0 + (+ux-uy)*(4.5*(+ux-uy) + 3.0) - u2);
LOCAL( srcGrid, SW) = DFL3*rho*(1.0 + (-ux-uy)*(4.5*(-ux-uy) + 3.0) - u2);
LOCAL( srcGrid, NT) = DFL3*rho*(1.0 + (+uy+uz)*(4.5*(+uy+uz) + 3.0) - u2);
LOCAL( srcGrid, NB) = DFL3*rho*(1.0 + (+uy-uz)*(4.5*(+uy-uz) + 3.0) - u2);
LOCAL( srcGrid, ST) = DFL3*rho*(1.0 + (-uy+uz)*(4.5*(-uy+uz) + 3.0) - u2);
LOCAL( srcGrid, SB) = DFL3*rho*(1.0 + (-uy-uz)*(4.5*(-uy-uz) + 3.0) - u2);
LOCAL( srcGrid, ET) = DFL3*rho*(1.0 + (+ux+uz)*(4.5*(+ux+uz) + 3.0) - u2);
LOCAL( srcGrid, EB) = DFL3*rho*(1.0 + (+ux-uz)*(4.5*(+ux-uz) + 3.0) - u2);
LOCAL( srcGrid, WT) = DFL3*rho*(1.0 + (-ux+uz)*(4.5*(-ux+uz) + 3.0) - u2);
LOCAL( srcGrid, WB) = DFL3*rho*(1.0 + (-ux-uz)*(4.5*(-ux-uz) + 3.0) - u2);
SWEEP_END
}// end target data region
}
/*############################################################################*/
void LBM_showGridStatistics( LBM_Grid grid ) {
int nObstacleCells = 0,
nAccelCells = 0,
nFluidCells = 0;
double ux, uy, uz;
double minU2 = 1e+30, maxU2 = -1e+30, u2;
double minRho = 1e+30, maxRho = -1e+30, rho;
double mass = 0;
SWEEP_VAR
SWEEP_START( 0, 0, 0, 0, 0, SIZE_Z )
rho = + LOCAL( grid, C ) + LOCAL( grid, N )
+ LOCAL( grid, S ) + LOCAL( grid, E )
+ LOCAL( grid, W ) + LOCAL( grid, T )
+ LOCAL( grid, B ) + LOCAL( grid, NE )
+ LOCAL( grid, NW ) + LOCAL( grid, SE )
+ LOCAL( grid, SW ) + LOCAL( grid, NT )
+ LOCAL( grid, NB ) + LOCAL( grid, ST )
+ LOCAL( grid, SB ) + LOCAL( grid, ET )
+ LOCAL( grid, EB ) + LOCAL( grid, WT )
+ LOCAL( grid, WB );
if( rho < minRho ) minRho = rho;
if( rho > maxRho ) maxRho = rho;
mass += rho;
if( TEST_FLAG_SWEEP( grid, OBSTACLE )) {
nObstacleCells++;
}
else {
if( TEST_FLAG_SWEEP( grid, ACCEL ))
nAccelCells++;
else
nFluidCells++;
ux = + LOCAL( grid, E ) - LOCAL( grid, W )
+ LOCAL( grid, NE ) - LOCAL( grid, NW )
+ LOCAL( grid, SE ) - LOCAL( grid, SW )
+ LOCAL( grid, ET ) + LOCAL( grid, EB )
- LOCAL( grid, WT ) - LOCAL( grid, WB );
uy = + LOCAL( grid, N ) - LOCAL( grid, S )
+ LOCAL( grid, NE ) + LOCAL( grid, NW )
- LOCAL( grid, SE ) - LOCAL( grid, SW )
+ LOCAL( grid, NT ) + LOCAL( grid, NB )
- LOCAL( grid, ST ) - LOCAL( grid, SB );
uz = + LOCAL( grid, T ) - LOCAL( grid, B )
+ LOCAL( grid, NT ) - LOCAL( grid, NB )
+ LOCAL( grid, ST ) - LOCAL( grid, SB )
+ LOCAL( grid, ET ) - LOCAL( grid, EB )
+ LOCAL( grid, WT ) - LOCAL( grid, WB );
u2 = (ux*ux + uy*uy + uz*uz) / (rho*rho);
if( u2 < minU2 ) minU2 = u2;
if( u2 > maxU2 ) maxU2 = u2;
}
SWEEP_END
printf( "LBM_showGridStatistics:\n"
"\tnObstacleCells: %7i nAccelCells: %7i nFluidCells: %7i\n"
"\tminRho: %8.4f maxRho: %8.4f mass: %e\n"
"\tminU: %e maxU: %e\n\n",
nObstacleCells, nAccelCells, nFluidCells,
minRho, maxRho, mass,
sqrt( minU2 ), sqrt( maxU2 ) );
}
/*############################################################################*/
static void storeValue( FILE* file, OUTPUT_PRECISION* v ) {
const int litteBigEndianTest = 1;
if( (*((unsigned char*) &litteBigEndianTest)) == 0 ) { /* big endian */
const char* vPtr = (char*) v;
char buffer[sizeof( OUTPUT_PRECISION )];
int i;
for (i = 0; i < sizeof( OUTPUT_PRECISION ); i++)
buffer[i] = vPtr[sizeof( OUTPUT_PRECISION ) - i - 1];
fwrite( buffer, sizeof( OUTPUT_PRECISION ), 1, file );
}
else { /* little endian */
fwrite( v, sizeof( OUTPUT_PRECISION ), 1, file );
}
}
/*############################################################################*/
static void loadValue( FILE* file, OUTPUT_PRECISION* v ) {
const int litteBigEndianTest = 1;
if( (*((unsigned char*) &litteBigEndianTest)) == 0 ) { /* big endian */
char* vPtr = (char*) v;
char buffer[sizeof( OUTPUT_PRECISION )];
int i;
fread( buffer, sizeof( OUTPUT_PRECISION ), 1, file );
for (i = 0; i < sizeof( OUTPUT_PRECISION ); i++)
vPtr[i] = buffer[sizeof( OUTPUT_PRECISION ) - i - 1];
}
else { /* little endian */
fread( v, sizeof( OUTPUT_PRECISION ), 1, file );
}
}
/*############################################################################*/
void LBM_storeVelocityField( LBM_Grid grid, const char* filename,
const int binary ) {
int x, y, z;
OUTPUT_PRECISION rho, ux, uy, uz;
FILE* file = fopen( filename, (binary ? "wb" : "w") );
for( z = 0; z < SIZE_Z; z++ ) {
for( y = 0; y < SIZE_Y; y++ ) {
for( x = 0; x < SIZE_X; x++ ) {
rho = + GRID_ENTRY( grid, x, y, z, C ) + GRID_ENTRY( grid, x, y, z, N )
+ GRID_ENTRY( grid, x, y, z, S ) + GRID_ENTRY( grid, x, y, z, E )
+ GRID_ENTRY( grid, x, y, z, W ) + GRID_ENTRY( grid, x, y, z, T )
+ GRID_ENTRY( grid, x, y, z, B ) + GRID_ENTRY( grid, x, y, z, NE )
+ GRID_ENTRY( grid, x, y, z, NW ) + GRID_ENTRY( grid, x, y, z, SE )
+ GRID_ENTRY( grid, x, y, z, SW ) + GRID_ENTRY( grid, x, y, z, NT )
+ GRID_ENTRY( grid, x, y, z, NB ) + GRID_ENTRY( grid, x, y, z, ST )
+ GRID_ENTRY( grid, x, y, z, SB ) + GRID_ENTRY( grid, x, y, z, ET )
+ GRID_ENTRY( grid, x, y, z, EB ) + GRID_ENTRY( grid, x, y, z, WT )
+ GRID_ENTRY( grid, x, y, z, WB );
ux = + GRID_ENTRY( grid, x, y, z, E ) - GRID_ENTRY( grid, x, y, z, W )
+ GRID_ENTRY( grid, x, y, z, NE ) - GRID_ENTRY( grid, x, y, z, NW )
+ GRID_ENTRY( grid, x, y, z, SE ) - GRID_ENTRY( grid, x, y, z, SW )
+ GRID_ENTRY( grid, x, y, z, ET ) + GRID_ENTRY( grid, x, y, z, EB )
- GRID_ENTRY( grid, x, y, z, WT ) - GRID_ENTRY( grid, x, y, z, WB );
uy = + GRID_ENTRY( grid, x, y, z, N ) - GRID_ENTRY( grid, x, y, z, S )
+ GRID_ENTRY( grid, x, y, z, NE ) + GRID_ENTRY( grid, x, y, z, NW )
- GRID_ENTRY( grid, x, y, z, SE ) - GRID_ENTRY( grid, x, y, z, SW )
+ GRID_ENTRY( grid, x, y, z, NT ) + GRID_ENTRY( grid, x, y, z, NB )
- GRID_ENTRY( grid, x, y, z, ST ) - GRID_ENTRY( grid, x, y, z, SB );
uz = + GRID_ENTRY( grid, x, y, z, T ) - GRID_ENTRY( grid, x, y, z, B )
+ GRID_ENTRY( grid, x, y, z, NT ) - GRID_ENTRY( grid, x, y, z, NB )
+ GRID_ENTRY( grid, x, y, z, ST ) - GRID_ENTRY( grid, x, y, z, SB )
+ GRID_ENTRY( grid, x, y, z, ET ) - GRID_ENTRY( grid, x, y, z, EB )
+ GRID_ENTRY( grid, x, y, z, WT ) - GRID_ENTRY( grid, x, y, z, WB );
ux /= rho;
uy /= rho;
uz /= rho;
if( binary ) {
/*
fwrite( &ux, sizeof( ux ), 1, file );
fwrite( &uy, sizeof( uy ), 1, file );
fwrite( &uz, sizeof( uz ), 1, file );
*/
storeValue( file, &ux );
storeValue( file, &uy );
storeValue( file, &uz );
} else
fprintf( file, "%e %e %e\n", ux, uy, uz );
}
}
}
fclose( file );
}
/*############################################################################*/
void LBM_compareVelocityField( LBM_Grid grid, const char* filename,
const int binary ) {
int x, y, z;
double rho, ux, uy, uz;
OUTPUT_PRECISION fileUx, fileUy, fileUz,
dUx, dUy, dUz,
diff2, maxDiff2 = -1e+30;
FILE* file = fopen( filename, (binary ? "rb" : "r") );
for( z = 0; z < SIZE_Z; z++ ) {
for( y = 0; y < SIZE_Y; y++ ) {
for( x = 0; x < SIZE_X; x++ ) {
rho = + GRID_ENTRY( grid, x, y, z, C ) + GRID_ENTRY( grid, x, y, z, N )
+ GRID_ENTRY( grid, x, y, z, S ) + GRID_ENTRY( grid, x, y, z, E )
+ GRID_ENTRY( grid, x, y, z, W ) + GRID_ENTRY( grid, x, y, z, T )
+ GRID_ENTRY( grid, x, y, z, B ) + GRID_ENTRY( grid, x, y, z, NE )
+ GRID_ENTRY( grid, x, y, z, NW ) + GRID_ENTRY( grid, x, y, z, SE )
+ GRID_ENTRY( grid, x, y, z, SW ) + GRID_ENTRY( grid, x, y, z, NT )
+ GRID_ENTRY( grid, x, y, z, NB ) + GRID_ENTRY( grid, x, y, z, ST )
+ GRID_ENTRY( grid, x, y, z, SB ) + GRID_ENTRY( grid, x, y, z, ET )
+ GRID_ENTRY( grid, x, y, z, EB ) + GRID_ENTRY( grid, x, y, z, WT )
+ GRID_ENTRY( grid, x, y, z, WB );
ux = + GRID_ENTRY( grid, x, y, z, E ) - GRID_ENTRY( grid, x, y, z, W )
+ GRID_ENTRY( grid, x, y, z, NE ) - GRID_ENTRY( grid, x, y, z, NW )
+ GRID_ENTRY( grid, x, y, z, SE ) - GRID_ENTRY( grid, x, y, z, SW )
+ GRID_ENTRY( grid, x, y, z, ET ) + GRID_ENTRY( grid, x, y, z, EB )
- GRID_ENTRY( grid, x, y, z, WT ) - GRID_ENTRY( grid, x, y, z, WB );
uy = + GRID_ENTRY( grid, x, y, z, N ) - GRID_ENTRY( grid, x, y, z, S )
+ GRID_ENTRY( grid, x, y, z, NE ) + GRID_ENTRY( grid, x, y, z, NW )
- GRID_ENTRY( grid, x, y, z, SE ) - GRID_ENTRY( grid, x, y, z, SW )
+ GRID_ENTRY( grid, x, y, z, NT ) + GRID_ENTRY( grid, x, y, z, NB )
- GRID_ENTRY( grid, x, y, z, ST ) - GRID_ENTRY( grid, x, y, z, SB );
uz = + GRID_ENTRY( grid, x, y, z, T ) - GRID_ENTRY( grid, x, y, z, B )
+ GRID_ENTRY( grid, x, y, z, NT ) - GRID_ENTRY( grid, x, y, z, NB )
+ GRID_ENTRY( grid, x, y, z, ST ) - GRID_ENTRY( grid, x, y, z, SB )
+ GRID_ENTRY( grid, x, y, z, ET ) - GRID_ENTRY( grid, x, y, z, EB )
+ GRID_ENTRY( grid, x, y, z, WT ) - GRID_ENTRY( grid, x, y, z, WB );
ux /= rho;
uy /= rho;
uz /= rho;
if( binary ) {
loadValue( file, &fileUx );
loadValue( file, &fileUy );
loadValue( file, &fileUz );
}
else {
if( sizeof( OUTPUT_PRECISION ) == sizeof( double )) {
fscanf( file, "%lf %lf %lf\n", &fileUx, &fileUy, &fileUz );
}
else {
fscanf( file, "%f %f %f\n", &fileUx, &fileUy, &fileUz );
}
}
dUx = ux - fileUx;
dUy = uy - fileUy;
dUz = uz - fileUz;
diff2 = dUx*dUx + dUy*dUy + dUz*dUz;
if( diff2 > maxDiff2 ) maxDiff2 = diff2;
}
}
}
printf( "LBM_compareVelocityField: maxDiff = %e \n\n",
sqrt( maxDiff2 ) );
fclose( file );
}
|
simd_loop_collapse.c | /* Example of the reduction and collapse clauses on the simd construct
The two perfectly nested loops are collapsed into a single iteration
space. The reduction clause is required to parallelize the
accumulation into t1.
*/
void simd_loop_collapse(double *r, double *b, double *c,
int n, int m)
{
int i, j;
double t1;
t1 = 0.0;
#pragma omp simd reduction(+:t1) collapse(2)
for (i=0; i<n; i++)
for (j=0; j<m; j++)
t1 += func1(b[i], c[j]);
*r = t1
}
|
GB_binop__minus_int8.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__minus_int8)
// A.*B function (eWiseMult): GB (_AemultB_01__minus_int8)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_int8)
// A.*B function (eWiseMult): GB (_AemultB_03__minus_int8)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_int8)
// A*D function (colscale): GB (_AxD__minus_int8)
// D*A function (rowscale): GB (_DxB__minus_int8)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_int8)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_int8)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_int8)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_int8)
// C=scalar+B GB (_bind1st__minus_int8)
// C=scalar+B' GB (_bind1st_tran__minus_int8)
// C=A+scalar GB (_bind2nd__minus_int8)
// C=A'+scalar GB (_bind2nd_tran__minus_int8)
// C type: int8_t
// A type: int8_t
// B,b type: int8_t
// BinaryOp: cij = (aij - bij)
#define GB_ATYPE \
int8_t
#define GB_BTYPE \
int8_t
#define GB_CTYPE \
int8_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int8_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int8_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int8_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x - y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINUS || GxB_NO_INT8 || GxB_NO_MINUS_INT8)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__minus_int8)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__minus_int8)
(
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__minus_int8)
(
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__minus_int8)
(
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 int8_t
int8_t bwork = (*((int8_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__minus_int8)
(
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
int8_t *restrict Cx = (int8_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__minus_int8)
(
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
int8_t *restrict Cx = (int8_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__minus_int8)
(
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__minus_int8)
(
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__minus_int8)
(
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__minus_int8)
(
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__minus_int8)
(
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__minus_int8)
(
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
int8_t *Cx = (int8_t *) Cx_output ;
int8_t x = (*((int8_t *) x_input)) ;
int8_t *Bx = (int8_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int8_t bij = GBX (Bx, p, false) ;
Cx [p] = (x - bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__minus_int8)
(
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 ;
int8_t *Cx = (int8_t *) Cx_output ;
int8_t *Ax = (int8_t *) Ax_input ;
int8_t y = (*((int8_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int8_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij - y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_int8)
(
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 \
int8_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int8_t x = (*((const int8_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int8_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int8_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_int8)
(
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
int8_t y = (*((const int8_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
tree.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_
#include <LightGBM/dataset.h>
#include <LightGBM/meta.h>
#include <string>
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
namespace LightGBM {
#define kCategoricalMask (1)
#define kDefaultLeftMask (2)
/*!
* \brief Tree model
*/
class Tree {
public:
/*!
* \brief Constructor
* \param max_leaves The number of max leaves
* \param track_branch_features Whether to keep track of ancestors of leaf nodes
*/
explicit Tree(int max_leaves, bool track_branch_features);
/*!
* \brief Constructor, from a string
* \param str Model string
* \param used_len used count of str
*/
Tree(const char* str, size_t* used_len);
~Tree();
/*!
* \brief Performing a split on tree leaves.
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split
* \param threshold_double Threshold on feature value
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \param missing_type missing type
* \param default_left default direction for missing value
* \return The index of new leaf.
*/
int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin,
double threshold_double, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight,
float gain, MissingType missing_type, bool default_left);
/*!
* \brief Performing a split on tree leaves, with categorical feature
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split, use bitset to represent
* \param num_threshold_bin size of threshold_bin
* \param threshold Thresholds of real feature value, use bitset to represent
* \param num_threshold size of threshold
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \return The index of new leaf.
*/
int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin,
const uint32_t* threshold, int num_threshold, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight, float gain, MissingType missing_type);
/*! \brief Get the output of one leaf */
inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; }
/*! \brief Set the output of one leaf */
inline void SetLeafOutput(int leaf, double output) {
leaf_value_[leaf] = MaybeRoundToZero(output);
}
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
data_size_t num_data,
double* score) const;
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param used_data_indices Indices of used data
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
const data_size_t* used_data_indices,
data_size_t num_data, double* score) const;
/*!
* \brief Get upper bound leaf value of this tree model
*/
double GetUpperBoundValue() const;
/*!
* \brief Get lower bound leaf value of this tree model
*/
double GetLowerBoundValue() const;
/*!
* \brief Prediction on one record
* \param feature_values Feature value of this record
* \return Prediction result
*/
inline double Predict(const double* feature_values) const;
inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const;
inline int PredictLeafIndex(const double* feature_values) const;
inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const;
inline void PredictContrib(const double* feature_values, int num_features, double* output);
/*! \brief Get Number of leaves*/
inline int num_leaves() const { return num_leaves_; }
/*! \brief Get depth of specific leaf*/
inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; }
/*! \brief Get parent of specific leaf*/
inline int leaf_parent(int leaf_idx) const {return leaf_parent_[leaf_idx]; }
/*! \brief Get feature of specific split*/
inline int split_feature(int split_idx) const { return split_feature_[split_idx]; }
/*! \brief Get features on leaf's branch*/
inline std::vector<int> branch_features(int leaf) const { return branch_features_[leaf]; }
inline double split_gain(int split_idx) const { return split_gain_[split_idx]; }
inline double internal_value(int node_idx) const {
return internal_value_[node_idx];
}
inline bool IsNumericalSplit(int node_idx) const {
return !GetDecisionType(decision_type_[node_idx], kCategoricalMask);
}
inline int left_child(int node_idx) const { return left_child_[node_idx]; }
inline int right_child(int node_idx) const { return right_child_[node_idx]; }
inline int split_feature_inner(int node_idx) const {
return split_feature_inner_[node_idx];
}
inline uint32_t threshold_in_bin(int node_idx) const {
return threshold_in_bin_[node_idx];
}
/*! \brief Get the number of data points that fall at or below this node*/
inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; }
/*!
* \brief Shrinkage for the tree's output
* shrinkage rate (a.k.a learning rate) is used to tune the training process
* \param rate The factor of shrinkage
*/
inline void Shrinkage(double rate) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] * rate);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] * rate);
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] * rate);
shrinkage_ *= rate;
}
inline double shrinkage() const { return shrinkage_; }
inline void AddBias(double val) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] + val);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] + val);
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] + val);
// force to 1.0
shrinkage_ = 1.0f;
}
inline void AsConstantTree(double val) {
num_leaves_ = 1;
shrinkage_ = 1.0f;
leaf_value_[0] = val;
}
/*! \brief Serialize this object to string*/
std::string ToString() const;
/*! \brief Serialize this object to json*/
std::string ToJSON() const;
/*! \brief Serialize this object to if-else statement*/
std::string ToIfElse(int index, bool predict_leaf_index) const;
inline static bool IsZero(double fval) {
return (fval >= -kZeroThreshold && fval <= kZeroThreshold);
}
inline static double MaybeRoundToZero(double fval) {
return IsZero(fval) ? 0 : fval;
}
inline static bool GetDecisionType(int8_t decision_type, int8_t mask) {
return (decision_type & mask) > 0;
}
inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) {
if (input) {
(*decision_type) |= mask;
} else {
(*decision_type) &= (127 - mask);
}
}
inline static int8_t GetMissingType(int8_t decision_type) {
return (decision_type >> 2) & 3;
}
inline static void SetMissingType(int8_t* decision_type, int8_t input) {
(*decision_type) &= 3;
(*decision_type) |= (input << 2);
}
void RecomputeMaxDepth();
int NextLeafId() const { return num_leaves_; }
private:
std::string NumericalDecisionIfElse(int node) const;
std::string CategoricalDecisionIfElse(int node) const;
inline int NumericalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if (std::isnan(fval) && missing_type != MissingType::NaN) {
fval = 0.0f;
}
if ((missing_type == MissingType::Zero && IsZero(fval))
|| (missing_type == MissingType::NaN && std::isnan(fval))) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if ((missing_type == MissingType::Zero && fval == default_bin)
|| (missing_type == MissingType::NaN && fval == max_bin)) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_in_bin_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int CategoricalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
int int_fval = static_cast<int>(fval);
if (int_fval < 0) {
return right_child_[node];;
} else if (std::isnan(fval)) {
// NaN is always in the right
if (missing_type == MissingType::NaN) {
return right_child_[node];
}
int_fval = 0;
}
int cat_idx = static_cast<int>(threshold_[node]);
if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx],
cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int CategoricalDecisionInner(uint32_t fval, int node) const {
int cat_idx = static_cast<int>(threshold_in_bin_[node]);
if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx],
cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int Decision(double fval, int node) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecision(fval, node);
} else {
return NumericalDecision(fval, node);
}
}
inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecisionInner(fval, node);
} else {
return NumericalDecisionInner(fval, node, default_bin, max_bin);
}
}
inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain);
/*!
* \brief Find leaf index of which record belongs by features
* \param feature_values Feature value of this record
* \return Leaf index
*/
inline int GetLeaf(const double* feature_values) const;
inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const;
/*! \brief Serialize one node to json*/
std::string NodeToJSON(int index) const;
/*! \brief Serialize one node to if-else statement*/
std::string NodeToIfElse(int index, bool predict_leaf_index) const;
std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const;
double ExpectedValue() const;
/*! \brief This is used fill in leaf_depth_ after reloading a model*/
inline void RecomputeLeafDepths(int node = 0, int depth = 0);
/*!
* \brief Used by TreeSHAP for data we keep about our decision path
*/
struct PathElement {
int feature_index;
double zero_fraction;
double one_fraction;
// note that pweight is included for convenience and is not tied with the other attributes,
// the pweight of the i'th path element is the permutation weight of paths with i-1 ones in them
double pweight;
PathElement() {}
PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {}
};
/*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/
void TreeSHAP(const double *feature_values, double *phi,
int node, int unique_depth,
PathElement *parent_unique_path, double parent_zero_fraction,
double parent_one_fraction, int parent_feature_index) const;
/*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/
static void ExtendPath(PathElement *unique_path, int unique_depth,
double zero_fraction, double one_fraction, int feature_index);
/*! \brief Undo a previous extension of the decision path for TreeSHAP*/
static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index);
/*! determine what the total permutation weight would be if we unwound a previous extension in the decision path*/
static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index);
/*! \brief Number of max leaves*/
int max_leaves_;
/*! \brief Number of current leaves*/
int num_leaves_;
// following values used for non-leaf node
/*! \brief A non-leaf node's left child */
std::vector<int> left_child_;
/*! \brief A non-leaf node's right child */
std::vector<int> right_child_;
/*! \brief A non-leaf node's split feature */
std::vector<int> split_feature_inner_;
/*! \brief A non-leaf node's split feature, the original index */
std::vector<int> split_feature_;
/*! \brief A non-leaf node's split threshold in bin */
std::vector<uint32_t> threshold_in_bin_;
/*! \brief A non-leaf node's split threshold in feature value */
std::vector<double> threshold_;
int num_cat_;
std::vector<int> cat_boundaries_inner_;
std::vector<uint32_t> cat_threshold_inner_;
std::vector<int> cat_boundaries_;
std::vector<uint32_t> cat_threshold_;
/*! \brief Store the information for categorical feature handle and missing value handle. */
std::vector<int8_t> decision_type_;
/*! \brief A non-leaf node's split gain */
std::vector<float> split_gain_;
// used for leaf node
/*! \brief The parent of leaf */
std::vector<int> leaf_parent_;
/*! \brief Output of leaves */
std::vector<double> leaf_value_;
/*! \brief weight of leaves */
std::vector<double> leaf_weight_;
/*! \brief DataCount of leaves */
std::vector<int> leaf_count_;
/*! \brief Output of non-leaf nodes */
std::vector<double> internal_value_;
/*! \brief weight of non-leaf nodes */
std::vector<double> internal_weight_;
/*! \brief DataCount of non-leaf nodes */
std::vector<int> internal_count_;
/*! \brief Depth for leaves */
std::vector<int> leaf_depth_;
/*! \brief whether to keep track of ancestor nodes for each leaf (only needed when feature interactions are restricted) */
bool track_branch_features_;
/*! \brief Features on leaf's branch, original index */
std::vector<std::vector<int>> branch_features_;
double shrinkage_;
int max_depth_;
};
inline void Tree::Split(int leaf, int feature, int real_feature,
double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain) {
int new_node_idx = num_leaves_ - 1;
// update parent info
int parent = leaf_parent_[leaf];
if (parent >= 0) {
// if cur node is left child
if (left_child_[parent] == ~leaf) {
left_child_[parent] = new_node_idx;
} else {
right_child_[parent] = new_node_idx;
}
}
// add new node
split_feature_inner_[new_node_idx] = feature;
split_feature_[new_node_idx] = real_feature;
split_gain_[new_node_idx] = gain;
// add two new leaves
left_child_[new_node_idx] = ~leaf;
right_child_[new_node_idx] = ~num_leaves_;
// update new leaves
leaf_parent_[leaf] = new_node_idx;
leaf_parent_[num_leaves_] = new_node_idx;
// save current leaf value to internal node before change
internal_weight_[new_node_idx] = leaf_weight_[leaf];
internal_value_[new_node_idx] = leaf_value_[leaf];
internal_count_[new_node_idx] = left_cnt + right_cnt;
leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
leaf_weight_[leaf] = left_weight;
leaf_count_[leaf] = left_cnt;
leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
leaf_weight_[num_leaves_] = right_weight;
leaf_count_[num_leaves_] = right_cnt;
// update leaf depth
leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
leaf_depth_[leaf]++;
if (track_branch_features_) {
branch_features_[num_leaves_] = branch_features_[leaf];
branch_features_[num_leaves_].push_back(split_feature_[new_node_idx]);
branch_features_[leaf].push_back(split_feature_[new_node_idx]);
}
}
inline double Tree::Predict(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
inline int Tree::PredictLeafIndex(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return leaf;
} else {
return 0;
}
}
inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return leaf;
} else {
return 0;
}
}
inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) {
output[num_features] += ExpectedValue();
// Run the recursion with preallocated space for the unique path data
if (num_leaves_ > 1) {
CHECK_GE(max_depth_, 0);
const int max_path_len = max_depth_ + 1;
std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
}
}
inline void Tree::RecomputeLeafDepths(int node, int depth) {
if (node == 0) leaf_depth_.resize(num_leaves());
if (node < 0) {
leaf_depth_[~node] = depth;
} else {
RecomputeLeafDepths(left_child_[node], depth + 1);
RecomputeLeafDepths(right_child_[node], depth + 1);
}
}
inline int Tree::GetLeaf(const double* feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values[split_feature_[node]], node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values[split_feature_[node]], node);
}
}
return ~node;
}
inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
}
return ~node;
}
} // namespace LightGBM
#endif // LightGBM_TREE_H_
|
3d25pt.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 4;
tile_size[1] = 4;
tile_size[2] = 8;
tile_size[3] = 512;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=2*Nt-2;t1++) {
lbp=ceild(t1+2,2);
ubp=min(floord(4*Nt+Nz-9,4),floord(2*t1+Nz-4,4));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(ceild(t1,4),ceild(4*t2-Nz+5,8));t3<=min(min(floord(4*Nt+Ny-9,8),floord(2*t1+Ny-3,8)),floord(4*t2+Ny-9,8));t3++) {
for (t4=max(max(ceild(t1-252,256),ceild(4*t2-Nz-499,512)),ceild(8*t3-Ny-499,512));t4<=min(min(min(floord(4*Nt+Nx-9,512),floord(2*t1+Nx-3,512)),floord(4*t2+Nx-9,512)),floord(8*t3+Nx-5,512));t4++) {
for (t5=max(max(max(ceild(t1,2),ceild(4*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(512*t4-Nx+5,4));t5<=floord(t1+1,2);t5++) {
for (t6=max(4*t2,-4*t1+4*t2+8*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) {
lbv=max(512*t4,4*t5+4);
ubv=min(512*t4+511,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
resize.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE %
% R R E SS I ZZ E %
% RRRR EEE SSS I ZZZ EEE %
% R R E SS I ZZ E %
% R R EEEEE SSSSS IIIII ZZZZZ EEEEE %
% %
% %
% ImageMagick Image Resize Methods %
% %
% Software Design %
% John Cristy %
% July 1992 %
% %
% %
% Copyright 1999-2008 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% http://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/artifact.h"
#include "magick/blob.h"
#include "magick/cache-view.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/draw.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/memory_.h"
#include "magick/pixel-private.h"
#include "magick/property.h"
#include "magick/monitor.h"
#include "magick/pixel.h"
#include "magick/option.h"
#include "magick/resample.h"
#include "magick/resize.h"
#include "magick/resize-private.h"
#include "magick/string_.h"
#include "magick/utility.h"
#include "magick/version.h"
#if defined(MAGICKCORE_LQR_DELEGATE)
#include <lqr.h>
#endif
/*
Typedef declarations.
*/
struct _ResizeFilter
{
MagickRealType
(*filter)(const MagickRealType, const ResizeFilter*),
(*window)(const MagickRealType, const ResizeFilter*),
support, /* filter region of support - the filter support limit */
wsupport, /* window support, usally equal to support (expert only) */
wsize, /* dimension to scale to fit window support (usally 1.0) */
blur, /* x-scale (blur-sharpen) */
cubic[8]; /* cubic coefficents for smooth Cubic filters */
unsigned long
signature;
};
/*
Forward declaractions.
*/
static MagickRealType
I0(MagickRealType x),
BesselOrderOne(MagickRealType);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ F i l t e r F u n c t i o n s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% These are the various filter and windowing functions that are provided,
%
% They are all internal to this module only. See AcquireResizeFilterInfo()
% for details of the access to these functions, via the
% GetResizeFilterSupport() and GetResizeFilterWeight() API interface.
%
% The individual filter functions have this format...
%
% static MagickRealtype *FilterName(const MagickRealType x,
% const MagickRealType support)
%
% o x: the distance from the sampling point
% generally in the range of 0 to support
% The GetResizeFilterWeight() ensures this is a positive value.
%
% o resize_filter: Current Filter Information
% This allows function to access support, and posibly other
% pre-calculated information defineding the functions.
%
*/
static MagickRealType Bessel(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* See Pratt "Digital Image Processing" p.97 for Bessel functions
This function actually a X-scaled Jinc(x) function.
http://mathworld.wolfram.com/JincFunction.html
And on page 11 of...
http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf
*/
if (x == 0.0)
return((MagickRealType) (MagickPI/4.0));
return(BesselOrderOne(MagickPI*x)/(2.0*x));
}
static MagickRealType Blackman(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Blackman: 2rd Order cosine windowing function */
return(0.42+0.5*cos(MagickPI*(double) x)+0.08*cos(2.0*MagickPI*(double) x));
}
static MagickRealType Bohman(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Bohman: 2rd Order cosine windowing function
*/
return((1-x)*cos(MagickPI*(double) x)+sin(MagickPI*(double) x)/MagickPI);
}
static MagickRealType Box(const MagickRealType magick_unused(x),
const ResizeFilter *magick_unused(resize_filter))
{
/* Just return 1.0, filter will still be clipped by its support window */
return(1.0);
}
#if 0
/* Replaced by CubicBC below */
static MagickRealType Catrom(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Catmull-Rom or Keys Cubic Filter, B=0 C=1/2 */
/* This is the Cubic Spline Interpolator */
if (x < 1.0)
return(1.0+x*x*(-2.5+1.5*x));
if (x < 2.0)
return(2.0+x*(-4.0+x*(2.5-0.5*x)));
return(0.0);
}
/* Replaced by CubicBC below */
static MagickRealType Cubic(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* B-Spline, B=1 C=0, A Cubic Spline approximation of Gaussian */
if (x < 1.0)
return((4.0+x*x*(-6.0+3.0*x))/6.0);
if (x < 2.0)
return((2.0-x)*(2.0-x)*(2.0-x)/6.0);
return(0.0);
}
/* Replaced by CubicBC below */
static MagickRealType Hermite(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* A Cubic windowing function, B=0, C=0 */
if (x < 1.0)
return((2.0*x-3.0)*x*x+1.0);
return(0.0);
}
#endif
static MagickRealType CubicBC(const MagickRealType x,
const ResizeFilter *resize_filter)
{
/*
Cubic Filters using B,C determined values :-
Mitchell-Netravali B=1/3 C=1/3 Qualitively ideal Cubic Filter
Catmull-Rom B= 0 C=1/2 Cublic Interpolation Function
Cubic B-Spline B= 1 C= 0 Spline Approximation of Gaussian
Hermite B= 0 C= 0 Quadratic Spline (support = 1)
See paper by Mitchell and Netravali,
Reconstruction Filters in Computer Graphics
Computer Graphics, Volume 22, Number 4, August 1988
http://www.cs.utexas.edu/users/fussell/courses/cs384g/
lectures/mitchell/Mitchell.pdf
Coefficents are determined from B,C values
P0 = ( 6 - 2*B )/6
P1 = 0
P2 = (-18 +12*B + 6*C )/6
P3 = ( 12 - 9*B - 6*C )/6
Q0 = ( 8*B +24*C )/6
Q1 = ( -12*B -48*C )/6
Q2 = ( 6*B +30*C )/6
Q3 = ( - 1*B - 6*C )/6
Which is used to define the filter...
P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1
Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x <= 2
Which ensures function is continuious in value and derivative (slope)
*/
if (x < 1.0)
return(resize_filter->cubic[0] +x*(resize_filter->cubic[1]
+x*(resize_filter->cubic[2] +x*resize_filter->cubic[3] )));
if (x < 2.0)
return(resize_filter->cubic[4] +x*(resize_filter->cubic[5]
+x*(resize_filter->cubic[6] +x*resize_filter->cubic[7] )));
return(0.0);
}
static MagickRealType Gaussian(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
return(exp((double) (-2.0*x*x))*sqrt(2.0/MagickPI));
}
static MagickRealType Hanning(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* A Cosine windowing function */
return(0.5+0.5*cos(MagickPI*(double) x));
}
static MagickRealType Hamming(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* A offset Cosine windowing function */
return(0.54+0.46*cos(MagickPI*(double) x));
}
static MagickRealType Kaiser(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Kaiser Windowing Function (bessel windowing)
Alpha is a free value from 5 to 8 (currently hardcoded to 6.5)
Future: make alpha and the IOA pre-calculation, a 'expert' setting
*/
#define Alpha 6.5
#define I0A (1.0/I0(Alpha))
return(I0A*I0(Alpha*sqrt((double) (1.0-x*x))));
}
static MagickRealType Lagrange(const MagickRealType x,
const ResizeFilter *resize_filter)
{
/* Lagrange Piece-Wise polynomial fit of Sinc
N is the 'order' of the lagrange function and depends on
the overall support window size of the filter. That is for
a support of 2, gives a lagrange-4 or piece-wise cubic functions
Note that n is the specific piece of the piece-wise function to calculate.
See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging,
Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064
*/
int N,n,i;
MagickRealType value;
if ( x > resize_filter->support )
return(0.0);
N = (int)(resize_filter->wsupport*2); /* order or number of pieces */
n = (int)(x+((double)N)/2.0); /* which piece does x belong to */
value = 1.0f;
for ( i=0; i<N; i++)
if ( i != n )
value *= (n-i-x)/(n-i);
return value;
}
#if 0
/* Replaced by CubicBC below */
static MagickRealType Lanczos(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* The lanzcos, sinc windowed sinc Filter
But it also ise used as a bessel windowed bessel
which complicates the use of the filter.
*/
if (x < support)
return(Sinc(x)*Sinc(x/support));
return(0.0);
}
static MagickRealType Mitchell(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Mitchell-Netravali B=1/3 C=1/3 Qualitively ideal Cubic Filter */
#define B (1.0/3.0)
#define C (1.0/3.0)
#define P0 (( 6.0- 2.0*B )/6.0)
#define P2 ((-18.0+12.0*B+ 6.0*C)/6.0)
#define P3 (( 12.0- 9.0*B- 6.0*C)/6.0)
#define Q0 (( 8.0*B+24.0*C)/6.0)
#define Q1 (( -12.0*B-48.0*C)/6.0)
#define Q2 (( 6.0*B+30.0*C)/6.0)
#define Q3 (( - 1.0*B- 6.0*C)/6.0)
if (x < 1.0)
return(P0+x*x*(P2+x*P3));
if (x < 2.0)
return(Q0+x*(Q1+x*(Q2+x*Q3)));
return(0.0);
}
#endif
static MagickRealType Quadratic(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* 2rd order (quadratic) B-Spline approximation of Gaussian */
if (x < 0.5)
return(0.75-x*x);
if (x < 1.5)
return(0.5*(x-1.5)*(x-1.5));
return(0.0);
}
static MagickRealType Sinc(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* This function actually a X-scaled Sinc(x) function. */
if (x == 0.0)
return(1.0);
return(sin(MagickPI*(double) x)/(MagickPI*(double) x));
}
static MagickRealType Triangle(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* 1rd order (linear) B-Spline, bilinear interpolation,
* Tent 1D filter, or a Bartlett 2D Cone filter */
if (x < 1.0)
return(1.0-x);
return(0.0);
}
static MagickRealType Welsh(const MagickRealType x,
const ResizeFilter *magick_unused(resize_filter))
{
/* Welsh parabolic windowing filter */
if (x < 1.0)
return(1 - x*x);
return(0.0);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e R e s i z e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireResizeFilter() allocates the ResizeFilter structure. Choose from
% these filters:
%
% FIR (Finite impulse Response) Filters
% Box Triangle Quadratic
% Cubic Hermite Catrom
% Mitchell
%
% IIR (Infinite impulse Response) Filters
% Gaussian Sinc Bessel
%
% Windowed Sinc/Bessel Method
% Blackman Hanning Hamming
% Kaiser Lancos (Sinc)
%
% FIR filters are used as is, and are limited by that filters support window
% (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also
% simply clipped by its support size (1.5).
%
% Requesting a windowed filter will return either a windowed Sinc, for a one
% dimentional orthogonal filtering method, such as ResizeImage(), or a
% windowed Bessel for image operations requiring a two dimentional
% cylindrical filtering method, such a DistortImage(). Which function is
% is used set by the "cylindrical" boolean argument.
%
% Directly requesting 'Sinc' or 'Bessel' will force the use of that filter
% function, with a default 'Blackman' windowing method. This is not however
% recommended as it removes the correct filter selection for different
% filtering image operations. Selecting a window filtering method is better.
%
% Lanczos is purely special case of a Sinc windowed Sinc, but defulting to
% a 3 lobe support, rather that the default 4 lobe support.
%
% Special options can be used to override specific, or all the filter
% settings. However doing so is not advisible unless you have expert
% knowledge of the use of resampling filtered techniques. Extreme caution is
% advised.
%
% "filter:filter" Select this function as the filter.
% If a "filter:window" operation is not provided, then no windowing
% will be performed on the selected filter, (support clipped)
%
% This can be used to force the use of a windowing method as filter,
% request a 'Sinc' filter in a radially filtered operation, or the
% 'Bessel' filter for a othogonal filtered operation.
%
% "filter:window" Select this windowing function for the filter.
% While any filter could be used as a windowing function,
% using that filters first lobe over the whole support window,
% using a non-windowing method is not advisible.
%
% "filter:lobes" Number of lobes to use for the Sinc/Bessel filter.
% This is a simper method of setting filter support size that will
% correctly handle the Sinc/Bessel switch for an operators filtering
% requirements.
%
% "filter:support" Set the support size for filtering to the size given
% This is not recomented for Sinc/Bessel windowed filters, but is
% used for simple filters like FIR filters, and the Gaussian Filter.
% This will override any 'filter:lobes' option.
%
% "filter:blur" Scale the filter and support window by this amount.
% A value >1 will generally result in a more burred image with
% more ringing effects, while a value <1 will sharpen the
% resulting image with more aliasing and Morie effects.
%
% "filter:win-support" Scale windowing function to this size instead.
% This causes the windowing (or self-windowing Lagrange filter)
% to act is if the support winodw it much much larger than what
% is actually supplied to the calling operator. The filter however
% is still clipped to the real support size given. If unset this
% will equal the normal filter support size.
%
% "filter:b"
% "filter:c" Override the preset B,C values for a Cubic type of filter
% If only one of these are given it is assumes to be a 'Keys'
% type of filter such that B+2C=1, where Keys 'alpha' value = C
%
% "filter:verbose" Output verbose plotting data for graphing the
% resulting filter over the whole support range (with blur effect).
%
% Set a true un-windowed Sinc filter with 10 lobes (very slow)
% -set option:filter:filter Sinc
% -set option:filter:lobes 8
%
% For example force an 8 lobe Lanczos (Sinc or Bessel) filter...
% -filter Lanczos
% -set option:filter:lobes 8
%
% The format of the AcquireResizeFilter method is:
%
% ResizeFilter *AcquireResizeFilter(const Image *image,
% const FilterTypes filter_type, const MagickBooleanType radial,
% ExceptionInfo *exception)
%
% o image: the image.
%
% o filter: the filter type, defining a preset filter, window and support.
%
% o blur: blur the filter by this amount, use 1.0 if unknown.
%
% o radial: 1D orthogonal filter (Sinc) or 2D radial filter (Bessel)
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport ResizeFilter *AcquireResizeFilter(const Image *image,
const FilterTypes filter, const MagickRealType blur,
const MagickBooleanType cylindrical, ExceptionInfo *exception)
{
const char
*artifact;
FilterTypes
filter_type,
window_type;
long
filter_artifact;
MagickRealType
B,
C;
register ResizeFilter
*resize_filter;
/*
Table Mapping given Filter, into Weighting and Windowing functions.
A 'Box' windowing function means its a simble non-windowed filter.
A 'Sinc' filter function (must be windowed) could be upgraded to a
'Bessel' filter if a "cylindrical" filter is requested, unless a "Sinc"
filter specifically request.
*/
static struct {
FilterTypes
filter,
window;
} const mapping[SentinelFilter] =
{
{ UndefinedFilter, BoxFilter }, /* undefined */
{ PointFilter, BoxFilter }, /* special, nearest-neighbour filter */
{ BoxFilter, BoxFilter }, /* Box averaging Filter */
{ TriangleFilter, BoxFilter }, /* Linear Interpolation Filter */
{ HermiteFilter, BoxFilter }, /* Hermite interpolation filter */
{ SincFilter, HanningFilter }, /* Hanning -- Cosine-Sinc */
{ SincFilter, HammingFilter }, /* Hamming -- '' variation */
{ SincFilter, BlackmanFilter }, /* Blackman -- 2*Cosine-Sinc */
{ GaussianFilter, BoxFilter }, /* Gaussain Blurring filter */
{ QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approximation */
{ CubicFilter, BoxFilter }, /* Cubic Gaussian approximation */
{ CatromFilter, BoxFilter }, /* Cubic Interpolator */
{ MitchellFilter, BoxFilter }, /* 'ideal' Cubic Filter */
{ LanczosFilter, SincFilter }, /* Special, 3 lobed Sinc-Sinc */
{ BesselFilter, BlackmanFilter }, /* 3 lobed bessel -specific request */
{ SincFilter, BlackmanFilter }, /* 4 lobed sinc - specific request */
{ SincFilter, KaiserFilter }, /* Kaiser -- SqRoot-Sinc */
{ SincFilter, WelshFilter }, /* Welsh -- Parabolic-Sinc */
{ SincFilter, CubicFilter }, /* Parzen -- Cubic-Sinc */
{ LagrangeFilter, BoxFilter }, /* Lagrange self-windowing filter */
{ SincFilter, BohmanFilter }, /* Bohman -- 2*Cosine-Sinc */
{ SincFilter, TriangleFilter } /* Bartlett -- Triangle-Sinc */
};
/*
Table maping the filter/window function from the above table to the actual
filter/window function call to use. The default support size for that
filter as a weighting function, and the point to scale when that function
is used as a windowing function (typ 1.0).
*/
static struct {
MagickRealType
(*function)(const MagickRealType, const ResizeFilter*),
support, /* default support size for function as a filter */
wsize, /* size windowing function, for scaling windowing function */
B,C; /* Cubic Filter factors for a CubicBC function, else ignored */
} const filters[SentinelFilter] =
{
{ Box, 0.0f, 0.5f, 0.0f, 0.0f }, /* Undefined */
{ Box, 0.0f, 0.5f, 0.0f, 0.0f }, /* Point */
{ Box, 0.5f, 0.5f, 0.0f, 0.0f }, /* Box */
{ Triangle, 1.0f, 1.0f, 0.0f, 0.0f }, /* Triangle */
{ CubicBC, 1.0f, 1.0f, 0.0f, 0.0f }, /* Hermite, Cubic B=C=0 */
{ Hanning, 1.0f, 1.0f, 0.0f, 0.0f }, /* Hanning, Cosine window */
{ Hamming, 1.0f, 1.0f, 0.0f, 0.0f }, /* Hamming, '' variation */
{ Blackman, 1.0f, 1.0f, 0.0f, 0.0f }, /* Blackman, 2*cos window */
{ Gaussian, 1.5f, 1.5f, 0.0f, 0.0f }, /* Gaussian */
{ Quadratic, 1.5f, 1.5f, 0.0f, 0.0f }, /* Quadratic Gaussian */
{ CubicBC, 2.0f, 2.0f, 1.0f, 0.0f }, /* B-Spline of Gaussian B=1 C=0 */
{ CubicBC, 2.0f, 1.0f, 0.0f, 0.5f }, /* Catmull-Rom B=0 C=1/2 */
{ CubicBC, 2.0f, 1.0f, 1.0f/3.0f, 1.0f/3.0f }, /* Mitchel B=C=1/3 */
{ Sinc, 3.0f, 1.0f, 0.0f, 0.0f }, /* Lanczos, 3 lobed Sinc-Sinc */
{ Bessel, 3.2383f,1.2197f,.0f,.0f }, /* 3 lobed Blackman-Bessel */
{ Sinc, 4.0f, 1.0f, 0.0f, 0.0f }, /* 4 lobed Blackman-Sinc */
{ Kaiser, 1.0f, 1.0f, 0.0f, 0.0f }, /* Kaiser, sq-root windowing */
{ Welsh, 1.0f, 1.0f, 0.0f, 0.0f }, /* Welsh, Parabolic windowing */
{ CubicBC, 2.0f, 2.0f, 1.0f, 0.0f }, /* Parzen, B-Spline windowing */
{ Lagrange, 2.0f, 1.0f, 0.0f, 0.0f }, /* Lagrangian Filter */
{ Bohman, 1.0f, 1.0f, 0.0f, 0.0f }, /* Bohman, 2*Cosine windowing */
{ Triangle, 1.0f, 1.0f, 0.0f, 0.0f } /* Bartlett, Triangle windowing */
};
/* The known zero crossings of the Bessel() or the Jinc(x*PI) function
Found by using
http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp
for Jv-function with v=1, then dividing X-roots by PI (tabled below)
*/
static MagickRealType bessel_zeros[16] = {
1.21966989126651f,
2.23313059438153f,
3.23831548416624f,
4.24106286379607f,
5.24276437687019f,
6.24392168986449f,
7.24475986871996f,
8.24539491395205f,
9.24589268494948f,
10.2462933487549f,
11.2466227948779f,
12.2468984611381f,
13.2471325221811f,
14.2473337358069f,
15.2475085630373f,
16.247661874701f
};
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(UndefinedFilter < filter && filter < SentinelFilter);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
resize_filter=(ResizeFilter *) AcquireMagickMemory(sizeof(*resize_filter));
if (resize_filter == (ResizeFilter *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
/* defaults for the requested filter */
filter_type = mapping[filter].filter;
window_type = mapping[filter].window;
if ( cylindrical == MagickTrue && filter != SincFilter ) {
/* promote 1D Sinc Filter to a 2D Bessel filter */
if ( filter_type == SincFilter )
filter_type = BesselFilter;
/* Prompote Lanczos (Sinc-Sinc) to Lanczos (Bessel-Bessel) */
else if ( filter_type == LanczosFilter ) {
filter_type = BesselFilter;
window_type = BesselFilter;
}
/* FUTURE: blur other filters by 1.22 for cylindrical usage??? */
}
/* Override Filter Selection */
artifact=GetImageArtifact(image,"filter:filter");
if (artifact != (const char *) NULL) {
/* raw filter request - no window function */
filter_artifact=ParseMagickOption(MagickFilterOptions,
MagickFalse,artifact);
if ( UndefinedFilter < filter_artifact &&
filter_artifact < SentinelFilter ) {
filter_type = (FilterTypes) filter_artifact;
window_type = BoxFilter;
}
/* Lanczos is nor a real filter but a self windowing Sinc/Bessel */
if ( filter_artifact == LanczosFilter ) {
filter_type = (cylindrical==MagickTrue) ? BesselFilter : LanczosFilter;
window_type = (cylindrical==MagickTrue) ? BesselFilter : SincFilter;
}
/* Filter overwide with a specific window function? */
artifact=GetImageArtifact(image,"filter:window");
if (artifact != (const char *) NULL) {
filter_artifact=ParseMagickOption(MagickFilterOptions,
MagickFalse,artifact);
if ( UndefinedFilter < filter_artifact &&
filter_artifact < SentinelFilter ) {
if ( filter_artifact != LanczosFilter )
window_type = (FilterTypes) filter_artifact;
else
window_type = (cylindrical==MagickTrue) ? BesselFilter : SincFilter;
}
}
}
else {
/* window specified, but no filter function? Assume Sinc/Bessel */
artifact=GetImageArtifact(image,"filter:window");
if (artifact != (const char *) NULL) {
filter_artifact=ParseMagickOption(MagickFilterOptions,MagickFalse,
artifact);
if ( UndefinedFilter < filter_artifact &&
filter_artifact < SentinelFilter ) {
filter_type = (cylindrical==MagickTrue) ? BesselFilter : SincFilter;
if ( filter_artifact != LanczosFilter )
window_type = (FilterTypes) filter_artifact;
else
window_type = filter_type;
}
}
}
resize_filter->filter = filters[filter_type].function;
resize_filter->support = filters[filter_type].support;
resize_filter->window = filters[window_type].function;
resize_filter->wsize = filters[window_type].wsize;
resize_filter->blur = blur;
resize_filter->signature=MagickSignature;
/* Filter support overrides */
artifact=GetImageArtifact(image,"filter:lobes");
if (artifact != (const char *) NULL) {
long lobes = atol(artifact);
if ( lobes < 1 ) lobes = 1;
resize_filter->support = (MagickRealType) lobes;
if ( filter_type == BesselFilter ) {
if ( lobes > 16 ) lobes = 16;
resize_filter->support = bessel_zeros[lobes-1];
}
}
artifact=GetImageArtifact(image,"filter:support");
if (artifact != (const char *) NULL)
resize_filter->support = fabs(atof(artifact));
/* Scale windowing function separatally to the support 'clipping' window
that calling operator is planning to actually use. - Expert Use Only
*/
resize_filter->wsupport = resize_filter->support;
artifact=GetImageArtifact(image,"filter:win-support");
if (artifact != (const char *) NULL)
resize_filter->wsupport = fabs(atof(artifact));
/* Filter blur -- scaling both filter and support window */
artifact=GetImageArtifact(image,"filter:blur");
if (artifact != (const char *) NULL)
resize_filter->blur = atof(artifact);
if ( resize_filter->blur < MagickEpsilon )
resize_filter->blur = (MagickRealType) MagickEpsilon;
/* Set Cubic Spline B,C values, calculate Cubic coefficents */
B=0.0;
C=0.0;
if ( filters[filter_type].function == CubicBC
|| filters[window_type].function == CubicBC ) {
if ( filters[filter_type].function == CubicBC ) {
B=filters[filter_type].B;
C=filters[filter_type].C;
}
else if ( filters[window_type].function == CubicBC ) {
B=filters[window_type].B;
C=filters[window_type].C;
}
artifact=GetImageArtifact(image,"filter:b");
if (artifact != (const char *) NULL) {
B=atof(artifact);
C=1.0-2.0*B; /* Calculate C as if it is a Keys cubic filter */
artifact=GetImageArtifact(image,"filter:c");
if (artifact != (const char *) NULL)
C=atof(artifact);
}
else {
artifact=GetImageArtifact(image,"filter:c");
if (artifact != (const char *) NULL) {
C=atof(artifact);
B=(1.0-C)/2.0; /* Calculate B as if it is a Keys cubic filter */
}
}
/* Convert B,C values into Cubic Coefficents - See CubicBC() */
resize_filter->cubic[0]=( 6.0 -2.0*B )/6.0;
resize_filter->cubic[1]=0.0;
resize_filter->cubic[2]=(-18.0+12.0*B+ 6.0*C)/6.0;
resize_filter->cubic[3]=( 12.0- 9.0*B- 6.0*C)/6.0;
resize_filter->cubic[4]=( 8.0*B+24.0*C)/6.0;
resize_filter->cubic[5]=( -12.0*B-48.0*C)/6.0;
resize_filter->cubic[6]=( 6.0*B+30.0*C)/6.0;
resize_filter->cubic[7]=( - 1.0*B- 6.0*C)/6.0;
}
/* Output filter graph -- for graphing filter result */
artifact=GetImageArtifact(image,"filter:verbose");
if (artifact != (const char *) NULL) {
MagickRealType x;
MagickRealType s = GetResizeFilterSupport(resize_filter);
printf("# support = %lg\n", (double) s);
for ( x = 0.0; x <= s; x+=0.01f )
printf("%5.2lf\t%lf\n", (double) x, (double) GetResizeFilterWeight(resize_filter, x) );
printf("%5.2lf\t%lf\n", (double) s, 0.0 );
}
return(resize_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A d a p t i v e R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AdaptiveResizeImage() adaptively resize image with pixel resampling.
%
% The format of the AdaptiveResizeImage method is:
%
% Image *AdaptiveResizeImage(const Image *image,
% const unsigned long columns,const unsigned long rows,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the resized image.
%
% o rows: the number of rows in the resized image.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *AdaptiveResizeImage(const Image *image,
const unsigned long columns,const unsigned long rows,ExceptionInfo *exception)
{
#define AdaptiveResizeImageTag "Resize/Image"
Image
*resize_image;
long
y;
MagickBooleanType
status;
MagickPixelPacket
pixel;
PointInfo
offset;
register IndexPacket
*resize_indexes;
register long
x;
register PixelPacket
*q;
ResampleFilter
*resample_filter;
ViewInfo
*resize_view;
/*
Adaptively resize image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
resize_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (resize_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(resize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
resize_image=DestroyImage(resize_image);
return((Image *) NULL);
}
GetMagickPixelPacket(image,&pixel);
resample_filter=AcquireResampleFilter(image,exception);
if (image->interpolate == UndefinedInterpolatePixel)
(void) SetResampleFilterInterpolateMethod(resample_filter,
MeshInterpolatePixel);
resize_view=OpenCacheView(resize_image);
for (y=0; y < (long) resize_image->rows; y++)
{
q=SetCacheView(resize_view,0,y,resize_image->columns,1);
if (q == (PixelPacket *) NULL)
break;
resize_indexes=GetIndexes(resize_image);
offset.y=((MagickRealType) y*image->rows/resize_image->rows);
for (x=0; x < (long) resize_image->columns; x++)
{
offset.x=((MagickRealType) x*image->columns/resize_image->columns);
pixel=ResamplePixelColor(resample_filter,offset.x-0.5,offset.y-0.5);
SetPixelPacket(resize_image,&pixel,q,resize_indexes+x);
q++;
}
if (SyncCacheView(resize_view) == MagickFalse)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(QuantumTick(y,image->rows) != MagickFalse))
{
status=image->progress_monitor(AdaptiveResizeImageTag,y,image->rows,
image->client_data);
if (status == MagickFalse)
break;
}
}
resample_filter=DestroyResampleFilter(resample_filter);
resize_view=CloseCacheView(resize_view);
return(resize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ B e s s e l O r d e r O n e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% BesselOrderOne() computes the Bessel function of x of the first kind of
% order 0:
%
% Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8]
%
% j1(x) = x*j1(x);
%
% For x in (8,inf)
%
% j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1))
%
% where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow:
%
% cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4)
% = 1/sqrt(2) * (sin(x) - cos(x))
% sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4)
% = -1/sqrt(2) * (sin(x) + cos(x))
%
% The format of the BesselOrderOne method is:
%
% MagickRealType BesselOrderOne(MagickRealType x)
%
% A description of each parameter follows:
%
% o x: MagickRealType value.
%
*/
#undef I0
static MagickRealType I0(MagickRealType x)
{
MagickRealType
sum,
t,
y;
register long
i;
/*
Zeroth order Bessel function of the first kind.
*/
sum=1.0;
y=x*x/4.0;
t=y;
for (i=2; t > MagickEpsilon; i++)
{
sum+=t;
t*=y/((MagickRealType) i*i);
}
return(sum);
}
#undef J1
static MagickRealType J1(MagickRealType x)
{
MagickRealType
p,
q;
register long
i;
static const double
Pone[] =
{
0.581199354001606143928050809e+21,
-0.6672106568924916298020941484e+20,
0.2316433580634002297931815435e+19,
-0.3588817569910106050743641413e+17,
0.2908795263834775409737601689e+15,
-0.1322983480332126453125473247e+13,
0.3413234182301700539091292655e+10,
-0.4695753530642995859767162166e+7,
0.270112271089232341485679099e+4
},
Qone[] =
{
0.11623987080032122878585294e+22,
0.1185770712190320999837113348e+20,
0.6092061398917521746105196863e+17,
0.2081661221307607351240184229e+15,
0.5243710262167649715406728642e+12,
0.1013863514358673989967045588e+10,
0.1501793594998585505921097578e+7,
0.1606931573481487801970916749e+4,
0.1e+1
};
p=Pone[8];
q=Qone[8];
for (i=7; i >= 0; i--)
{
p=p*x*x+Pone[i];
q=q*x*x+Qone[i];
}
return(p/q);
}
#undef P1
static MagickRealType P1(MagickRealType x)
{
MagickRealType
p,
q;
register long
i;
static const double
Pone[] =
{
0.352246649133679798341724373e+5,
0.62758845247161281269005675e+5,
0.313539631109159574238669888e+5,
0.49854832060594338434500455e+4,
0.2111529182853962382105718e+3,
0.12571716929145341558495e+1
},
Qone[] =
{
0.352246649133679798068390431e+5,
0.626943469593560511888833731e+5,
0.312404063819041039923015703e+5,
0.4930396490181088979386097e+4,
0.2030775189134759322293574e+3,
0.1e+1
};
p=Pone[5];
q=Qone[5];
for (i=4; i >= 0; i--)
{
p=p*(8.0/x)*(8.0/x)+Pone[i];
q=q*(8.0/x)*(8.0/x)+Qone[i];
}
return(p/q);
}
#undef Q1
static MagickRealType Q1(MagickRealType x)
{
MagickRealType
p,
q;
register long
i;
static const double
Pone[] =
{
0.3511751914303552822533318e+3,
0.7210391804904475039280863e+3,
0.4259873011654442389886993e+3,
0.831898957673850827325226e+2,
0.45681716295512267064405e+1,
0.3532840052740123642735e-1
},
Qone[] =
{
0.74917374171809127714519505e+4,
0.154141773392650970499848051e+5,
0.91522317015169922705904727e+4,
0.18111867005523513506724158e+4,
0.1038187585462133728776636e+3,
0.1e+1
};
p=Pone[5];
q=Qone[5];
for (i=4; i >= 0; i--)
{
p=p*(8.0/x)*(8.0/x)+Pone[i];
q=q*(8.0/x)*(8.0/x)+Qone[i];
}
return(p/q);
}
static MagickRealType BesselOrderOne(MagickRealType x)
{
MagickRealType
p,
q;
if (x == 0.0)
return(0.0);
p=x;
if (x < 0.0)
x=(-x);
if (x < 8.0)
return(p*J1(x));
q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin((double) x)-
cos((double) x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin((double) x)+
cos((double) x))));
if (p < 0.0)
q=(-q);
return(q);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y R e s i z e F i l t e r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyResizeFilter() destroy the resize filter.
%
% The format of the AcquireResizeFilter method is:
%
% ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter)
%
% A description of each parameter follows:
%
% o resize_filter: the resize filter.
%
*/
MagickExport ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickSignature);
resize_filter->signature=(~MagickSignature);
resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter);
return(resize_filter);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t R e s i z e F i l t e r S u p p o r t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetResizeFilterSupport() return the current support window size for this
% filter. Note that this may have been enlarged by filter:blur factor.
%
% The format of the GetResizeFilterSupport method is:
%
% MagickRealType GetResizeFilterSupport(const ResizeFilter *resize_filter)
%
% A description of each parameter follows:
%
% o filter: Image filter to use.
%
*/
MagickExport MagickRealType GetResizeFilterSupport(
const ResizeFilter *resize_filter)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickSignature);
return(resize_filter->support*resize_filter->blur);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t R e s i z e F i l t e r W e i g h t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetResizeFilterWeight evaluates the specified resize filter at the point x
% which usally lies between zero and the filters current 'support' and
% returns the weight of the filter function at that point.
%
% The format of the GetResizeFilterWeight method is:
%
% MagickRealType GetResizeFilterWeight(const ResizeFilter *resize_filter,
% const MagickRealType x)
%
% A description of each parameter follows:
%
% o filter: the filter type.
%
% o x: the point.
%
*/
MagickExport MagickRealType GetResizeFilterWeight(
const ResizeFilter *resize_filter,const MagickRealType x)
{
MagickRealType
x_blur,
wscale;
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickSignature);
x_blur = fabs(x)/resize_filter->blur; /* X position with blur scaling */
/* windowing function - scale the weighting filter by this amount */
if ( resize_filter->wsupport < MagickEpsilon || resize_filter->window == Box )
wscale = 1.0; /* Point/Box Filter -- avoid division by zero */
else {
wscale = resize_filter->wsize/resize_filter->wsupport; /* scale window */
wscale = resize_filter->window(x_blur*wscale,resize_filter);
}
/* weighting for the filter at this position */
return( wscale*resize_filter->filter(x_blur,resize_filter) );
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M a g n i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MagnifyImage() is a convenience method that scales an image proportionally
% to twice its size.
%
% The format of the MagnifyImage method is:
%
% Image *MagnifyImage(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 Image *MagnifyImage(const Image *image,ExceptionInfo *exception)
{
Image
*magnify_image;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
magnify_image=ResizeImage(image,2*image->columns,2*image->rows,CubicFilter,
1.0,exception);
return(magnify_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% M i n i f y I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% MinifyImage() is a convenience method that scales an image proportionally
% to half its size.
%
% The format of the MinifyImage method is:
%
% Image *MinifyImage(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 Image *MinifyImage(const Image *image,ExceptionInfo *exception)
{
Image
*minify_image;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
minify_image=ResizeImage(image,image->columns/2,image->rows/2,CubicFilter,
1.0,exception);
return(minify_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s a m p l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResampleImage() resize image in terms of its pixel size, so that when
% displayed at the given resolution it will be the same size in terms of
% real world units as the original image at the original resolution.
%
% The format of the ResampleImage method is:
%
% Image *ResampleImage(Image *image,const double x_resolution,
% const double y_resolution,const FilterTypes filter,const double blur,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image to be resized to fit the given resolution.
%
% o x_resolution: the new image x resolution.
%
% o y_resolution: the new image y resolution.
%
% o filter: Image filter to use.
%
% o blur: the blur factor where > 1 is blurry, < 1 is sharp.
%
*/
MagickExport Image *ResampleImage(const Image *image,const double x_resolution,
const double y_resolution,const FilterTypes filter,const double blur,
ExceptionInfo *exception)
{
#define ResampleImageTag "Resample/Image"
Image
*resample_image;
unsigned long
height,
width;
/*
Initialize sampled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
width=(unsigned long) (x_resolution*image->columns/
(image->x_resolution == 0.0 ? 72.0 : image->x_resolution)+0.5);
height=(unsigned long) (y_resolution*image->rows/
(image->y_resolution == 0.0 ? 72.0 : image->y_resolution)+0.5);
resample_image=ResizeImage(image,width,height,filter,blur,exception);
if (resample_image != (Image *) NULL)
{
resample_image->x_resolution=x_resolution;
resample_image->y_resolution=y_resolution;
}
return(resample_image);
}
#if defined(MAGICKCORE_LQR_DELEGATE)
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% L i q u i d R e s c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% LiquidRescaleImage() rescales image with seam carving.
%
% The format of the LiquidRescaleImage method is:
%
% Image *LiquidRescaleImage(const Image *image,
% const unsigned long columns,const unsigned long rows,
% const double delta_x,const double rigidity,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the rescaled image.
%
% o rows: the number of rows in the rescaled image.
%
% o delta_x: maximum seam transversal step (0 means straight seams).
%
% o rigidity: introduce a bias for non-straight seams (typically 0).
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport Image *LiquidRescaleImage(const Image *image,
const unsigned long columns,const unsigned long rows,
const double delta_x,const double rigidity,ExceptionInfo *exception)
{
#define LiquidRescaleImageTag "Rescale/Image"
const char
*map;
guchar
*packet;
Image
*rescale_image;
int
x,
y;
LqrCarver
*carver;
LqrRetVal
lqr_status;
MagickBooleanType
status;
MagickPixelPacket
pixel;
register IndexPacket
*rescale_indexes;
register PixelPacket
*q;
unsigned char
*pixels;
/*
Liquid rescale image.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
if ((columns <= 2) || (rows <= 2))
return(ZoomImage(image,columns,rows,exception));
if ((columns >= (2*image->columns)) || (rows >= (2*image->rows)))
{
Image
*resize_image;
unsigned long
height,
width;
/*
Honor liquid resize size limitations.
*/
for (width=image->columns; columns >= (2*width-1); width*=2);
for (height=image->rows; rows >= (2*height-1); height*=2);
resize_image=ResizeImage(image,width,height,image->filter,image->blur,
exception);
if (resize_image == (Image *) NULL)
return((Image *) NULL);
rescale_image=LiquidRescaleImage(resize_image,columns,rows,delta_x,
rigidity,exception);
resize_image=DestroyImage(resize_image);
return(rescale_image);
}
map="RGB";
if (image->matte == MagickFalse)
map="RGBA";
if (image->colorspace == CMYKColorspace)
{
map="CMYK";
if (image->matte == MagickFalse)
map="CMYKA";
}
pixels=(unsigned char *) AcquireQuantumMemory(image->columns,image->rows*
strlen(map)*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
return((Image *) NULL);
status=ExportImagePixels(image,0,0,image->columns,image->rows,map,CharPixel,
pixels,exception);
if (status == MagickFalse)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
carver=lqr_carver_new(pixels,image->columns,image->rows,strlen(map));
if (carver == (LqrCarver *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity);
lqr_status=lqr_carver_resize(carver,columns,rows);
rescale_image=CloneImage(image,lqr_carver_get_width(carver),
lqr_carver_get_height(carver),MagickTrue,exception);
if (rescale_image == (Image *) NULL)
{
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
return((Image *) NULL);
}
if (SetImageStorageClass(rescale_image,DirectClass) == MagickFalse)
{
InheritException(exception,&rescale_image->exception);
rescale_image=DestroyImage(rescale_image);
return((Image *) NULL);
}
GetMagickPixelPacket(rescale_image,&pixel);
(void) lqr_carver_scan_reset(carver);
while (lqr_carver_scan(carver,&x,&y,&packet) != 0)
{
q=SetImagePixels(rescale_image,x,y,1,1);
if (q == (PixelPacket *) NULL)
break;
rescale_indexes=GetIndexes(rescale_image);
pixel.red=QuantumRange*(packet[0]/255.0);
pixel.green=QuantumRange*(packet[1]/255.0);
pixel.blue=QuantumRange*(packet[2]/255.0);
if (image->colorspace != CMYKColorspace)
{
if (image->matte == MagickFalse)
pixel.opacity=QuantumRange*(packet[3]/255.0);
}
else
{
pixel.index=QuantumRange*(packet[3]/255.0);
if (image->matte == MagickFalse)
pixel.opacity=QuantumRange*(packet[4]/255.0);
}
SetPixelPacket(rescale_image,&pixel,q,rescale_indexes);
if (SyncImagePixels(rescale_image) == MagickFalse)
break;
}
/*
Relinquish resources.
*/
lqr_carver_destroy(carver);
return(rescale_image);
}
#else
MagickExport Image *LiquidRescaleImage(const Image *image,
const unsigned long magick_unused(columns),
const unsigned long magick_unused(rows),
const double magick_unused(delta_x),
const double magick_unused(rigidity),
ExceptionInfo *exception)
{
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
(void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError,
"DelegateLibrarySupportNotBuiltIn","`%s' (LQR)",image->filename);
return((Image *) NULL);
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e s i z e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ResizeImage() scales an image to the desired dimensions, using
% the given filter (see AcquireFilterInfo() ).
%
% If an undefined filter is given the filter defaults to Mitchell for a
% colormapped image, a image with a matte channel, or if the image is
% enlarged. Otherwise the filter defaults to a Lanczos.
%
% ResizeImage() was inspired by Paul Heckbert's "zoom" program.
%
% The format of the ResizeImage method is:
%
% Image *ResizeImage(Image *image,const unsigned long columns,
% const unsigned long rows,const FilterTypes filter,const double blur,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o filter: Image filter to use.
%
% o blur: the blur factor where > 1 is blurry, < 1 is sharp.
% Typically set this to 1.0.
%
% o exception: Return any errors or warnings in this structure.
%
*/
typedef struct _ContributionInfo
{
MagickRealType
weight;
long
pixel;
} ContributionInfo;
static inline double MagickMax(const double x,const double y)
{
if (x > y)
return(x);
return(y);
}
static inline double MagickMin(const double x,const double y)
{
if (x < y)
return(x);
return(y);
}
static MagickBooleanType HorizontalFilter(const ResizeFilter *resize_filter,
const Image *image,Image *resize_image,const MagickRealType x_factor,
const MagickSizeType span,MagickOffsetType *quantum,ExceptionInfo *exception)
{
#define ResizeImageTag "Resize/Image"
ContributionInfo
*contribution;
long
j,
n,
start,
stop,
x;
MagickBooleanType
status;
MagickPixelPacket
pixel,
zero;
MagickRealType
alpha,
center,
density,
gamma,
scale,
support;
register const IndexPacket
*indexes;
register const PixelPacket
*pixels;
register IndexPacket
*resize_indexes;
register long
i,
y;
register PixelPacket
*resize_pixels;
/*
Apply filter to resize horizontally from image to resize_image.
*/
scale=MagickMax(1.0/x_factor,1.0);
support=scale*GetResizeFilterSupport(resize_filter);
resize_image->storage_class=image->storage_class;
if (support > 0.5)
{
if (SetImageStorageClass(resize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
return(MagickFalse);
}
}
else
{
/*
Support too small even for nearest neighbour
Reduce to point sampling.
*/
support=(MagickRealType) 0.5;
scale=1.0;
}
contribution=(ContributionInfo *) AcquireQuantumMemory((size_t) (2.0*support+
3.0),sizeof(*contribution));
if (contribution == (ContributionInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
scale=1.0/scale;
(void) ResetMagickMemory(&zero,0,sizeof(zero));
for (x=0; x < (long) resize_image->columns; x++)
{
center=(MagickRealType) (x+0.5)/x_factor;
start=(long) (MagickMax(center-support-MagickEpsilon,0.0)+0.5);
stop=(long) (MagickMin(center+support,(double) image->columns)+0.5);
density=0.0;
for (n=0; n < (stop-start); n++)
{
contribution[n].pixel=start+n;
contribution[n].weight=GetResizeFilterWeight(resize_filter,scale*
((MagickRealType) (start+n)-center+0.5));
density+=contribution[n].weight;
}
if ((density != 0.0) && (density != 1.0))
{
/*
Normalize.
*/
density=1.0/density;
for (i=0; i < n; i++)
contribution[i].weight*=density;
}
pixels=AcquireImagePixels(image,contribution[0].pixel,0,(unsigned long)
(contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception);
resize_pixels=SetImagePixels(resize_image,x,0,1,resize_image->rows);
if ((pixels == (const PixelPacket *) NULL) ||
(resize_pixels == (PixelPacket *) NULL))
break;
indexes=AcquireIndexes(image);
resize_indexes=GetIndexes(resize_image);
#pragma omp parallel for private(alpha, gamma, i, j, pixel)
for (y=0; y < (long) resize_image->rows; y++)
{
pixel=zero;
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight;
pixel.red+=alpha*(pixels+j)->red;
pixel.green+=alpha*(pixels+j)->green;
pixel.blue+=alpha*(pixels+j)->blue;
pixel.opacity+=alpha*(pixels+j)->opacity;
}
resize_pixels[y].red=RoundToQuantum(pixel.red);
resize_pixels[y].green=RoundToQuantum(pixel.green);
resize_pixels[y].blue=RoundToQuantum(pixel.blue);
resize_pixels[y].opacity=RoundToQuantum(pixel.opacity);
}
else
{
gamma=0.0;
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight*QuantumScale*((MagickRealType)
QuantumRange-(pixels+j)->opacity);
pixel.red+=alpha*(pixels+j)->red;
pixel.green+=alpha*(pixels+j)->green;
pixel.blue+=alpha*(pixels+j)->blue;
pixel.opacity+=contribution[i].weight*(pixels+j)->opacity;
gamma+=alpha;
}
gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
resize_pixels[y].red=RoundToQuantum(gamma*pixel.red);
resize_pixels[y].green=RoundToQuantum(gamma*pixel.green);
resize_pixels[y].blue=RoundToQuantum(gamma*pixel.blue);
resize_pixels[y].opacity=RoundToQuantum(pixel.opacity);
}
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight;
pixel.index+=alpha*indexes[j];
}
resize_indexes[y]=(IndexPacket) RoundToQuantum(pixel.index);
}
else
{
gamma=0.0;
for (i=0; i < n; i++)
{
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i].pixel-contribution[0].pixel);
alpha=contribution[i].weight*QuantumScale*((MagickRealType)
QuantumRange-(pixels+j)->opacity);
pixel.index+=alpha*indexes[j];
gamma+=alpha;
}
gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
resize_indexes[y]=(IndexPacket) RoundToQuantum(gamma*pixel.index);
}
}
if ((resize_image->storage_class == PseudoClass) &&
(image->storage_class == PseudoClass))
{
i=(long) (MagickMin(MagickMax(center,(double) start),(double) stop-
1.0)+0.5);
j=y*(contribution[n-1].pixel-contribution[0].pixel+1)+
(contribution[i-start].pixel-contribution[0].pixel);
resize_indexes[y]=indexes[j];
}
}
if (SyncImagePixels(resize_image) == MagickFalse)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(QuantumTick(*quantum,span) != MagickFalse))
{
status=image->progress_monitor(ResizeImageTag,(MagickOffsetType)
*quantum,span,image->client_data);
if (status == MagickFalse)
break;
}
(*quantum)++;
}
contribution=(ContributionInfo *) RelinquishMagickMemory(contribution);
return(x == (long) resize_image->columns ? MagickTrue : MagickFalse);
}
static MagickBooleanType VerticalFilter(const ResizeFilter *resize_filter,
const Image *image,Image *resize_image,const MagickRealType y_factor,
const MagickSizeType span,MagickOffsetType *quantum,ExceptionInfo *exception)
{
ContributionInfo
*contribution;
long
j,
n,
start,
stop,
y;
MagickBooleanType
status;
MagickPixelPacket
pixel,
zero;
MagickRealType
alpha,
center,
density,
gamma,
scale,
support;
register const IndexPacket
*indexes;
register const PixelPacket
*pixels;
register IndexPacket
*resize_indexes;
register long
i,
x;
register PixelPacket
*resize_pixels;
/*
Apply filter to resize vertically from image to resize_image.
*/
scale=MagickMax(1.0/y_factor,1.0);
support=scale*GetResizeFilterSupport(resize_filter);
resize_image->storage_class=image->storage_class;
if (support > 0.5)
{
if (SetImageStorageClass(resize_image,DirectClass) == MagickFalse)
{
InheritException(exception,&resize_image->exception);
return(MagickFalse);
}
}
else
{
/*
Support too small even for nearest neighbour
Reduce to point sampling.
*/
support=(MagickRealType) 0.5;
scale=1.0;
}
contribution=(ContributionInfo *) AcquireQuantumMemory((size_t) (2.0*support+
3.0),sizeof(*contribution));
if (contribution == (ContributionInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
scale=1.0/scale;
(void) ResetMagickMemory(&zero,0,sizeof(zero));
for (y=0; y < (long) resize_image->rows; y++)
{
center=(MagickRealType) (y+0.5)/y_factor;
start=(long) (MagickMax(center-support-MagickEpsilon,0.0)+0.5);
stop=(long) (MagickMin(center+support,(double) image->rows)+0.5);
density=0.0;
for (n=0; n < (stop-start); n++)
{
contribution[n].pixel=start+n;
contribution[n].weight=GetResizeFilterWeight(resize_filter,scale*
((MagickRealType) (start+n)-center+0.5));
density+=contribution[n].weight;
}
if ((density != 0.0) && (density != 1.0))
{
/*
Normalize.
*/
density=1.0/density;
for (i=0; i < n; i++)
contribution[i].weight*=density;
}
pixels=AcquireImagePixels(image,0,contribution[0].pixel,image->columns,
(unsigned long) (contribution[n-1].pixel-contribution[0].pixel+1),
exception);
resize_pixels=SetImagePixels(resize_image,0,y,resize_image->columns,1);
if ((pixels == (const PixelPacket *) NULL) ||
(resize_pixels == (PixelPacket *) NULL))
break;
indexes=AcquireIndexes(image);
resize_indexes=GetIndexes(resize_image);
#pragma omp parallel for private(alpha, gamma, i, j, pixel)
for (x=0; x < (long) resize_image->columns; x++)
{
gamma=0.0;
pixel=zero;
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=(long) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight;
pixel.red+=alpha*(pixels+j)->red;
pixel.green+=alpha*(pixels+j)->green;
pixel.blue+=alpha*(pixels+j)->blue;
pixel.opacity+=alpha*(pixels+j)->opacity;
}
resize_pixels[x].red=RoundToQuantum(pixel.red);
resize_pixels[x].green=RoundToQuantum(pixel.green);
resize_pixels[x].blue=RoundToQuantum(pixel.blue);
resize_pixels[x].opacity=RoundToQuantum(pixel.opacity);
}
else
{
for (i=0; i < n; i++)
{
j=(long) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight*QuantumScale*((MagickRealType)
QuantumRange-(pixels+j)->opacity);
pixel.red+=alpha*(pixels+j)->red;
pixel.green+=alpha*(pixels+j)->green;
pixel.blue+=alpha*(pixels+j)->blue;
pixel.opacity+=contribution[i].weight*(pixels+j)->opacity;
gamma+=alpha;
}
gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
resize_pixels[x].red=RoundToQuantum(gamma*pixel.red);
resize_pixels[x].green=RoundToQuantum(gamma*pixel.green);
resize_pixels[x].blue=RoundToQuantum(gamma*pixel.blue);
resize_pixels[x].opacity=RoundToQuantum(pixel.opacity);
}
if ((image->colorspace == CMYKColorspace) &&
(resize_image->colorspace == CMYKColorspace))
{
gamma=0.0;
if (image->matte == MagickFalse)
{
for (i=0; i < n; i++)
{
j=(long) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight;
pixel.index+=alpha*indexes[j];
}
resize_indexes[x]=(IndexPacket) RoundToQuantum(pixel.index);
}
else
{
for (i=0; i < n; i++)
{
j=(long) ((contribution[i].pixel-contribution[0].pixel)*
image->columns+x);
alpha=contribution[i].weight*QuantumScale*((MagickRealType)
QuantumRange-(pixels+j)->opacity);
pixel.index+=alpha*indexes[j];
gamma+=alpha;
}
gamma=1.0/(fabs((double) gamma) <= MagickEpsilon ? 1.0 : gamma);
resize_indexes[x]=(IndexPacket) RoundToQuantum(gamma*pixel.index);
}
}
if ((resize_image->storage_class == PseudoClass) &&
(image->storage_class == PseudoClass))
{
i=(long) (MagickMin(MagickMax(center,(double) start),(double) stop-
1.0)+0.5);
j=(long) ((contribution[i-start].pixel-contribution[0].pixel)*
image->columns+x);
resize_indexes[x]=indexes[j];
}
}
if (SyncImagePixels(resize_image) == MagickFalse)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(QuantumTick(*quantum,span) != MagickFalse))
{
status=image->progress_monitor(ResizeImageTag,(MagickOffsetType)
*quantum,span,image->client_data);
if (status == MagickFalse)
break;
}
(*quantum)++;
}
contribution=(ContributionInfo *) RelinquishMagickMemory(contribution);
return(y == (long) resize_image->rows ? MagickTrue : MagickFalse);
}
MagickExport Image *ResizeImage(const Image *image,const unsigned long columns,
const unsigned long rows,const FilterTypes filter,const double blur,
ExceptionInfo *exception)
{
FilterTypes
filter_type;
Image
*filter_image,
*resize_image;
MagickRealType
x_factor,
y_factor;
MagickSizeType
span;
MagickStatusType
status;
ResizeFilter
*resize_filter;
MagickOffsetType
quantum;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
/*
Initialize resize image attributes.
*/
if ((columns == 0) || (rows == 0))
ThrowImageException(ImageError,"NegativeOrZeroImageSize");
if ((columns == image->columns) && (rows == image->rows) &&
(filter == UndefinedFilter) && (blur == 1.0))
return(CloneImage(image,0,0,MagickTrue,exception));
resize_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (resize_image == (Image *) NULL)
return((Image *) NULL);
/*
Scaling, Acquire filter, and contribution info
*/
x_factor=(MagickRealType) resize_image->columns/(MagickRealType)
image->columns;
y_factor=(MagickRealType) resize_image->rows/(MagickRealType) image->rows;
filter_type=LanczosFilter;
if (filter != UndefinedFilter)
filter_type=filter;
else
if ((x_factor == 1.0) && (y_factor == 1.0))
filter_type=PointFilter;
else
if ((image->storage_class == PseudoClass) ||
(image->matte != MagickFalse) || ((x_factor*y_factor) > 1.0))
filter_type=MitchellFilter;
resize_filter=AcquireResizeFilter(image,filter_type,blur,MagickFalse,
exception);
/*
Resize image.
*/
quantum=0;
if ((columns*((MagickSizeType) image->rows+rows)) >
(rows*((MagickSizeType) image->columns+columns)))
{
filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception);
if (filter_image == (Image *) NULL)
{
resize_image=DestroyImage(resize_image);
resize_filter=DestroyResizeFilter(resize_filter);
return((Image *) NULL);
}
span=(MagickSizeType) (filter_image->columns+resize_image->rows);
status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span,
&quantum,exception);
status|=VerticalFilter(resize_filter,filter_image,resize_image,y_factor,
span,&quantum,exception);
}
else
{
filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception);
if (filter_image == (Image *) NULL)
{
resize_image=DestroyImage(resize_image);
resize_filter=DestroyResizeFilter(resize_filter);
return((Image *) NULL);
}
span=(MagickSizeType) (resize_image->columns+filter_image->rows);
status=VerticalFilter(resize_filter,image,filter_image,y_factor,span,
&quantum,exception);
status|=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor,
span,&quantum,exception);
}
/*
Free allocated memory.
*/
filter_image=DestroyImage(filter_image);
resize_filter=DestroyResizeFilter(resize_filter);
if (status == MagickFalse)
{
resize_image=DestroyImage(resize_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
return(resize_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S a m p l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SampleImage() scales an image to the desired dimensions with pixel
% sampling. Unlike other scaling methods, this method does not introduce
% any additional color into the scaled image.
%
% The format of the SampleImage method is:
%
% Image *SampleImage(const Image *image,const unsigned long columns,
% const unsigned long rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the sampled image.
%
% o rows: the number of rows in the sampled image.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *SampleImage(const Image *image,const unsigned long columns,
const unsigned long rows,ExceptionInfo *exception)
{
#define SampleImageTag "Sample/Image"
Image
*sample_image;
long
j,
*x_offset,
y,
*y_offset;
MagickBooleanType
status;
register const IndexPacket
*indexes;
register const PixelPacket
*pixels;
register IndexPacket
*sample_indexes;
register long
x;
register PixelPacket
*sample_pixels;
/*
Initialize sampled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((columns == 0) || (rows == 0))
ThrowImageException(ImageError,"NegativeOrZeroImageSize");
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
sample_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (sample_image == (Image *) NULL)
return((Image *) NULL);
/*
Allocate scan line buffer and column offset buffers.
*/
x_offset=(long *) AcquireQuantumMemory((size_t) sample_image->columns,
sizeof(*x_offset));
y_offset=(long *) AcquireQuantumMemory((size_t) sample_image->rows,
sizeof(*y_offset));
if ((x_offset == (long *) NULL) || (y_offset == (long *) NULL))
{
sample_image=DestroyImage(sample_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Initialize pixel offsets.
*/
for (x=0; x < (long) sample_image->columns; x++)
x_offset[x]=(long) (((MagickRealType) x+0.5)*image->columns/
sample_image->columns);
for (y=0; y < (long) sample_image->rows; y++)
y_offset[y]=(long) (((MagickRealType) y+0.5)*image->rows/
sample_image->rows);
/*
Sample each row.
*/
j=(-1);
pixels=AcquireImagePixels(image,0,0,image->columns,1,exception);
indexes=AcquireIndexes(image);
for (y=0; y < (long) sample_image->rows; y++)
{
sample_pixels=SetImagePixels(sample_image,0,y,sample_image->columns,1);
if (sample_pixels == (PixelPacket *) NULL)
break;
sample_indexes=GetIndexes(sample_image);
if (j != y_offset[y])
{
/*
Read a scan line.
*/
j=y_offset[y];
pixels=AcquireImagePixels(image,0,j,image->columns,1,exception);
if (pixels == (const PixelPacket *) NULL)
break;
indexes=AcquireIndexes(image);
}
/*
Sample each column.
*/
for (x=0; x < (long) sample_image->columns; x++)
sample_pixels[x]=pixels[x_offset[x]];
if ((image->storage_class == PseudoClass) ||
(image->colorspace == CMYKColorspace))
for (x=0; x < (long) sample_image->columns; x++)
sample_indexes[x]=indexes[x_offset[x]];
if (SyncImagePixels(sample_image) == MagickFalse)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(QuantumTick(y,image->rows) != MagickFalse))
{
status=image->progress_monitor(SampleImageTag,y,image->rows,
image->client_data);
if (status == MagickFalse)
break;
}
}
y_offset=(long *) RelinquishMagickMemory(y_offset);
x_offset=(long *) RelinquishMagickMemory(x_offset);
return(sample_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S c a l e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ScaleImage() changes the size of an image to the given dimensions.
%
% The format of the ScaleImage method is:
%
% Image *ScaleImage(const Image *image,const unsigned long columns,
% const unsigned long rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *ScaleImage(const Image *image,const unsigned long columns,
const unsigned long rows,ExceptionInfo *exception)
{
#define ScaleImageTag "Scale/Image"
Image
*scale_image;
long
number_rows,
y;
MagickBooleanType
next_column,
next_row,
status;
MagickPixelPacket
pixel,
*scale_scanline,
*scanline,
*x_vector,
*y_vector,
zero;
PointInfo
scale,
span;
register const IndexPacket
*indexes;
register const PixelPacket
*p;
register IndexPacket
*scale_indexes;
register long
i,
x;
register MagickPixelPacket
*s,
*t;
register PixelPacket
*q;
/*
Initialize scaled image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
if ((columns == 0) || (rows == 0))
return((Image *) NULL);
if ((columns == image->columns) && (rows == image->rows))
return(CloneImage(image,0,0,MagickTrue,exception));
scale_image=CloneImage(image,columns,rows,MagickTrue,exception);
if (scale_image == (Image *) NULL)
return((Image *) NULL);
if (SetImageStorageClass(scale_image,DirectClass) == MagickFalse)
{
InheritException(exception,&scale_image->exception);
scale_image=DestroyImage(scale_image);
return((Image *) NULL);
}
/*
Allocate memory.
*/
x_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*x_vector));
scanline=x_vector;
if (image->rows != scale_image->rows)
scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*scanline));
scale_scanline=(MagickPixelPacket *) AcquireQuantumMemory((size_t)
scale_image->columns,sizeof(*scale_scanline));
y_vector=(MagickPixelPacket *) AcquireQuantumMemory((size_t) image->columns,
sizeof(*y_vector));
if ((scanline == (MagickPixelPacket *) NULL) ||
(scale_scanline == (MagickPixelPacket *) NULL) ||
(x_vector == (MagickPixelPacket *) NULL) ||
(y_vector == (MagickPixelPacket *) NULL))
{
scale_image=DestroyImage(scale_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Scale image.
*/
number_rows=0;
next_row=MagickTrue;
span.y=1.0;
scale.y=(double) scale_image->rows/(double) image->rows;
(void) ResetMagickMemory(y_vector,0,(size_t) image->columns*
sizeof(*y_vector));
GetMagickPixelPacket(image,&pixel);
(void) ResetMagickMemory(&zero,0,sizeof(zero));
i=0;
for (y=0; y < (long) scale_image->rows; y++)
{
q=SetImagePixels(scale_image,0,y,scale_image->columns,1);
if (q == (PixelPacket *) NULL)
break;
scale_indexes=GetIndexes(scale_image);
if (scale_image->rows == image->rows)
{
/*
Read a new scanline.
*/
p=AcquireImagePixels(image,0,i++,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=AcquireIndexes(image);
for (x=0; x < (long) image->columns; x++)
{
x_vector[x].red=(MagickRealType) p->red;
x_vector[x].green=(MagickRealType) p->green;
x_vector[x].blue=(MagickRealType) p->blue;
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) p->opacity;
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) indexes[x];
p++;
}
}
else
{
/*
Scale Y direction.
*/
while (scale.y < span.y)
{
if ((next_row != MagickFalse) && (number_rows < (long) image->rows))
{
/*
Read a new scanline.
*/
p=AcquireImagePixels(image,0,i++,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=AcquireIndexes(image);
for (x=0; x < (long) image->columns; x++)
{
x_vector[x].red=(MagickRealType) p->red;
x_vector[x].green=(MagickRealType) p->green;
x_vector[x].blue=(MagickRealType) p->blue;
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) p->opacity;
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) indexes[x];
p++;
}
number_rows++;
}
for (x=0; x < (long) image->columns; x++)
{
y_vector[x].red+=scale.y*x_vector[x].red;
y_vector[x].green+=scale.y*x_vector[x].green;
y_vector[x].blue+=scale.y*x_vector[x].blue;
if (scale_image->matte != MagickFalse)
y_vector[x].opacity+=scale.y*x_vector[x].opacity;
if (scale_indexes != (IndexPacket *) NULL)
y_vector[x].index+=scale.y*x_vector[x].index;
}
span.y-=scale.y;
scale.y=(double) scale_image->rows/(double) image->rows;
next_row=MagickTrue;
}
if ((next_row != MagickFalse) && (number_rows < (long) image->rows))
{
/*
Read a new scanline.
*/
p=AcquireImagePixels(image,0,i++,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=AcquireIndexes(image);
for (x=0; x < (long) image->columns; x++)
{
x_vector[x].red=(MagickRealType) p->red;
x_vector[x].green=(MagickRealType) p->green;
x_vector[x].blue=(MagickRealType) p->blue;
if (image->matte != MagickFalse)
x_vector[x].opacity=(MagickRealType) p->opacity;
if (indexes != (IndexPacket *) NULL)
x_vector[x].index=(MagickRealType) indexes[x];
p++;
}
number_rows++;
next_row=MagickFalse;
}
s=scanline;
for (x=0; x < (long) image->columns; x++)
{
pixel.red=y_vector[x].red+span.y*x_vector[x].red;
pixel.green=y_vector[x].green+span.y*x_vector[x].green;
pixel.blue=y_vector[x].blue+span.y*x_vector[x].blue;
if (image->matte != MagickFalse)
pixel.opacity=y_vector[x].opacity+span.y*x_vector[x].opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index=y_vector[x].index+span.y*x_vector[x].index;
s->red=pixel.red;
s->green=pixel.green;
s->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
s->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
s->index=pixel.index;
s++;
y_vector[x]=zero;
}
scale.y-=span.y;
if (scale.y <= 0)
{
scale.y=(double) scale_image->rows/(double) image->rows;
next_row=MagickTrue;
}
span.y=1.0;
}
if (scale_image->columns == image->columns)
{
/*
Transfer scanline to scaled image.
*/
s=scanline;
for (x=0; x < (long) scale_image->columns; x++)
{
q->red=RoundToQuantum(s->red);
q->green=RoundToQuantum(s->green);
q->blue=RoundToQuantum(s->blue);
if (scale_image->matte != MagickFalse)
q->opacity=RoundToQuantum(s->opacity);
if (scale_indexes != (IndexPacket *) NULL)
scale_indexes[x]=(IndexPacket) RoundToQuantum(s->index);
q++;
s++;
}
}
else
{
/*
Scale X direction.
*/
pixel=zero;
next_column=MagickFalse;
span.x=1.0;
s=scanline;
t=scale_scanline;
for (x=0; x < (long) image->columns; x++)
{
scale.x=(double) scale_image->columns/(double) image->columns;
while (scale.x >= span.x)
{
if (next_column != MagickFalse)
{
pixel=zero;
t++;
}
pixel.red+=span.x*s->red;
pixel.green+=span.x*s->green;
pixel.blue+=span.x*s->blue;
if (image->matte != MagickFalse)
pixel.opacity+=span.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=span.x*s->index;
t->red=pixel.red;
t->green=pixel.green;
t->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
t->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
t->index=pixel.index;
scale.x-=span.x;
span.x=1.0;
next_column=MagickTrue;
}
if (scale.x > 0)
{
if (next_column != MagickFalse)
{
pixel=zero;
next_column=MagickFalse;
t++;
}
pixel.red+=scale.x*s->red;
pixel.green+=scale.x*s->green;
pixel.blue+=scale.x*s->blue;
if (scale_image->matte != MagickFalse)
pixel.opacity+=scale.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=scale.x*s->index;
span.x-=scale.x;
}
s++;
}
if (span.x > 0)
{
s--;
pixel.red+=span.x*s->red;
pixel.green+=span.x*s->green;
pixel.blue+=span.x*s->blue;
if (scale_image->matte != MagickFalse)
pixel.opacity+=span.x*s->opacity;
if (scale_indexes != (IndexPacket *) NULL)
pixel.index+=span.x*s->index;
}
if ((next_column == MagickFalse) &&
((long) (t-scale_scanline) < (long) scale_image->columns))
{
t->red=pixel.red;
t->green=pixel.green;
t->blue=pixel.blue;
if (scale_image->matte != MagickFalse)
t->opacity=pixel.opacity;
if (scale_indexes != (IndexPacket *) NULL)
t->index=pixel.index;
}
/*
Transfer scanline to scaled image.
*/
t=scale_scanline;
for (x=0; x < (long) scale_image->columns; x++)
{
q->red=RoundToQuantum(t->red);
q->green=RoundToQuantum(t->green);
q->blue=RoundToQuantum(t->blue);
if (scale_image->matte != MagickFalse)
q->opacity=RoundToQuantum(t->opacity);
if (scale_indexes != (IndexPacket *) NULL)
scale_indexes[x]=(IndexPacket) RoundToQuantum(t->index);
t++;
q++;
}
}
if (SyncImagePixels(scale_image) == MagickFalse)
break;
if ((image->progress_monitor != (MagickProgressMonitor) NULL) &&
(QuantumTick(y,image->rows) != MagickFalse))
{
status=image->progress_monitor(ScaleImageTag,y,image->rows,
image->client_data);
if (status == MagickFalse)
break;
}
}
/*
Free allocated memory.
*/
y_vector=(MagickPixelPacket *) RelinquishMagickMemory(y_vector);
scale_scanline=(MagickPixelPacket *) RelinquishMagickMemory(scale_scanline);
if (scale_image->rows != image->rows)
scanline=(MagickPixelPacket *) RelinquishMagickMemory(scanline);
x_vector=(MagickPixelPacket *) RelinquishMagickMemory(x_vector);
return(scale_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ S e t R e s i z e F i l t e r S u p p o r t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetResizeFilterSupport() specifies which IR filter to use to window
%
% The format of the SetResizeFilterSupport method is:
%
% void SetResizeFilterSupport(ResizeFilter *resize_filter,
% const MagickRealType support)
%
% A description of each parameter follows:
%
% o resize_filter: the resize filter.
%
% o support: the filter spport radius.
%
*/
MagickExport void SetResizeFilterSupport(ResizeFilter *resize_filter,
const MagickRealType support)
{
assert(resize_filter != (ResizeFilter *) NULL);
assert(resize_filter->signature == MagickSignature);
resize_filter->support=support;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T h u m b n a i l I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ThumbnailImage() changes the size of an image to the given dimensions and
% removes any associated profiles. The goal is to produce small low cost
% thumbnail images suited for display on the Web.
%
% The format of the ThumbnailImage method is:
%
% Image *ThumbnailImage(const Image *image,const unsigned long columns,
% const unsigned long rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o columns: the number of columns in the scaled image.
%
% o rows: the number of rows in the scaled image.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *ThumbnailImage(const Image *image,
const unsigned long columns,const unsigned long rows,ExceptionInfo *exception)
{
char
value[MaxTextExtent];
const char
*attribute;
Image
*sample_image,
*thumbnail_image;
MagickRealType
x_factor,
y_factor;
struct stat
attributes;
unsigned long
version;
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
x_factor=(MagickRealType) columns/(MagickRealType) image->columns;
y_factor=(MagickRealType) rows/(MagickRealType) image->rows;
if ((x_factor*y_factor) > 0.1)
{
thumbnail_image=ZoomImage(image,columns,rows,exception);
if (thumbnail_image != (Image *) NULL)
(void) StripImage(thumbnail_image);
return(thumbnail_image);
}
sample_image=SampleImage(image,5*columns,5*rows,exception);
if (sample_image == (Image *) NULL)
return((Image *) NULL);
thumbnail_image=ZoomImage(sample_image,columns,rows,exception);
sample_image=DestroyImage(sample_image);
if (thumbnail_image == (Image *) NULL)
return(thumbnail_image);
if (thumbnail_image->matte == MagickFalse)
(void) SetImageOpacity(thumbnail_image,OpaqueOpacity);
thumbnail_image->depth=8;
thumbnail_image->interlace=NoInterlace;
(void) StripImage(thumbnail_image);
(void) CopyMagickString(value,image->magick_filename,MaxTextExtent);
if (strstr(image->magick_filename,"///") == (char *) NULL)
(void) FormatMagickString(value,MaxTextExtent,"file:///%s",
image->magick_filename);
(void) SetImageProperty(thumbnail_image,"Thumb::URI",value);
(void) CopyMagickString(value,image->magick_filename,MaxTextExtent);
if (stat(image->filename,&attributes) == 0)
{
(void) FormatMagickString(value,MaxTextExtent,"%ld",(long)
attributes.st_mtime);
(void) SetImageProperty(thumbnail_image,"Thumb::MTime",value);
}
(void) FormatMagickString(value,MaxTextExtent,"%ld",(long)
attributes.st_mtime);
(void) FormatMagickSize(GetBlobSize(image),value);
(void) SetImageProperty(thumbnail_image,"Thumb::Size",value);
(void) FormatMagickString(value,MaxTextExtent,"image/%s",image->magick);
LocaleLower(value);
(void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value);
attribute=GetImageProperty(image,"comment");
if ((attribute != (const char *) NULL) &&
(value != (char *) NULL))
(void) SetImageProperty(thumbnail_image,"description",value);
(void) SetImageProperty(thumbnail_image,"software",
GetMagickVersion(&version));
(void) FormatMagickString(value,MaxTextExtent,"%lu",image->magick_columns);
(void) SetImageProperty(thumbnail_image,"Thumb::Image::Width",value);
(void) FormatMagickString(value,MaxTextExtent,"%lu",image->magick_rows);
(void) SetImageProperty(thumbnail_image,"Thumb::Image::height",value);
(void) FormatMagickString(value,MaxTextExtent,"%lu",
GetImageListLength(image));
(void) SetImageProperty(thumbnail_image,"Thumb::Document::Pages",value);
return(thumbnail_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% Z o o m I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ZoomImage() creates a new image that is a scaled size of an existing one.
% It allocates the memory necessary for the new Image structure and returns a
% pointer to the new image. The Point filter gives fast pixel replication,
% Triangle is equivalent to bi-linear interpolation, and Mitchel giver slower,
% very high-quality results. See Graphic Gems III for details on this
% algorithm.
%
% The filter member of the Image structure specifies which image filter to
% use. Blur specifies the blur factor where > 1 is blurry, < 1 is sharp.
%
% The format of the ZoomImage method is:
%
% Image *ZoomImage(const Image *image,const unsigned long columns,
% const unsigned long rows,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o zoom_image: Method ZoomImage returns a pointer to the image after
% scaling. A null image is returned if there is a memory shortage.
%
% o image: the image.
%
% o columns: An integer that specifies the number of columns in the zoom
% image.
%
% o rows: An integer that specifies the number of rows in the scaled
% image.
%
% o exception: Return any errors or warnings in this structure.
%
*/
MagickExport Image *ZoomImage(const Image *image,const unsigned long columns,
const unsigned long rows,ExceptionInfo *exception)
{
Image
*zoom_image;
assert(image != (const Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
zoom_image=ResizeImage(image,columns,rows,image->filter,image->blur,
exception);
return(zoom_image);
}
|
scanrom.c | #include "scanrom.h"
#include "floram_util.h"
void scanrom_read_with_bitvector_offline(uint8_t * output_share, uint8_t * rom_memory, bool * bitvector, size_t memblocksize, size_t blockcount) {
memset(output_share, 0, memblocksize);
uint64_t * rm = rom_memory;
bool * biv = bitvector;
uint64_t ** sums;
size_t threadcount;
floram_set_procs_for_data_size(memblocksize * blockcount);
#pragma omp parallel
{
threadcount = omp_get_num_threads();
#pragma omp single
sums = malloc(threadcount * sizeof(uint64_t *));
uint64_t * s;
floram_zpma(&s, 16, memblocksize);
sums[omp_get_thread_num()] = s;
#pragma omp for schedule(guided)
for (size_t ii = 0; ii < blockcount; ii++) {
#pragma omp simd aligned(rm,biv,s:16)
for (size_t jj = 0; jj < memblocksize /sizeof(uint64_t); jj++) {
s[jj] ^= biv[ii] * rm[ii * ((memblocksize) /sizeof(uint64_t)) + jj];
}
}
}
for (size_t ii = 0; ii < threadcount; ii++) {
for (size_t jj = 0; jj < memblocksize /sizeof(uint64_t); jj++) {
((uint64_t *)output_share)[jj] ^= sums[ii][jj];
}
free(sums[ii]);
}
free(sums);
}
void scanrom_read_with_blockvector_offline(uint8_t * z_and_output, uint8_t * rom_memory, bool * bitvector, uint8_t * blockvector, size_t memblocksize, size_t blockcount) {
uint64_t * rm = rom_memory;
uint64_t ** sums;
size_t threadcount;
floram_set_procs_for_data_size(memblocksize * blockcount);
#pragma omp parallel
{
threadcount = omp_get_num_threads();
#pragma omp single
sums = malloc(threadcount * sizeof(uint64_t *));
uint64_t * s;
floram_zpma(&s, 16, memblocksize);
sums[omp_get_thread_num()] = s;
#pragma omp for schedule(guided)
for (size_t ii = 0; ii < blockcount; ii++) {
bool bitvector_bit = bitvector[ii/(BLOCKSIZE * 8)];
uint8_t z_block_part = z_and_output[(ii%(BLOCKSIZE*8))/8];
uint8_t * blockvector_block = &blockvector[(ii/(BLOCKSIZE * 8))*BLOCKSIZE];
uint8_t blockvector_block_part = blockvector_block[(ii%(BLOCKSIZE*8))/8];
bool b_temp = (((bitvector_bit * z_block_part) ^ blockvector_block_part) >> (ii % 8)) & 0x1;
#pragma omp simd aligned(rm,s:16)
for (size_t jj = 0; jj < memblocksize /sizeof(uint64_t); jj++) {
s[jj] ^= b_temp * rm[ii * memblocksize/sizeof(uint64_t) + jj];
}
}
}
memset(z_and_output, 0, memblocksize);
for (size_t ii = 0; ii < threadcount; ii++) {
for (size_t jj = 0; jj < memblocksize /sizeof(uint64_t); jj++) {
((uint64_t *)z_and_output)[jj] ^= sums[ii][jj];
}
free(sums[ii]);
}
free(sums);
}
#ifdef SCANROM_DISABLE_ENCRYPTION
void scanrom_encrypt_offline(uint8_t * out, uint8_t * in, uint8_t* key, size_t index, size_t blockmultiple, size_t blockcount) {
if (in == NULL) {
memset(out, 0, BLOCKSIZE * blockcount * blockmultiple);
} else {
memcpy(out, in, BLOCKSIZE * blockcount * blockmultiple);
}
}
#else
void scanrom_encrypt_offline(uint8_t * out, uint8_t * in, uint8_t* key, size_t index, size_t blockmultiple, size_t blockcount) {
offline_expand_from(out, key, index*blockmultiple, blockcount * blockmultiple);
if (in != NULL) {
floram_set_procs_for_data_size(BLOCKSIZE * blockmultiple * blockcount);
#pragma omp parallel for simd schedule(guided)
for (size_t ii = 0; ii < blockcount * blockmultiple * BLOCKSIZE / sizeof(uint64_t); ii++) {
((uint64_t *)out)[ii] ^= ((uint64_t *)in)[ii];
}
}
}
#endif
void scanwrom_write_with_blockvector_offline(uint8_t * wrom_memory, uint8_t * blockvector, bool * bitvector, uint8_t*z_block, size_t memblocksize, size_t blockcount) {
uint64_t * wm = wrom_memory;
uint64_t * blv = blockvector;
bool * biv = bitvector;
uint64_t * z = z_block;
floram_set_procs_for_data_size(memblocksize * blockcount);
#pragma omp parallel for schedule(guided)
for (size_t ii = 0; ii< blockcount; ii++) {
#pragma omp simd aligned(wm,blv,biv,z:16)
for (size_t jj = 0; jj < memblocksize/sizeof(uint64_t); jj++) {
wm[ii * memblocksize/sizeof(uint64_t) + jj] ^= blv[ii * memblocksize/sizeof(uint64_t) + jj] ^ (biv[ii] * z[jj]);
}
}
} |
3d7pt_var.c | /*
* Order-1, 3D 7 point stencil with variable coefficients
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, m, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+2;
Ny = atoi(argv[2])+2;
Nz = atoi(argv[3])+2;
}
if (argc > 4)
Nt = atoi(argv[4]);
// allocate the arrays
double ****A = (double ****) malloc(sizeof(double***)*2);
for(m=0; m<2;m++){
A[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
double ****coef = (double ****) malloc(sizeof(double***)*7);
for(m=0; m<7;m++){
coef[m] = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
coef[m][i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
coef[m][i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 32;
tile_size[1] = 32;
tile_size[2] = 32;
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;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
for (m=0; m<7; m++) {
for (i=1; i<Nz; i++) {
for (j=1; j<Ny; j++) {
for (k=1; k<Nx; k++) {
coef[m][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#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] = coef[0][i][j][k] * A[t%2][i ][j ][k ] +
coef[1][i][j][k] * A[t%2][i-1][j ][k ] +
coef[2][i][j][k] * A[t%2][i ][j-1][k ] +
coef[3][i][j][k] * A[t%2][i ][j ][k-1] +
coef[4][i][j][k] * A[t%2][i+1][j ][k ] +
coef[5][i][j][k] * A[t%2][i ][j+1][k ] +
coef[6][i][j][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, "variable no-symmetry")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
}
free(A[0][i]);
free(A[1][i]);
}
free(A[0]);
free(A[1]);
for(m=0; m<7;m++){
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(coef[m][i][j]);
}
free(coef[m][i]);
}
free(coef[m]);
}
return 0;
}
|
Efficient_RANSAC.h | // Copyright (c) 2015 INRIA Sophia-Antipolis (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : Sven Oesau, Yannick Verdie, Clément Jamin, Pierre Alliez
//
#ifndef CGAL_SHAPE_DETECTION_EFFICIENT_RANSAC_H
#define CGAL_SHAPE_DETECTION_EFFICIENT_RANSAC_H
#include <CGAL/license/Shape_detection.h>
#include <CGAL/Random.h>
#include <CGAL/Shape_detection/Efficient_RANSAC/Octree.h>
#include <CGAL/Shape_detection/Efficient_RANSAC/Shape_base.h>
#include <CGAL/Shape_detection/Efficient_RANSAC/Plane.h>
// for octree ------------------------------
#include <boost/iterator/filter_iterator.hpp>
#include <CGAL/bounding_box.h>
#include <CGAL/Iterator_range.h>
//----------
#include <vector>
#include <cmath>
#include <limits>
#include <fstream>
#include <sstream>
#include <functional>
// boost --------------
#include <CGAL/boost/iterator/counting_iterator.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
//---------------------
namespace CGAL {
namespace Shape_detection {
/*!
\ingroup PkgShapeDetectionRANSAC
\brief Shape detection algorithm based on the RANSAC method.
Given a point set in 3D space with unoriented normals, sampled on surfaces,
this class enables to detect subsets of connected points lying on the surface of primitive shapes.
Each input point is assigned to either none or at most one detected primitive
shape. The implementation follows \cgalCite{schnabel2007efficient}.
\tparam Traits must be a model of `EfficientRANSACTraits`.
*/
template <class Traits>
class Efficient_RANSAC {
public:
/// \cond SKIP_IN_MANUAL
struct Filter_unassigned_points {
Filter_unassigned_points() : m_shape_index(dummy) {}
Filter_unassigned_points(const std::vector<int> &shapeIndex)
: m_shape_index(shapeIndex) {}
bool operator()(std::size_t x) {
if (x < m_shape_index.size())
return m_shape_index[x] == -1;
else return true; // to prevent infinite incrementing
}
const std::vector<int>& m_shape_index;
std::vector<int> dummy;
};
typedef boost::filter_iterator<Filter_unassigned_points,
boost::counting_iterator<std::size_t, boost::use_default, std::ptrdiff_t> > Point_index_iterator;
///< iterator for indices of points.
/// \endcond
/// \name Types
/// @{
/// \cond SKIP_IN_MANUAL
typedef typename Traits::Input_range::iterator Input_iterator;
typedef typename Traits::FT FT; ///< number type.
typedef typename Traits::Point_3 Point; ///< point type.
typedef typename Traits::Vector_3 Vector; ///< vector type.
/// \endcond
typedef typename Traits::Input_range Input_range;
///< Model of the concept `Range` with random access iterators, providing input points and normals
/// through the following two property maps.
typedef typename Traits::Point_map Point_map;
///< Property map to access the location of an input point.
typedef typename Traits::Normal_map Normal_map;
///< Property map to access the unoriented normal of an input point.
typedef Shape_base<Traits> Shape; ///< Shape type.
typedef Plane<Traits> Plane_shape; ///< %Plane shape type.
#ifdef DOXYGEN_RUNNING
typedef unspecified_type Shape_range;
///< `Iterator_range` with a bidirectional constant iterator type with value type `boost::shared_ptr<Shape>`.
typedef unspecified_type Plane_range;
///< `Iterator_range` with a bidirectional constant iterator type with value type `boost::shared_ptr<Plane_shape>`.
#else
struct Shape_range : public Iterator_range<
typename std::vector<boost::shared_ptr<Shape> >::const_iterator> {
typedef Iterator_range<
typename std::vector<boost::shared_ptr<Shape> >::const_iterator> Base;
Shape_range(boost::shared_ptr<std::vector<boost::shared_ptr<Shape> > >
extracted_shapes) : Base(make_range(extracted_shapes->begin(),
extracted_shapes->end())), m_extracted_shapes(extracted_shapes) {}
private:
boost::shared_ptr<std::vector<boost::shared_ptr<Shape> > >
m_extracted_shapes; // keeps a reference to the shape vector
};
struct Plane_range : public Iterator_range<
typename std::vector<boost::shared_ptr<Plane_shape> >::const_iterator> {
typedef Iterator_range<
typename std::vector<boost::shared_ptr<Plane_shape> >::const_iterator> Base;
Plane_range(boost::shared_ptr<std::vector<boost::shared_ptr<Plane_shape> > >
extracted_shapes) : Base(make_range(extracted_shapes->begin(),
extracted_shapes->end())), m_extracted_shapes(extracted_shapes) {}
private:
boost::shared_ptr<std::vector<boost::shared_ptr<Plane_shape> > >
m_extracted_shapes; // keeps a reference to the shape vector
};
#endif
#ifdef DOXYGEN_RUNNING
typedef unspecified_type Point_index_range;
///< `Iterator_range` with a bidirectional iterator with value type `std::size_t`
/// as indices into the input data that has not been assigned to a shape.
/// As this range class has no `size()` method, the method
/// `Efficient_RANSAC::number_of_unassigned_points()` is provided.
#else
typedef Iterator_range<Point_index_iterator>
Point_index_range;
#endif
/// @}
/// \name Parameters
/// @{
/*!
Parameters for the shape detection algorithm. They are explained in detail
in Section \ref Shape_detection_RANSACParameters of the User Manual.
*/
struct Parameters {
Parameters()
: probability((FT) 0.01)
, min_points((std::numeric_limits<std::size_t>::max)())
, epsilon(-1)
, normal_threshold((FT) 0.9)
, cluster_epsilon(-1)
{}
/*!
Probability to control search endurance.
%Default value is 0.05.
A lower probability provides a higher reliability and determinism at the cost
of longer running time due to a higher search endurance.
It must belong to the interval [0, 1].
*/
FT probability;
/*!
Minimum number of points in a shape.
%Default value is 1% of total number of input points.
It must belong to the interval [0, +inf).
*/
std::size_t min_points;
/*!
Maximum acceptable Euclidean distance between a point and a shape.
%Default value is 1% of the bounding box diagonal.
It must belong to the interval [0, +inf).
*/
FT epsilon;
/*!
Maximum threshold on the dot product between the estimated
shape's normal and the point's normal, that is the cosine of the angle (cos(25°) = 0.9).
%Default value is 0.9 (around 25 degrees).
It must belong to the interval [0, 1].
*/
FT normal_threshold;
/*!
Maximum acceptable Euclidean distance between points, which are assumed to be neighbors.
%Default value is 1% of the bounding box diagonal.
It must belong to the interval [0, +inf).
*/
FT cluster_epsilon;
};
/// @}
private:
typedef internal::Octree<internal::DirectPointAccessor<Traits> >
Direct_octree;
typedef internal::Octree<internal::IndexedPointAccessor<Traits> >
Indexed_octree;
//--------------------------------------------typedef
// Creates a function pointer for instancing shape instances.
template <class ShapeT>
static Shape *factory() {
return new ShapeT;
}
public:
/// \name Initialization
/// @{
/*!
Constructs an empty shape detection object.
*/
Efficient_RANSAC(Traits t = Traits())
: m_traits(t)
, m_direct_octrees(nullptr)
, m_global_octree(nullptr)
, m_num_subsets(0)
, m_num_available_points(0)
, m_num_total_points(0)
, m_valid_iterators(false)
{}
/*!
Releases all memory allocated by this instance including shapes.
*/
~Efficient_RANSAC() {
clear();
}
/*!
Retrieves the traits class.
*/
const Traits&
traits() const
{
return m_traits;
}
/*!
Retrieves the point property map.
*/
const Point_map& point_map() const { return m_point_pmap; }
/*!
Retrieves the normal property map.
*/
const Normal_map& normal() const { return m_normal_pmap; }
Input_iterator input_iterator_first() const
{
return m_input_iterator_first;
}
Input_iterator input_iterator_beyond() const
{
return m_input_iterator_beyond;
}
/*!
Sets the input data. The range must stay valid
until the detection has been performed and the access to the
results is no longer required. The data in the input is reordered by the methods
`detect()` and `preprocess()`. This function first calls `clear()`.
*/
void set_input(
Input_range& input_range,
///< Range of input data.
Point_map point_map = Point_map(),
///< Property map to access the position of an input point.
Normal_map normal_map = Normal_map()
///< Property map to access the normal of an input point.
) {
m_point_pmap = point_map;
m_normal_pmap = normal_map;
m_input_iterator_first = input_range.begin();
m_input_iterator_beyond = input_range.end();
clear();
m_extracted_shapes =
boost::make_shared<std::vector<boost::shared_ptr<Shape> > >();
m_num_available_points = m_num_total_points = std::distance(
m_input_iterator_first, m_input_iterator_beyond);
m_valid_iterators = true;
}
/*!
Registers the shape type `ShapeType` in the detection engine that must inherit from `Shape_base`.
For example, for registering a plane as detectable shape, you should call
`ransac.add_shape_factory< Shape_detection::Plane<Traits> >();`. Note
that if your call is within a template, you should add the `template`
keyword just before `add_shape_factory`:
`ransac.template add_shape_factory< Shape_detection::Plane<Traits> >();`.
*/
template <class Shape_type>
void add_shape_factory() {
m_shape_factories.push_back(factory<Shape_type>);
}
/*!
Constructs internal data structures required for the shape detection.
These structures only depend on the input data, i.e. the points and
normal vectors. This method is called by `detect()`, if it was not called
before by the user.
*/
bool preprocess() {
if (m_num_total_points == 0)
return false;
// Generation of subsets
m_num_subsets = (std::size_t)(std::max<std::ptrdiff_t>)((std::ptrdiff_t)
std::floor(std::log(double(m_num_total_points))/std::log(2.))-9, 2);
// SUBSET GENERATION ->
// approach with increasing subset sizes -> replace with octree later on
Input_iterator last = m_input_iterator_beyond - 1;
std::size_t remainingPoints = m_num_total_points;
m_available_octree_sizes.resize(m_num_subsets);
m_direct_octrees = new Direct_octree *[m_num_subsets];
for (int s = int(m_num_subsets) - 1;s >= 0;--s) {
std::size_t subsetSize = remainingPoints;
std::vector<std::size_t> indices(subsetSize);
if (s) {
subsetSize >>= 1;
for (std::size_t i = 0;i<subsetSize;i++) {
std::size_t index = get_default_random()(2);
index = index + (i<<1);
index = (index >= remainingPoints) ? remainingPoints - 1 : index;
indices[i] = index;
}
// move points to the end of the point vector
std::size_t j = subsetSize;
do {
j--;
typename std::iterator_traits<Input_iterator>::value_type
tmp = (*last);
*last = m_input_iterator_first[indices[std::size_t(j)]];
m_input_iterator_first[indices[std::size_t(j)]] = tmp;
last--;
} while (j > 0);
m_direct_octrees[s] = new Direct_octree(
m_traits, last + 1,
last + subsetSize + 1,
m_point_pmap, m_normal_pmap,
remainingPoints - subsetSize);
}
else
m_direct_octrees[0] = new Direct_octree(
m_traits, m_input_iterator_first,
m_input_iterator_first + (subsetSize),
m_point_pmap, m_normal_pmap,
0);
m_available_octree_sizes[s] = subsetSize;
m_direct_octrees[s]->createTree(m_options.cluster_epsilon);
remainingPoints -= subsetSize;
}
m_global_octree = new Indexed_octree(
m_traits, m_input_iterator_first, m_input_iterator_beyond,
m_point_pmap, m_normal_pmap);
m_global_octree->createTree(m_options.cluster_epsilon);
return true;
}
/// @}
/// \name Memory Management
/// @{
/*!
Removes all shape types registered for detection.
*/
void clear_shape_factories() {
m_shape_factories.clear();
}
/*!
Frees memory allocated for the internal search structures but keeps the detected shapes.
It invalidates the range retrieved using `unassigned_points()`.
*/
void clear_octrees() {
// If there is no data yet, there are no data structures.
if (!m_valid_iterators)
return;
if (m_global_octree) {
delete m_global_octree;
m_global_octree = nullptr;
}
if (m_direct_octrees) {
for (std::size_t i = 0;i<m_num_subsets;i++)
delete m_direct_octrees[i];
delete [] m_direct_octrees;
m_direct_octrees = nullptr;
}
m_num_subsets = 0;
}
/*!
Calls `clear_octrees()` and removes all detected shapes.
All internal structures are cleaned, including formerly detected shapes.
Thus iterators and ranges retrieved through `shapes()`, `planes()` and `indices_of_unassigned_points()`
are invalidated.
*/
void clear() {
// If there is no data yet, there are no data structures.
if (!m_valid_iterators)
return;
std::vector<int>().swap(m_shape_index);
m_extracted_shapes =
boost::make_shared<std::vector<boost::shared_ptr<Shape> > >();
m_num_available_points = m_num_total_points;
clear_octrees();
clear_shape_factories();
}
/// @}
/// \name Detection
/// @{
/*!
Performs the shape detection. Shape types considered during the detection
are those registered using `add_shape_factory()`.
\param options parameters for shape detection
\param callback can be omitted if the algorithm should be run
without any callback. It is called regularly when the algorithm
is running: the current advancement (between 0.0 and 1.0) is
passed as parameter. If it returns `true`, then the algorithm
continues its execution normally; if it returns `false`, the
algorithm is stopped. Note that this interruption may leave the
class in an invalid state.
\return `true` if shape types have been registered and
input data has been set. Otherwise, `false` is returned.
*/
bool detect(const Parameters &options = Parameters(),
const std::function<bool(double)>& callback
= std::function<bool(double)>())
{
m_options = options;
// No shape types for detection or no points provided, exit
if (m_shape_factories.size() == 0 ||
(m_input_iterator_beyond - m_input_iterator_first) == 0)
return false;
if (m_num_subsets == 0 || m_global_octree == 0) {
if (!preprocess())
return false;
}
if (callback && !callback(0.))
return false;
// Reset data structures possibly used by former search
m_extracted_shapes =
boost::make_shared<std::vector<boost::shared_ptr<Shape> > >();
m_num_available_points = m_num_total_points;
for (std::size_t i = 0;i<m_num_subsets;i++) {
m_available_octree_sizes[i] = m_direct_octrees[i]->size();
}
// Use bounding box diagonal as reference for default values
Bbox_3 bbox = m_global_octree->boundingBox();
FT bbox_diagonal = (FT) CGAL::sqrt(
(bbox.xmax() - bbox.xmin()) * (bbox.xmax() - bbox.xmin())
+ (bbox.ymax() - bbox.ymin()) * (bbox.ymax() - bbox.ymin())
+ (bbox.zmax() - bbox.zmin()) * (bbox.zmax() - bbox.zmin()));
// Epsilon or cluster_epsilon have been set by the user?
// If not, derive from bounding box diagonal
m_options.epsilon = (m_options.epsilon < 0)
? bbox_diagonal * (FT) 0.01 : m_options.epsilon;
m_options.cluster_epsilon = (m_options.cluster_epsilon < 0)
? bbox_diagonal * (FT) 0.01 : m_options.cluster_epsilon;
// Minimum number of points has been set?
m_options.min_points =
(m_options.min_points == (std::numeric_limits<std::size_t>::max)()) ?
(std::size_t)((FT)0.01 * m_num_available_points) :
m_options.min_points;
m_options.min_points = (m_options.min_points < 10) ? 10 : m_options.min_points;
// Initializing the shape index
m_shape_index.assign(m_num_available_points, -1);
if (m_options.min_points > m_num_available_points)
return true;
// List of all randomly drawn candidates
// with the minimum number of points
std::vector<Shape *> candidates;
// Identifying minimum number of samples
m_required_samples = 0;
for (std::size_t i = 0;i<m_shape_factories.size();i++) {
Shape *tmp = (Shape *) m_shape_factories[i]();
m_required_samples = (std::max<std::size_t>)(m_required_samples, tmp->minimum_sample_size());
delete tmp;
}
std::size_t first_sample; // first sample for RANSAC
FT best_expected = 0;
// number of points that have been assigned to a shape
std::size_t num_invalid = 0;
std::size_t generated_candidates = 0;
std::size_t failed_candidates = 0;
std::size_t limit_failed_candidates = (std::max)(std::size_t(10000),
std::size_t(m_input_iterator_beyond
- m_input_iterator_first)
/ std::size_t(100));
bool force_exit = false;
bool keep_searching = true;
do { // main loop
best_expected = 0;
if (keep_searching)
do {
// Search (remaining_points / min_points) shapes (max 200 per iteration, min 1)
std::size_t search_number
= (std::min)(std::size_t(200),
(std::max)(std::size_t((m_num_available_points - num_invalid) / double(m_options.min_points)),
std::size_t(1)));
for (std::size_t nb = 0; nb < search_number; ++ nb)
{
// Generate candidates
//1. pick a point p1 randomly among available points
std::set<std::size_t> indices;
bool done = false;
do {
do
first_sample = get_default_random()(
static_cast<unsigned int>(m_num_available_points));
while (m_shape_index[first_sample] != -1);
done = m_global_octree->drawSamplesFromCellContainingPoint(
get(m_point_pmap,
*(m_input_iterator_first + first_sample)),
select_random_octree_level(),
indices,
m_shape_index,
m_required_samples);
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
} while (m_shape_index[first_sample] != -1 || !done);
generated_candidates++;
//add candidate for each type of primitives
for(typename std::vector<Shape *(*)()>::iterator it =
m_shape_factories.begin(); it != m_shape_factories.end(); it++) {
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
Shape *p = (Shape *) (*it)();
//compute the primitive and says if the candidate is valid
p->compute(indices,
m_input_iterator_first,
m_traits,
m_point_pmap,
m_normal_pmap,
m_options.epsilon,
m_options.normal_threshold);
if (p->is_valid()) {
improve_bound(p, m_num_available_points - num_invalid, 1, 500);
//evaluate the candidate
if(p->max_bound() >= m_options.min_points && p->score() > 0) {
if (best_expected < p->expected_value())
best_expected = p->expected_value();
candidates.push_back(p);
}
else {
failed_candidates++;
delete p;
}
}
else {
failed_candidates++;
delete p;
}
}
}
if (failed_candidates >= limit_failed_candidates)
{
force_exit = true;
}
keep_searching = (stop_probability(m_options.min_points,
m_num_available_points - num_invalid,
generated_candidates, m_global_octree->maxLevel())
> m_options.probability);
} while( !force_exit
&& stop_probability((std::size_t) best_expected,
m_num_available_points - num_invalid,
generated_candidates,
m_global_octree->maxLevel())
> m_options.probability
&& keep_searching);
// end of generate candidate
if (force_exit) {
break;
}
if (candidates.empty())
continue;
// Now get the best candidate in the current set of all candidates
// Note that the function sorts the candidates:
// the best candidate is always the last element of the vector
Shape *best_candidate =
get_best_candidate(candidates, m_num_available_points - num_invalid);
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
// If search is done and the best candidate is too small, we are done.
if (!keep_searching && best_candidate->m_score < m_options.min_points)
break;
if (!best_candidate)
continue;
best_candidate->m_indices.clear();
best_candidate->m_score =
m_global_octree->score(best_candidate,
m_shape_index,
FT(3) * m_options.epsilon,
m_options.normal_threshold);
best_expected = static_cast<FT>(best_candidate->m_score);
best_candidate->connected_component(best_candidate->m_indices,
m_options.cluster_epsilon);
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
// check score against min_points and clear out candidates if too low
if (best_candidate->indices_of_assigned_points().size() <
m_options.min_points)
{
if (!(best_candidate->indices_of_assigned_points().empty()))
for (std::size_t i = 0;i < candidates.size() - 1;i++) {
if (best_candidate->is_same(candidates[i])) {
delete candidates[i];
candidates[i] = nullptr;
}
}
candidates.back() = nullptr;
delete best_candidate;
best_candidate = nullptr;
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
// Trimming candidates list
std::size_t empty = 0, occupied = 0;
while (empty < candidates.size()) {
while (empty < candidates.size() && candidates[empty]) empty++;
if (empty >= candidates.size())
break;
if (occupied < empty)
occupied = empty + 1;
while (occupied < candidates.size() && !candidates[occupied])
occupied++;
if (occupied >= candidates.size())
break;
candidates[empty] = candidates[occupied];
candidates[occupied] = nullptr;
empty++;
occupied++;
}
candidates.resize(empty);
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
}
else
if (stop_probability((std::size_t) best_candidate->expected_value(),
(m_num_available_points - num_invalid),
generated_candidates,
m_global_octree->maxLevel())
<= m_options.probability) {
// Remove candidate from list
candidates.back() = nullptr;
//1. add best candidate to final result.
m_extracted_shapes->push_back(
boost::shared_ptr<Shape>(best_candidate));
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
//2. remove the points
const std::vector<std::size_t> &indices_points_best_candidate =
best_candidate->indices_of_assigned_points();
// update generated candidates to reflect removal of points
generated_candidates = std::size_t(std::pow (1.f - (indices_points_best_candidate.size() /
float(m_num_available_points - num_invalid)), 3.f)
* generated_candidates);
//2.3 Remove the points from the subtrees
for (std::size_t i = 0;i<indices_points_best_candidate.size();i++) {
m_shape_index[indices_points_best_candidate.at(i)] =
int(m_extracted_shapes->size()) - 1;
num_invalid++;
for (std::size_t j = 0;j<m_num_subsets;j++) {
if (m_direct_octrees[j] && m_direct_octrees[j]->m_root) {
std::size_t offset = m_direct_octrees[j]->offset();
if (offset <= indices_points_best_candidate.at(i) &&
(indices_points_best_candidate.at(i) - offset)
< m_direct_octrees[j]->size()) {
m_available_octree_sizes[j]--;
}
}
}
}
failed_candidates = 0;
best_expected = 0;
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
std::vector<std::size_t> subset_sizes(m_num_subsets);
subset_sizes[0] = m_available_octree_sizes[0];
for (std::size_t i = 1;i<m_num_subsets;i++) {
subset_sizes[i] = subset_sizes[i-1] + m_available_octree_sizes[i];
}
//3. Remove points from candidates common with extracted primitive
//#pragma omp parallel for
best_expected = 0;
for (std::size_t i=0;i< candidates.size()-1;i++) {
if (candidates[i]) {
candidates[i]->update_points(m_shape_index);
candidates[i]->compute_bound(
subset_sizes[candidates[i]->m_nb_subset_used - 1],
m_num_available_points - num_invalid);
if (candidates[i]->max_bound() < m_options.min_points) {
delete candidates[i];
candidates[i] = nullptr;
}
else {
best_expected = (candidates[i]->expected_value() > best_expected) ?
candidates[i]->expected_value() : best_expected;
}
}
}
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
std::size_t start = 0, end = candidates.size() - 1;
while (start < end) {
while (candidates[start] && start < end) start++;
while (!candidates[end] && start < end) end--;
if (!candidates[start] && candidates[end] && start < end) {
candidates[start] = candidates[end];
candidates[end] = nullptr;
start++;
end--;
}
}
if (candidates[end]) end++;
candidates.resize(end);
}
else if (!keep_searching)
++ generated_candidates;
if (callback && !callback(num_invalid / double(m_num_total_points)))
return false;
keep_searching = (stop_probability(m_options.min_points,
m_num_available_points - num_invalid,
generated_candidates,
m_global_octree->maxLevel())
> m_options.probability);
}
while((keep_searching
&& FT(m_num_available_points - num_invalid) >= m_options.min_points)
|| best_expected >= m_options.min_points);
// Clean up remaining candidates.
for (std::size_t i = 0;i<candidates.size();i++)
delete candidates[i];
candidates.resize(0);
m_num_available_points -= num_invalid;
return true;
}
/// @}
/// \name Access
/// @{
/*!
Returns an `Iterator_range` with a bidirectional iterator with value type
`boost::shared_ptr<Shape>` over the detected shapes in the order of detection.
Depending on the chosen probability
for the detection, the shapes are ordered with decreasing size.
*/
Shape_range shapes() const {
return Shape_range(m_extracted_shapes);
}
/*!
Returns an `Iterator_range` with a bidirectional iterator with
value type `boost::shared_ptr<Plane_shape>` over only the
detected planes in the order of detection. Depending on the
chosen probability for the detection, the planes are ordered
with decreasing size.
*/
Plane_range planes() const {
boost::shared_ptr<std::vector<boost::shared_ptr<Plane_shape> > > planes
= boost::make_shared<std::vector<boost::shared_ptr<Plane_shape> > >();
for (std::size_t i = 0; i < m_extracted_shapes->size(); ++ i)
{
boost::shared_ptr<Plane_shape> pshape
= boost::dynamic_pointer_cast<Plane_shape>((*m_extracted_shapes)[i]);
// Ignore all shapes other than plane
if (pshape != boost::shared_ptr<Plane_shape>())
planes->push_back (pshape);
}
return Plane_range(planes);
}
/*!
Number of points not assigned to a shape.
*/
std::size_t number_of_unassigned_points() const {
return m_num_available_points;
}
/*!
Returns an `Iterator_range` with a bidirectional iterator with value type `std::size_t`
as indices into the input data that has not been assigned to a shape.
*/
Point_index_range indices_of_unassigned_points() {
Filter_unassigned_points fup(m_shape_index);
Point_index_iterator p1 =
boost::make_filter_iterator<Filter_unassigned_points>(
fup,
boost::counting_iterator<std::size_t, boost::use_default, std::ptrdiff_t>(0),
boost::counting_iterator<std::size_t, boost::use_default, std::ptrdiff_t>(m_shape_index.size()));
return make_range(p1, Point_index_iterator(p1.end()));
}
/// @}
private:
int select_random_octree_level() {
return (int) get_default_random()(
static_cast<unsigned int>(m_global_octree->maxLevel() + 1));
}
Shape* get_best_candidate(std::vector<Shape* >& candidates,
const std::size_t num_available_points) {
if (candidates.size() == 1)
return candidates.back();
int index_worse_candidate = 0;
bool improved = true;
while (index_worse_candidate < (int)candidates.size() - 1 && improved) {
improved = false;
typename Shape::Compare_by_max_bound comp;
std::sort(candidates.begin() + index_worse_candidate,
candidates.end(),
comp);
//refine the best one
improve_bound(candidates.back(),
num_available_points, m_num_subsets,
m_options.min_points);
int position_stop;
//Take all those intersecting the best one, check for equal ones
for (position_stop = int(candidates.size()) - 1;
position_stop > index_worse_candidate;
position_stop--) {
if (candidates.back()->min_bound() >
candidates.at(position_stop)->max_bound())
break;//the intervals do not overlaps anymore
if (candidates.at(position_stop)->max_bound()
<= m_options.min_points)
break; //the following candidate doesn't have enough points!
//if we reach this point, there is an overlap
// between best one and position_stop
//so request refining bound on position_stop
improved |= improve_bound(candidates.at(position_stop),
num_available_points,
m_num_subsets,
m_options.min_points);
//test again after refined
if (candidates.back()->min_bound() >
candidates.at(position_stop)->max_bound())
break;//the intervals do not overlaps anymore
}
index_worse_candidate = position_stop;
}
return candidates.back();
}
bool improve_bound(Shape *candidate,
std::size_t num_available_points,
std::size_t max_subset,
std::size_t min_points) {
if (candidate->m_nb_subset_used >= max_subset)
return false;
if (candidate->m_nb_subset_used >= m_num_subsets)
return false;
candidate->m_nb_subset_used =
(candidate->m_nb_subset_used >= m_num_subsets) ?
m_num_subsets - 1 : candidate->m_nb_subset_used;
//what it does is add another subset and recompute lower and upper bound
//the next subset to include is provided by m_nb_subset_used
std::size_t num_points_evaluated = 0;
for (std::size_t i=0;i<candidate->m_nb_subset_used;i++)
num_points_evaluated += m_available_octree_sizes[i];
// need score of new subset as well as sum of
// the score of the previous considered subset
std::size_t new_score = 0;
std::size_t new_sampled_points = 0;
do {
new_score = m_direct_octrees[candidate->m_nb_subset_used]->score(
candidate,
m_shape_index,
m_options.epsilon,
m_options.normal_threshold);
candidate->m_score += new_score;
num_points_evaluated +=
m_available_octree_sizes[candidate->m_nb_subset_used];
new_sampled_points +=
m_available_octree_sizes[candidate->m_nb_subset_used];
candidate->m_nb_subset_used++;
} while (new_sampled_points < min_points &&
candidate->m_nb_subset_used < m_num_subsets);
candidate->m_score = candidate->m_indices.size();
candidate->compute_bound(num_points_evaluated, num_available_points);
return true;
}
inline FT stop_probability(std::size_t largest_candidate, std::size_t num_pts, std::size_t num_candidates, std::size_t octree_depth) const {
return (std::min<FT>)(std::pow((FT) 1.f - (FT) largest_candidate
/ (FT(num_pts) * (octree_depth+1) * (1 << (m_required_samples - 1))), (int) num_candidates), (FT) 1);
}
private:
Parameters m_options;
// Traits class.
Traits m_traits;
// Octrees build on input data for quick shape evaluation and
// sample selection within an octree cell.
Direct_octree **m_direct_octrees;
Indexed_octree *m_global_octree;
std::vector<std::size_t> m_available_octree_sizes;
std::size_t m_num_subsets;
// maps index into points to assigned extracted primitive
std::vector<int> m_shape_index;
std::size_t m_num_available_points;
std::size_t m_num_total_points;
std::size_t m_required_samples;
//give the index of the subset of point i
std::vector<int> m_index_subsets;
boost::shared_ptr<std::vector<boost::shared_ptr<Shape> > > m_extracted_shapes;
std::vector<Shape *(*)()> m_shape_factories;
// iterators of input data
bool m_valid_iterators;
Input_iterator m_input_iterator_first, m_input_iterator_beyond;
Point_map m_point_pmap;
Normal_map m_normal_pmap;
};
}
}
#endif // CGAL_SHAPE_DETECTION_EFFICIENT_RANSAC_H
|
declare_reduction_ast_print.c | // RUN: %clang_cc1 -verify -fopenmp -ast-print %s | FileCheck %s
// RUN: %clang_cc1 -fopenmp -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
#pragma omp declare reduction(+ : int, char : omp_out *= omp_in)
// CHECK: #pragma omp declare reduction (+ : int : omp_out *= omp_in)
// CHECK-NEXT: #pragma omp declare reduction (+ : char : omp_out *= omp_in)
#pragma omp declare reduction(fun : float : omp_out += omp_in) initializer(omp_priv = omp_orig + 15)
// CHECK: #pragma omp declare reduction (fun : float : omp_out += omp_in) initializer(omp_priv = omp_orig + 15)
// CHECK: struct SSS {
struct SSS {
int field;
#pragma omp declare reduction(+ : int, char : omp_out *= omp_in)
// CHECK: #pragma omp declare reduction (+ : int : omp_out *= omp_in)
// CHECK-NEXT: #pragma omp declare reduction (+ : char : omp_out *= omp_in)
};
// CHECK: };
void init(struct SSS *priv, struct SSS orig);
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: #pragma omp declare reduction (fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: int main() {
int main() {
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: #pragma omp declare reduction (fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
{
#pragma omp declare reduction(fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
// CHECK: #pragma omp declare reduction (fun : struct SSS : omp_out = omp_in) initializer(init(&omp_priv, omp_orig))
}
return 0;
}
// CHECK: }
#endif
|
dem_fem_search.h | //
// Project Name: Kratos
// Last Modified by: $Author: msantasusana, croig $
// Date: $Date: 2015-10-26 19:37:47 $
// Revision: $Revision: 1.2 $
//
//
#if !defined(KRATOS_DEM_FEM_SEARCH_H_INCLUDED )
#define KRATOS_DEM_FEM_SEARCH_H_INCLUDED
// System includes
#include <string>
#include <iostream>
// include kratos definitions
#include "includes/define.h"
// Project includes
#include "utilities/openmp_utils.h"
// Configures
#include "rigid_face_geometrical_object_configure.h"
// Search
#include "spatial_containers/bins_dynamic_objects.h"
#include "spatial_containers/bins_dynamic.h"
// External includes
//#define CUSTOMTIMER
/* Timer defines */
#include "utilities/timer.h"
#ifdef CUSTOMTIMER
#define KRATOS_TIMER_START(t) Timer::Start(t);
#define KRATOS_TIMER_STOP(t) Timer::Stop(t);
#else
#define KRATOS_TIMER_START(t)
#define KRATOS_TIMER_STOP(t)
#endif
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
class KRATOS_API(DEM_APPLICATION) DEM_FEM_Search : public SpatialSearch
{
public:
///@name Type Definitions
///@{
/// Pointer definition of OMP_DEMSearch
KRATOS_CLASS_POINTER_DEFINITION(DEM_FEM_Search);
typedef PointType* PtrPointType;
typedef std::vector<PtrPointType>* PointVector;
typedef std::vector<PtrPointType>::iterator PointIterator;
typedef double* DistanceVector;
typedef double* DistanceIterator;
// //Configure Types
// typedef RigidFaceConfigure<3> ElementConfigureType; //Element
// //Bin Types
// typedef BinsObjectDynamic<ElementConfigureType> BinsType;
//
//Configure Types
typedef RigidFaceGeometricalObjectConfigure<3> RigidFaceGeometricalConfigureType;
//Bin Types
typedef BinsObjectDynamic<RigidFaceGeometricalConfigureType> GeometricalBinsType;
//typedef PointerVectorSet<GeometricalObject, IndexedObject> GeometricalObjectType;
typedef typename RigidFaceGeometricalConfigureType::ElementsContainerType GeometricalObjectType;
//typedef PointerVector<GeometricalObject> GeometricalObjectType;
///@}
///@name Life Cycle
///@{
/// Default constructor.
DEM_FEM_Search(){
mBins = NULL;
}
/// Destructor.
~DEM_FEM_Search(){
}
void SearchRigidFaceForDEMInRadiusExclusiveImplementation (
ElementsContainerType const& rElements,
ConditionsContainerType const& rConditions,
VectorResultConditionsContainerType& rResults,
VectorDistanceType& rResultsDistance)
{
KRATOS_TRY
/*
STEPS:
¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨¨
1. INITIALIZE
2. CALCULATE THE DEM BBX
3. GATHER DEM BOUNDING BOX
4. FIND THE FE INSIDE DEM_BB TO BUILD THE BINS AND CONSTRUCT THE GLOBAL BBX
5. GATHER FEM ELEMENTS AND THE GLOBAL BBX
6. BUILD THE BINS
7. PERFORM THE SEARCH FOR THE SPHERES INSIDE THE BBX (amplified by the radius of each particle)
*/
//1. INITIALIZE
int MaxNumberOfElements = rConditions.size();
ElementsContainerType::ContainerType& elements_sear = const_cast<ElementsContainerType::ContainerType&> (rElements.GetContainer());
ConditionsContainerType::ContainerType& conditions_bins = const_cast<ConditionsContainerType::ContainerType&>(rConditions.GetContainer());
//GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector;
GeometricalObjectType::ContainerType BinsConditionPointerToGeometricalObjecPointerTemporalVector;
RadiusArrayType Radius_out;
int num_of_threads = OpenMPUtils::GetNumThreads();
std::vector<unsigned int> total_dem_partition_index;
std::vector<unsigned int> total_fem_partition_index;
OpenMPUtils::CreatePartition(num_of_threads, elements_sear.size(), total_dem_partition_index);
OpenMPUtils::CreatePartition(num_of_threads, conditions_bins.size(), total_fem_partition_index);
//std::vector<GeometricalObjectType::ContainerType> Vector_SearElementPointerToGeometricalObjecPointerTemporalVector(num_of_threads);
std::vector<GeometricalObjectType::ContainerType> Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector(num_of_threads);
std::vector<array_1d<double, 3> > Vector_DEM_BB_LowPoint(num_of_threads); std::vector <array_1d<double, 3 > > Vector_DEM_BB_HighPoint(num_of_threads);
std::vector<array_1d<double, 3> > Vector_GLOBAL_BB_LowPoint(num_of_threads); std::vector <array_1d<double, 3 > > Vector_GLOBAL_BB_HighPoint(num_of_threads);
std::vector<double> Vector_Ref_Radius(num_of_threads);
std::vector<RadiusArrayType> Vector_Radius_out(num_of_threads);
double Global_Ref_Radius = 0.0;
double inf = std::numeric_limits<double>::infinity();
for (std::size_t i = 0; i < 3; i++) {
DEM_BB_LowPoint[i] = inf;
DEM_BB_HighPoint[i] = -inf;
mGlobal_BB_LowPoint[i] = inf;
mGlobal_BB_HighPoint[i] = -inf;
}
typedef ElementsContainerType::ContainerType::iterator Elem_iter;
typedef ConditionsContainerType::ContainerType::iterator Cond_iter;
//2. CALCULATE THE DEM BBX
#pragma omp parallel
{
double radius = 0.0;
int k = OpenMPUtils::ThisThread();
for(std::size_t i = 0; i < 3; i++) {
Vector_DEM_BB_LowPoint[k][i] = inf;
Vector_DEM_BB_HighPoint[k][i] = -inf;
}
#pragma omp for
for (int p = 0; p <(int) elements_sear.size(); p++) {
Elem_iter it = elements_sear.begin() + p;
GeometryType& pGeometry = (*it)->GetGeometry();
const array_1d<double, 3 >& aux_coor = pGeometry[0].Coordinates();
SphericParticle* p_particle = dynamic_cast<SphericParticle*>((*it).get());
radius = p_particle->GetSearchRadius();
Vector_Ref_Radius[k] = (Vector_Ref_Radius[k] < radius) ? radius : Vector_Ref_Radius[k] ;
for(std::size_t i = 0; i < 3; i++) {
Vector_DEM_BB_LowPoint[k][i] = (Vector_DEM_BB_LowPoint[k][i] > aux_coor[i]) ? aux_coor[i] : Vector_DEM_BB_LowPoint[k][i];
Vector_DEM_BB_HighPoint[k][i] = (Vector_DEM_BB_HighPoint[k][i] < aux_coor[i]) ? aux_coor[i] : Vector_DEM_BB_HighPoint[k][i];
}
} //pragma
}//pragma parallel
//3. GATHER DEM BOUNDING BOX
for(int k = 0; k < num_of_threads; k++) {
for(std::size_t i = 0; i < 3; i++) {
DEM_BB_LowPoint[i] = (DEM_BB_LowPoint[i] > Vector_DEM_BB_LowPoint[k][i]) ? Vector_DEM_BB_LowPoint[k][i] : DEM_BB_LowPoint[i];
DEM_BB_HighPoint[i] = (DEM_BB_HighPoint[i] < Vector_DEM_BB_HighPoint[k][i]) ? Vector_DEM_BB_HighPoint[k][i] : DEM_BB_HighPoint[i];
}
Global_Ref_Radius = (Global_Ref_Radius < Vector_Ref_Radius[k]) ? Vector_Ref_Radius[k] : Global_Ref_Radius;
}
for(std::size_t i = 0; i < 3; i++) {
DEM_BB_LowPoint[i] -= 1.00f * Global_Ref_Radius;
DEM_BB_HighPoint[i] += 1.00f * Global_Ref_Radius;
}
//4. FIND THE FE INSIDE DEM_BB TO BUILD THE BINS AND CONSTRUCT THE GLOBAL BBX
#pragma omp parallel
{
int k = OpenMPUtils::ThisThread();
Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector[k].reserve(total_fem_partition_index[k+1]);
for(std::size_t i = 0; i < 3; i++) {
Vector_GLOBAL_BB_LowPoint[k][i] = inf;
Vector_GLOBAL_BB_HighPoint[k][i] = -inf;
}
array_1d<double, 3> rHighPoint;
array_1d<double, 3> rLowPoint;
#pragma omp for private(rHighPoint,rLowPoint)
for (int c = 0; c < (int)conditions_bins.size(); c++) {
Cond_iter it = conditions_bins.begin() + c;
const GeometryType& pGeometry = (*it)->GetGeometry();
noalias(rLowPoint) = pGeometry[0];
noalias(rHighPoint) = pGeometry[0];
for(unsigned int point = 1; point < pGeometry.size(); point++ ) {
for(unsigned int i = 0; i < 3; i++ ) {
rHighPoint[i] = ( rHighPoint[i] < pGeometry[point][i] ) ? pGeometry[point][i] : rHighPoint[i];
rLowPoint[i] = ( rLowPoint[i] > pGeometry[point][i] ) ? pGeometry[point][i] : rLowPoint[i];
}
}
bool add = true;
for(unsigned int i = 0; i < 3; i++) {
if(( rHighPoint[i] < DEM_BB_LowPoint[i] ) || ( rLowPoint[i] > DEM_BB_HighPoint[i] )) {
add = false;
break;
}
}
if(add) {
for(unsigned int i = 0; i < 3; i++ ) {
Vector_GLOBAL_BB_LowPoint[k][i] = (Vector_GLOBAL_BB_LowPoint[k][i] > rLowPoint[i]) ? rLowPoint[i] : Vector_GLOBAL_BB_LowPoint[k][i];
Vector_GLOBAL_BB_HighPoint[k][i] = (Vector_GLOBAL_BB_HighPoint[k][i] < rHighPoint[i]) ? rHighPoint[i] : Vector_GLOBAL_BB_HighPoint[k][i];
}
Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector[k].push_back(*it);
}
}//parallel for
}//parallel omp
//5. GATHER FEM ELEMENTS AND THE GLOBAL BBX
int fem_total_size = 0;
for(int k = 0; k < num_of_threads; k++) {
fem_total_size += Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector[k].size();
}
BinsConditionPointerToGeometricalObjecPointerTemporalVector.reserve(fem_total_size);
for(int k = 0; k < num_of_threads; k++) {
BinsConditionPointerToGeometricalObjecPointerTemporalVector.insert(
BinsConditionPointerToGeometricalObjecPointerTemporalVector.end(),
Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector[k].begin(),
Vector_BinsConditionPointerToGeometricalObjecPointerTemporalVector[k].end()
);
for(std::size_t i = 0; i < 3; i++) {
mGlobal_BB_LowPoint[i] = (mGlobal_BB_LowPoint[i] > Vector_GLOBAL_BB_LowPoint[k][i]) ? Vector_GLOBAL_BB_LowPoint[k][i] : mGlobal_BB_LowPoint[i];
mGlobal_BB_HighPoint[i] = (mGlobal_BB_HighPoint[i] < Vector_GLOBAL_BB_HighPoint[k][i]) ? Vector_GLOBAL_BB_HighPoint[k][i] : mGlobal_BB_HighPoint[i];
}
}
if(BinsConditionPointerToGeometricalObjecPointerTemporalVector.size() >0 ) {
//6. CREATE THE BINS
//if (mBins) free(mBins);
delete mBins;
mBins = new GeometricalBinsType(BinsConditionPointerToGeometricalObjecPointerTemporalVector.begin(), BinsConditionPointerToGeometricalObjecPointerTemporalVector.end());
//7. PERFORM THE SEARCH ON THE SPHERES
#pragma omp parallel
{
GeometricalObjectType::ContainerType localResults(MaxNumberOfElements);
DistanceType localResultsDistances(MaxNumberOfElements);
std::size_t NumberOfResults = 0;
#pragma omp for schedule(dynamic, 100)
for (int p = 0; p < (int)elements_sear.size(); p++) {
Elem_iter it = elements_sear.begin() + p;
GeometricalObject::Pointer go_it(*it);
bool search_particle = true;
array_1d<double, 3 > & aux_coor = go_it->GetGeometry()[0].Coordinates();
SphericParticle* p_particle = dynamic_cast<SphericParticle*>((*it).get());
double Rad = p_particle->GetSearchRadius();
for(unsigned int i = 0; i < 3; i++ ) {
search_particle &= !(aux_coor[i] < (mGlobal_BB_LowPoint[i] - Rad) ) || (aux_coor[i] > (mGlobal_BB_HighPoint[i] + Rad) ); //amplify the BBX with the radius for every particle
}
if(search_particle) {
auto ResultsPointer = localResults.begin();
DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin();
NumberOfResults = (*mBins).SearchObjectsInRadiusExclusive(go_it,Rad,ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements);
rResults[p].reserve(NumberOfResults);
for(auto c_it = localResults.begin(); c_it != localResults.begin() + NumberOfResults; c_it++) {
auto presult = *c_it;
Condition::Pointer condition = dynamic_pointer_cast<Condition>(presult);
//Condition::Pointer condition = Kratos::dynamic_pointer_cast<Condition>(*c_it);
rResults[p].push_back(condition);
}
rResultsDistance[p].insert(rResultsDistance[p].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults);
}
} //loop elements
} //parallel
}//if Bins is not empty--> search
KRATOS_CATCH("")
}
array_1d<double, 3 > GetBBHighPoint() {
return (mGlobal_BB_HighPoint);
}
array_1d<double, 3 > GetBBLowPoint() {
return (mGlobal_BB_LowPoint);
}
/// Turn back information as a string.
virtual std::string Info() const override
{
std::stringstream buffer;
buffer << "DEM_FEM_Search" ;
return buffer.str();
}
/// Print information about this object.
virtual void PrintInfo(std::ostream& rOStream) const override {rOStream << "DEM_FEM_Search";}
/// Print object's data.
virtual void PrintData(std::ostream& rOStream) const override {}
///@}
///@name Friends
///@{
///@}
protected:
///@name Protected static Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
array_1d<double, 3 > mGlobal_BB_HighPoint;
array_1d<double, 3 > mGlobal_BB_LowPoint;
array_1d<double, 3 > DEM_BB_HighPoint;
array_1d<double, 3 > DEM_BB_LowPoint;
GeometricalBinsType* mBins;
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
/// Assignment operator.
DEM_FEM_Search& operator=(DEM_FEM_Search const& rOther)
{
return *this;
}
/// Copy constructor.
DEM_FEM_Search(DEM_FEM_Search const& rOther)
{
*this = rOther;
}
}; // Class DEM_FEMSearch
} // namespace Kratos.
#endif // KRATOS_DEM_FEM_SEARCH_H_INCLUDED defined
|
ParticleSet.h | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: D. Das, University of Illinois at Urbana-Champaign
// Bryan Clark, bclark@Princeton.edu, Princeton University
// Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign
// Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
// Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
// Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
//
// File created by: Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_PARTICLESET_H
#define QMCPLUSPLUS_PARTICLESET_H
#include <Configuration.h>
#include <ParticleTags.h>
#include <Particle/Walker.h>
#include <Utilities/SpeciesSet.h>
#include <Utilities/PooledData.h>
#include <OhmmsPETE/OhmmsArray.h>
#include <Utilities/NewTimer.h>
#include <OhmmsSoA/Container.h>
#include "type_traits/template_types.hpp"
namespace qmcplusplus
{
///forward declaration of DistanceTableData
class DistanceTableData;
class StructFact;
/** Monte Carlo Data of an ensemble
*
* The quantities are shared by all the nodes in a group
* - NumSamples number of samples
* - Weight total weight of a sample
* - Energy average energy of a sample
* - Variance variance
* - LivingFraction fraction of walkers alive each step.
*/
template<typename T>
struct MCDataType
{
T NumSamples;
T RNSamples;
T Weight;
T Energy;
T AlternateEnergy;
T Variance;
T R2Accepted;
T R2Proposed;
T LivingFraction;
};
/** Specialized paritlce class for atomistic simulations
*
* Derived from QMCTraits, ParticleBase<PtclOnLatticeTraits> and OhmmsElementBase.
* The ParticleLayout class represents a supercell with/without periodic boundary
* conditions. The ParticleLayout class also takes care of spatial decompositions
* for efficient evaluations for the interactions with a finite cutoff.
*/
class ParticleSet : public QMCTraits, public OhmmsElementBase, public PtclOnLatticeTraits
{
public:
///@typedef walker type
typedef Walker<QMCTraits, PtclOnLatticeTraits> Walker_t;
///@typedef container type to store the property
typedef Walker_t::PropertyContainer_t PropertyContainer_t;
///@typedef buffer type for a serialized buffer
typedef PooledData<RealType> Buffer_t;
enum quantum_domains
{
no_quantum_domain = 0,
classical,
quantum
};
///quantum_domain of the particles, default = classical
quantum_domains quantum_domain;
//@{ public data members
///property of an ensemble represented by this ParticleSet
//MCDataType<FullPrecRealType> EnsembleProperty;
///ParticleLayout
ParticleLayout_t Lattice, PrimitiveLattice;
///Long-range box
ParticleLayout_t LRBox;
///unique, persistent ID for each particle
ParticleIndex_t ID;
///index to the primitice cell with tiling
ParticleIndex_t PCID;
/** ID map that reflects species group
*
* IsGrouped=true, if ID==IndirectID
*/
ParticleIndex_t IndirectID;
///Species ID
ParticleIndex_t GroupID;
///Position
ParticlePos_t R;
///SoA copy of R
VectorSoaContainer<RealType, DIM> RSoA;
///internal spin variables for dynamical spin calculations
ParticleScalar_t spins;
///gradients of the particles
ParticleGradient_t G;
///laplacians of the particles
ParticleLaplacian_t L;
///differential gradients of the particles
ParticleGradient_t dG;
///differential laplacians of the particles
ParticleLaplacian_t dL;
///mass of each particle
ParticleScalar_t Mass;
///charge of each particle
ParticleScalar_t Z;
///true if the particles are grouped
bool IsGrouped;
///true if the particles have the same mass
bool SameMass;
///threa id
Index_t ThreadID;
/** the index of the active particle during particle-by-particle moves
*
* when a single particle move is proposed, the particle id is assigned to activePtcl
* No matter the move is accepted or rejected, activePtcl is marked back to -1.
* This state flag is used for picking coordinates and distances for SPO evaluation.
*/
Index_t activePtcl;
///the group of the active particle during particle-by-particle moves
Index_t activeGroup;
///the index of the active bead for particle-by-particle moves
Index_t activeBead;
///the direction reptile traveling
Index_t direction;
///the proposed position of activePtcl during particle-by-particle moves
SingleParticlePos_t activePos;
///the proposed position in the Lattice unit
SingleParticlePos_t newRedPos;
///SpeciesSet of particles
SpeciesSet mySpecies;
///Structure factor
StructFact* SK;
///Particle density in G-space for MPC interaction
std::vector<TinyVector<int, OHMMS_DIM>> DensityReducedGvecs;
std::vector<ComplexType> Density_G;
Array<RealType, OHMMS_DIM> Density_r;
/// DFT potential
std::vector<TinyVector<int, OHMMS_DIM>> VHXCReducedGvecs;
std::vector<ComplexType> VHXC_G[2];
Array<RealType, OHMMS_DIM> VHXC_r[2];
/** name-value map of Walker Properties
*
* PropertyMap is used to keep the name-value mapping of
* Walker_t::Properties. PropertyList::Values are not
* necessarily updated during the simulations.
*/
PropertySetType PropertyList;
/** properties of the current walker
*
* The internal order is identical to PropertyList, which holds
* the matching names.
*/
PropertyContainer_t Properties;
/** observables in addition to those registered in Properties/PropertyList
*
* Such observables as density, gofr, sk are not stored per walker but
* collected during QMC iterations.
*/
Buffer_t Collectables;
///clones of this object: used by the thread pool
std::vector<ParticleSet*> myClones;
///Property history vector
std::vector<std::vector<FullPrecRealType>> PropertyHistory;
std::vector<int> PHindex;
///@}
///current MC step
int current_step;
///default constructor
ParticleSet();
///copy constructor
ParticleSet(const ParticleSet& p);
///default destructor
virtual ~ParticleSet();
/** create particles
* @param n number of particles
*/
void create(int n);
/** create grouped particles
* @param agroup number of particles per group
*/
void create(const std::vector<int>& agroup);
///write to a std::ostream
bool get(std::ostream&) const;
///read from std::istream
bool put(std::istream&);
///reset member data
void reset();
///initialize ParticleSet from xmlNode
bool put(xmlNodePtr cur);
///specify quantum_domain of particles
void set_quantum_domain(quantum_domains qdomain);
void set_quantum() { quantum_domain = quantum; }
inline bool is_classical() const { return quantum_domain == classical; }
inline bool is_quantum() const { return quantum_domain == quantum; }
///check whether quantum domain is valid for particles
inline bool quantum_domain_valid(quantum_domains qdomain) const { return qdomain != no_quantum_domain; }
///check whether quantum domain is valid for particles
inline bool quantum_domain_valid() const { return quantum_domain_valid(quantum_domain); }
/** add a distance table
* @param psrc source particle set
* @param dt_type distance table type
* @param need_full_table_loadWalker if ture, fully computed in loadWalker()
*
* if this->myName == psrc.getName(), AA type. Otherwise, AB type.
*/
int addTable(const ParticleSet& psrc, int dt_type, bool need_full_table_loadWalker = false);
/** get a distance table by table_ID
*/
inline const DistanceTableData& getDistTable(int table_ID) const { return *DistTables[table_ID]; }
/** reset all the collectable quantities during a MC iteration
*/
inline void resetCollectables() { std::fill(Collectables.begin(), Collectables.end(), 0.0); }
/** update the internal data
*@param skip SK update if skipSK is true
*/
void update(bool skipSK = false);
/** create Structure Factor with PBCs
*/
void createSK();
/** Turn on per particle storage in Structure Factor
*/
void turnOnPerParticleSK();
///retrun the SpeciesSet of this particle set
inline SpeciesSet& getSpeciesSet() { return mySpecies; }
///retrun the const SpeciesSet of this particle set
inline const SpeciesSet& getSpeciesSet() const { return mySpecies; }
///return parent's name
inline const std::string& parentName() const { return ParentName; }
inline void setName(const std::string& aname)
{
myName = aname;
if (ParentName == "0")
{
ParentName = aname;
}
}
//inline RealType getTotalWeight() const { return EnsembleProperty.Weight; }
void resetGroups();
/** set active particle
* @param iat particle index
*
* Compute internal data based on current R[iat]
* Introduced to work with update-only methods.
*/
void setActive(int iat);
/// batched version of setActive
static void flex_setActive(const RefVector<ParticleSet>& P_list, int iat);
/** return the position of the active particle
*
* activePtcl=-1 is used to flag non-physical moves
*/
inline const PosType& activeR(int iat) const { return (activePtcl == iat) ? activePos : R[iat]; }
/** move the iat-th particle to activePos
* @param iat the index of the particle to be moved
* @param displ the displacement of the iat-th particle position
*
* Update activePtcl index and activePos position (R[iat]+displ) for a proposed move.
* Evaluate the related distance table data DistanceTableData::Temp.
*/
void makeMove(Index_t iat, const SingleParticlePos_t& displ);
/// batched version of makeMove
static void flex_makeMove(const RefVector<ParticleSet>& P_list, int iat, const std::vector<SingleParticlePos_t>& displs);
/** move the iat-th particle to activePos
* @param iat the index of the particle to be moved
* @param displ random displacement of the iat-th particle
* @return true, if the move is valid
*
* Update activePtcl index and activePos position (R[iat]+displ) for a proposed move.
* Evaluate the related distance table data DistanceTableData::Temp.
*
* When a Lattice is defined, passing two checks makes a move valid.
* outOfBound(displ): invalid move, if displ is larger than half, currently, of the box in any direction
* isValid(Lattice.toUnit(activePos)): invalid move, if activePos goes out of the Lattice in any direction marked with open BC.
* Note: activePos and distances tables are always evaluated no matter the move is valid or not.
*/
bool makeMoveAndCheck(Index_t iat, const SingleParticlePos_t& displ);
/** Handles virtual moves for all the particles to a single newpos.
*
* The state activePtcl remains -1 and rejectMove is not needed.
* acceptMove can not be used.
* See QMCHamiltonians::MomentumEstimator as an example
*/
void makeVirtualMoves(const SingleParticlePos_t& newpos);
/** move all the particles of a walker
* @param awalker the walker to operate
* @param deltaR proposed displacement
* @param dt factor of deltaR
* @return true if all the moves are legal.
*
* If big displacements or illegal positions are detected, return false.
* If all good, R = awalker.R + dt* deltaR
*/
bool makeMoveAllParticles(const Walker_t& awalker, const ParticlePos_t& deltaR, RealType dt);
bool makeMoveAllParticles(const Walker_t& awalker, const ParticlePos_t& deltaR, const std::vector<RealType>& dt);
/** move all the particles including the drift
*
* Otherwise, everything is the same as makeMove for a walker
*/
bool makeMoveAllParticlesWithDrift(const Walker_t& awalker, const ParticlePos_t& drift, const ParticlePos_t& deltaR, RealType dt);
bool makeMoveAllParticlesWithDrift(const Walker_t& awalker,
const ParticlePos_t& drift,
const ParticlePos_t& deltaR,
const std::vector<RealType>& dt);
/** accept the move
*@param iat the index of the particle whose position and other attributes to be updated
*/
void acceptMove(Index_t iat);
/// batched version of acceptMove
static void flex_acceptMove(const RefVector<ParticleSet>& P_list, Index_t iat)
{
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().acceptMove(iat);
}
/** reject the move
*/
void rejectMove(Index_t iat) { activePtcl = -1; }
/// batched version of rejectMove
static void flex_rejectMove(const RefVector<ParticleSet>& P_list, Index_t iat)
{
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().rejectMove(iat);
}
void initPropertyList();
inline int addProperty(const std::string& pname) { return PropertyList.add(pname.c_str()); }
int addPropertyHistory(int leng);
// void rejectedMove();
// void resetPropertyHistory( );
// void addPropertyHistoryPoint(int index, RealType data);
void clearDistanceTables();
void convert(const ParticlePos_t& pin, ParticlePos_t& pout);
void convert2Unit(const ParticlePos_t& pin, ParticlePos_t& pout);
void convert2Cart(const ParticlePos_t& pin, ParticlePos_t& pout);
void convert2Unit(ParticlePos_t& pout);
void convert2Cart(ParticlePos_t& pout);
void convert2UnitInBox(const ParticlePos_t& pint, ParticlePos_t& pout);
void convert2CartInBox(const ParticlePos_t& pint, ParticlePos_t& pout);
void applyBC(const ParticlePos_t& pin, ParticlePos_t& pout);
void applyBC(ParticlePos_t& pos);
void applyBC(const ParticlePos_t& pin, ParticlePos_t& pout, int first, int last);
void applyMinimumImage(ParticlePos_t& pinout);
/** load a Walker_t to the current ParticleSet
* @param awalker the reference to the walker to be loaded
* @param pbyp true if it is used by PbyP update
*
* PbyP requires the distance tables and Sk with awalker.R
*/
void loadWalker(Walker_t& awalker, bool pbyp);
/** save this to awalker
*
* just the R, G, and L
* More duplicate data that makes code difficult to reason about should be removed.
*/
void saveWalker(Walker_t& awalker);
/** batched version of saveWalker
*
* just the R, G, and L
*/
static void flex_saveWalker(RefVector<ParticleSet>& psets, RefVector<Walker_t>& walkers);
/** update structure factor and unmark activePtcl
*
* The Coulomb interaction evaluation needs the structure factor.
* For these reason, call donePbyP after the loop of single
* electron moves before evaluating the Hamiltonian. Unmark
* activePtcl is more of a safety measure probably not needed.
*/
void donePbyP();
/// batched version of donePbyP
static void flex_donePbyP(const RefVector<ParticleSet>& P_list)
{
#pragma omp parallel for
for (int iw = 0; iw < P_list.size(); iw++)
P_list[iw].get().donePbyP();
}
///return the address of the values of Hamiltonian terms
inline FullPrecRealType* restrict getPropertyBase() { return Properties.data(); }
///return the address of the values of Hamiltonian terms
inline const FullPrecRealType* restrict getPropertyBase() const { return Properties.data(); }
///return the address of the i-th properties
inline FullPrecRealType* restrict getPropertyBase(int i) { return Properties[i]; }
///return the address of the i-th properties
inline const FullPrecRealType* restrict getPropertyBase(int i) const { return Properties[i]; }
inline void setTwist(SingleParticlePos_t& t) { myTwist = t; }
inline SingleParticlePos_t getTwist() const { return myTwist; }
/** Initialize particles around another ParticleSet
* Used to initialize an electron ParticleSet by an ion ParticleSet
*/
void randomizeFromSource(ParticleSet& src);
/** return the ip-th clone
* @param ip thread number
*
* Return itself if ip==0
*/
inline ParticleSet* get_clone(int ip)
{
if (ip >= myClones.size())
return 0;
return (ip) ? myClones[ip] : this;
}
inline const ParticleSet* get_clone(int ip) const
{
if (ip >= myClones.size())
return 0;
return (ip) ? myClones[ip] : this;
}
inline int clones_size() const { return myClones.size(); }
/** update R of its own and its clones
* @param rnew new position array of N
*/
template<typename PAT>
inline void update_clones(const PAT& rnew)
{
if (R.size() != rnew.size())
APP_ABORT("ParticleSet::updateR failed due to different sizes");
R = rnew;
for (int ip = 1; ip < myClones.size(); ++ip)
myClones[ip]->R = rnew;
}
/** reset internal data of clones including itself
*/
void reset_clones();
/** get species name of particle i
*/
inline const std::string& species_from_index(int i) { return mySpecies.speciesName[GroupID[i]]; }
inline size_t getTotalNum() const { return TotalNum; }
inline void resize(size_t numPtcl)
{
TotalNum = numPtcl;
R.resize(numPtcl);
spins.resize(numPtcl);
ID.resize(numPtcl);
PCID.resize(numPtcl);
GroupID.resize(numPtcl);
G.resize(numPtcl);
dG.resize(numPtcl);
L.resize(numPtcl);
dL.resize(numPtcl);
Mass.resize(numPtcl);
Z.resize(numPtcl);
IndirectID.resize(numPtcl);
RSoA.resize(numPtcl);
}
inline void clear()
{
TotalNum = 0;
R.clear();
spins.clear();
ID.clear();
PCID.clear();
GroupID.clear();
G.clear();
dG.clear();
L.clear();
dL.clear();
Mass.clear();
Z.clear();
IndirectID.clear();
RSoA.resize(0);
}
inline void assign(const ParticleSet& ptclin)
{
resize(ptclin.getTotalNum());
Lattice = ptclin.Lattice;
PrimitiveLattice = ptclin.PrimitiveLattice;
R.InUnit = ptclin.R.InUnit;
R = ptclin.R;
ID = ptclin.ID;
GroupID = ptclin.GroupID;
if (ptclin.SubPtcl.size())
{
SubPtcl.resize(ptclin.SubPtcl.size());
SubPtcl = ptclin.SubPtcl;
}
}
///return the number of groups
inline int groups() const { return SubPtcl.size() - 1; }
///return the first index of a group i
inline int first(int igroup) const { return SubPtcl[igroup]; }
///return the last index of a group i
inline int last(int igroup) const { return SubPtcl[igroup + 1]; }
inline int groupsize(int igroup) const { return SubPtcl[igroup + 1] - SubPtcl[igroup]; }
///add attributes to list for IO
template<typename ATList>
inline void createAttributeList(ATList& AttribList)
{
R.setTypeName(ParticleTags::postype_tag);
R.setObjName(ParticleTags::position_tag);
spins.setTypeName(ParticleTags::scalartype_tag);
spins.setObjName(ParticleTags::spins_tag);
ID.setTypeName(ParticleTags::indextype_tag);
ID.setObjName(ParticleTags::id_tag);
GroupID.setTypeName(ParticleTags::indextype_tag);
GroupID.setObjName(ParticleTags::ionid_tag);
//add basic attributes
AttribList.add(R);
AttribList.add(spins);
AttribList.add(ID);
AttribList.add(GroupID);
G.setTypeName(ParticleTags::gradtype_tag);
L.setTypeName(ParticleTags::laptype_tag);
dG.setTypeName(ParticleTags::gradtype_tag);
dL.setTypeName(ParticleTags::laptype_tag);
G.setObjName("grad");
L.setObjName("lap");
dG.setObjName("dgrad");
dL.setObjName("dlap");
AttribList.add(G);
AttribList.add(L);
AttribList.add(dG);
AttribList.add(dL);
//more particle attributes
Mass.setTypeName(ParticleTags::scalartype_tag);
Mass.setObjName("mass");
AttribList.add(Mass);
Z.setTypeName(ParticleTags::scalartype_tag);
Z.setObjName("charge");
AttribList.add(Z);
PCID.setTypeName(ParticleTags::indextype_tag); //add PCID tags
PCID.setObjName("pcid");
AttribList.add(PCID);
IndirectID.setTypeName(ParticleTags::indextype_tag); //add IndirectID tags
IndirectID.setObjName("id1");
AttribList.add(IndirectID);
}
inline int getNumDistTables() const { return DistTables.size(); }
protected:
/** map to handle distance tables
*
* myDistTableMap[source-particle-tag]= locator in the distance table
* myDistTableMap[ObjectTag] === 0
*/
std::map<std::string, int> myDistTableMap;
/// distance tables that need to be updated by moving this ParticleSet
std::vector<DistanceTableData*> DistTables;
/// Descriptions from distance table creation. Same order as DistTables.
std::vector<std::string> distTableDescriptions;
enum PSTimers
{
PS_newpos,
PS_donePbyP,
PS_setActive,
PS_update
};
static const TimerNameList_t<PSTimers> PSTimerNames;
TimerList_t myTimers;
SingleParticlePos_t myTwist;
std::string ParentName;
///total number of particles
size_t TotalNum;
///array to handle a group of distinct particles per species
ParticleIndex_t SubPtcl;
/** compute temporal DistTables and SK for a new particle position
*
* @param iat the particle that is moved on a sphere
* @param newpos a new particle position
*/
void computeNewPosDistTablesAndSK(Index_t iat, const SingleParticlePos_t& newpos);
/** compute temporal DistTables and SK for a new particle position for each walker in a batch
*
* @param P_list the list of wrapped ParticleSet references in a walker batch
* @param iat the particle that is moved on a sphere
* @param new_positions new particle positions
*/
static void mw_computeNewPosDistTablesAndSK(const RefVector<ParticleSet>& P_list, Index_t iat, const std::vector<SingleParticlePos_t>& new_positions);
};
} // namespace qmcplusplus
#endif
|
normal.c | /* =============================================================================
*
* normal.c
* -- Implementation of normal k-means clustering algorithm
*
* =============================================================================
*
* Author:
*
* Wei-keng Liao
* ECE Department, Northwestern University
* email: wkliao@ece.northwestern.edu
*
*
* Edited by:
*
* Jay Pisharath
* Northwestern University.
*
* Chi Cao Minh
* Stanford University
*
* =============================================================================
*
* For the license of bayes/sort.h and bayes/sort.c, please see the header
* of the files.
*
* ------------------------------------------------------------------------
*
* For the license of kmeans, please see kmeans/LICENSE.kmeans
*
* ------------------------------------------------------------------------
*
* For the license of ssca2, please see ssca2/COPYRIGHT
*
* ------------------------------------------------------------------------
*
* For the license of lib/mt19937ar.c and lib/mt19937ar.h, please see the
* header of the files.
*
* ------------------------------------------------------------------------
*
* For the license of lib/rbtree.h and lib/rbtree.c, please see
* lib/LEGALNOTICE.rbtree and lib/LICENSE.rbtree
*
* ------------------------------------------------------------------------
*
* Unless otherwise noted, the following license applies to STAMP files:
*
* Copyright (c) 2007, Stanford University
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Stanford University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY STANFORD UNIVERSITY ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* =============================================================================
*/
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include "common.h"
#include "normal.h"
#include "random.h"
#include "thread.h"
#include "timer.h"
#include "tm.h"
#include "util.h"
#include "stm/lib_hicamp.h"
double global_time = 0.0;
typedef struct args {
float** feature;
int nfeatures;
int npoints;
int nclusters;
int* membership;
float** clusters;
int** new_centers_len;
float** new_centers;
} args_t;
float global_delta;
long global_i; /* index into task queue */
#define CHUNK 3
/* =============================================================================
* work
* =============================================================================
*/
static void
work (void* argPtr)
{
TM_THREAD_ENTER();
args_t* args = (args_t*)argPtr;
float** feature = args->feature;
int nfeatures = args->nfeatures;
int npoints = args->npoints;
int nclusters = args->nclusters;
int* membership = args->membership;
float** clusters = args->clusters;
int** new_centers_len = args->new_centers_len;
float** new_centers = args->new_centers;
float delta = 0.0;
int index;
int i;
int j;
int start;
int stop;
int myId;
myId = thread_getId();
start = myId * CHUNK;
while (start < npoints) {
stop = (((start + CHUNK) < npoints) ? (start + CHUNK) : npoints);
for (i = start; i < stop; i++) {
index = common_findNearestPoint(feature[i],
nfeatures,
clusters,
nclusters);
/*
* If membership changes, increase delta by 1.
* membership[i] cannot be changed by other threads
*/
if (membership[i] != index) {
delta += 1.0;
}
/* Assign the membership to object i */
/* membership[i] can't be changed by other thread */
membership[i] = index;
/* Update new cluster centers : sum of objects located within */
TM_BEGIN();
printf("DOing shared write\n");
TM_SHARED_WRITE_I(*new_centers_len[index],
TM_SHARED_READ_I(*new_centers_len[index]) + 1);
printf("SW DONE\n");
for (j = 0; j < nfeatures; j++) {
TM_SHARED_WRITE_F(
new_centers[index][j],
(TM_SHARED_READ_F(new_centers[index][j]) + feature[i][j])
);
}
TM_END();
}
/* Update task queue */
if (start + CHUNK < npoints) {
TM_BEGIN();
start = (int)TM_SHARED_READ_L(global_i);
TM_SHARED_WRITE_L(global_i, (long)(start + CHUNK));
TM_END();
} else {
break;
}
}
TM_BEGIN();
TM_SHARED_WRITE_F(global_delta, TM_SHARED_READ_F(global_delta) + delta);
TM_END();
TM_THREAD_EXIT();
}
/* =============================================================================
* normal_exec
* =============================================================================
*/
float**
normal_exec (int nthreads,
float** feature, /* in: [npoints][nfeatures] */
int nfeatures,
int npoints,
int nclusters,
float threshold,
int* membership,
random_t* randomPtr) /* out: [npoints] */
{
int i;
int j;
int loop = 0;
int** new_centers_len; /* [nclusters]: no. of points in each cluster */
float delta;
float** clusters; /* out: [nclusters][nfeatures] */
float** new_centers; /* [nclusters][nfeatures] */
void* alloc_memory = NULL;
args_t args;
TIMER_T startTime;
TIMER_T stopTime;
/* Allocate space for returning variable clusters[] */
clusters = (float**)SEQ_MALLOC(nclusters * sizeof(float*));
assert(clusters);
clusters[0] = (float*)SEQ_MALLOC(nclusters * nfeatures * sizeof(float));
assert(clusters[0]);
for (i = 1; i < nclusters; i++) {
clusters[i] = clusters[i-1] + nfeatures;
}
/* Randomly pick cluster centers */
for (i = 0; i < nclusters; i++) {
int n = (int)(random_generate(randomPtr) % npoints);
for (j = 0; j < nfeatures; j++) {
clusters[i][j] = feature[n][j];
}
}
for (i = 0; i < npoints; i++) {
membership[i] = -1;
}
/*
* Need to initialize new_centers_len and new_centers[0] to all 0.
* Allocate clusters on different cache lines to reduce false sharing.
*/
{
int cluster_size = sizeof(int) + sizeof(float) * nfeatures;
const int cacheLineSize = 32;
cluster_size += (cacheLineSize-1) - ((cluster_size-1) % cacheLineSize);
alloc_memory = hccalloc(nclusters, cluster_size);
printf("allocing new centers len\n");
new_centers_len = (int**) SEQ_MALLOC(nclusters * sizeof(int*));
printf("alloc new centers done %p\n", new_centers_len);
new_centers = (float**) SEQ_MALLOC(nclusters * sizeof(float*));
assert(alloc_memory && new_centers && new_centers_len);
for (i = 0; i < nclusters; i++) {
new_centers_len[i] = (int*)((char*)alloc_memory + cluster_size * i);
new_centers[i] = (float*)((char*)alloc_memory + cluster_size * i + sizeof(int));
}
}
// NB: Since ASF/PTLSim "REAL" is native execution, and since we are using
// wallclock time, we want to be sure we read time inside the
// simulator, or else we report native cycles spent on the benchmark
// instead of simulator cycles.
//GOTO_SIM();
//TIMER_READ(start);
BEGIN_ROI;
do {
delta = 0.0;
args.feature = feature;
args.nfeatures = nfeatures;
args.npoints = npoints;
args.nclusters = nclusters;
args.membership = membership;
args.clusters = clusters;
args.new_centers_len = new_centers_len;
args.new_centers = new_centers;
global_i = nthreads * CHUNK;
global_delta = delta;
#ifdef OTM
#pragma omp parallel
{
work(&args);
}
#else
thread_start(work, &args);
#endif
delta = global_delta;
/* Replace old cluster centers with new_centers */
for (i = 0; i < nclusters; i++) {
for (j = 0; j < nfeatures; j++) {
if (new_centers_len[i] > 0) {
clusters[i][j] = new_centers[i][j] / *new_centers_len[i];
}
new_centers[i][j] = 0.0; /* set back to 0 */
}
*new_centers_len[i] = 0; /* set back to 0 */
}
delta /= npoints;
} while ((delta > threshold) && (loop++ < 500));
END_ROI;
//TIMER_READ(stop);
// NB: As above, timer reads must be done inside of the simulated region
// for PTLSim/ASF
//GOTO_REAL();
global_time += TIMER_DIFF_SECONDS(startTime, stopTime);
SEQ_FREE(alloc_memory);
SEQ_FREE(new_centers);
SEQ_FREE(new_centers_len);
return clusters;
}
/* =============================================================================
*
* End of normal.c
*
* =============================================================================
*/
|
GB_binop__minus_uint16.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__minus_uint16)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__minus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_03__minus_uint16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__minus_uint16)
// A*D function (colscale): GB (_AxD__minus_uint16)
// D*A function (rowscale): GB (_DxB__minus_uint16)
// C+=B function (dense accum): GB (_Cdense_accumB__minus_uint16)
// C+=b function (dense accum): GB (_Cdense_accumb__minus_uint16)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__minus_uint16)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__minus_uint16)
// C=scalar+B GB (_bind1st__minus_uint16)
// C=scalar+B' GB (_bind1st_tran__minus_uint16)
// C=A+scalar GB (_bind2nd__minus_uint16)
// C=A'+scalar GB (_bind2nd_tran__minus_uint16)
// C type: uint16_t
// A type: uint16_t
// B,b type: uint16_t
// BinaryOp: cij = (aij - bij)
#define GB_ATYPE \
uint16_t
#define GB_BTYPE \
uint16_t
#define GB_CTYPE \
uint16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
uint16_t aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
uint16_t bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = (x - y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINUS || GxB_NO_UINT16 || GxB_NO_MINUS_UINT16)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__minus_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__minus_uint16)
(
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__minus_uint16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__minus_uint16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint16_t
uint16_t bwork = (*((uint16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__minus_uint16)
(
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
uint16_t *restrict Cx = (uint16_t *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__minus_uint16)
(
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
uint16_t *restrict Cx = (uint16_t *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__minus_uint16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool 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__minus_uint16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__minus_uint16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__minus_uint16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_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__minus_uint16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__minus_uint16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t x = (*((uint16_t *) x_input)) ;
uint16_t *Bx = (uint16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint16_t bij = Bx [p] ;
Cx [p] = (x - bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__minus_uint16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint16_t *Cx = (uint16_t *) Cx_output ;
uint16_t *Ax = (uint16_t *) Ax_input ;
uint16_t y = (*((uint16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint16_t aij = Ax [p] ;
Cx [p] = (aij - y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = (x - aij) ; \
}
GrB_Info GB (_bind1st_tran__minus_uint16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t x = (*((const uint16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint16_t aij = Ax [pA] ; \
Cx [pC] = (aij - y) ; \
}
GrB_Info GB (_bind2nd_tran__minus_uint16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint16_t y = (*((const uint16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
par_mod_lr_interp.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 "aux_interp.h"
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildModExtInterp
* Comment:
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtInterpHost(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
/* Communication Variables */
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle = NULL;
HYPRE_Int my_id, num_procs;
/* Variables to store input variables */
hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A);
HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag);
HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag);
HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag);
hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A);
HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd);
HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd);
HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd);
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt total_global_cpts;
/* Interpolation matrix P */
hypre_ParCSRMatrix *P;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data = NULL;
HYPRE_Int *P_diag_i, *P_diag_j = NULL;
HYPRE_Real *P_offd_data = NULL;
HYPRE_Int *P_offd_i, *P_offd_j = NULL;
/* Intermediate matrices */
hypre_ParCSRMatrix *As_FF, *As_FC, *W;
HYPRE_Real *D_q, *D_w;
hypre_CSRMatrix *As_FF_diag;
hypre_CSRMatrix *As_FF_offd;
hypre_CSRMatrix *As_FC_diag;
hypre_CSRMatrix *As_FC_offd;
hypre_CSRMatrix *W_diag;
hypre_CSRMatrix *W_offd;
HYPRE_Int *As_FF_diag_i;
HYPRE_Int *As_FF_offd_i;
HYPRE_Int *As_FC_diag_i;
HYPRE_Int *As_FC_offd_i;
HYPRE_Int *W_diag_i;
HYPRE_Int *W_offd_i;
HYPRE_Int *W_diag_j;
HYPRE_Int *W_offd_j;
HYPRE_Real *As_FF_diag_data;
HYPRE_Real *As_FF_offd_data;
HYPRE_Real *As_FC_diag_data;
HYPRE_Real *As_FC_offd_data;
HYPRE_Real *W_diag_data;
HYPRE_Real *W_offd_data;
HYPRE_BigInt *col_map_offd_P = NULL;
HYPRE_BigInt *new_col_map_offd = NULL;
HYPRE_Int P_diag_size;
HYPRE_Int P_offd_size;
HYPRE_Int new_ncols_P_offd;
HYPRE_Int num_cols_P_offd;
HYPRE_Int *P_marker = NULL;
HYPRE_Int *dof_func_offd = NULL;
/* Loop variables */
HYPRE_Int index;
HYPRE_Int i, j;
HYPRE_Int *cpt_array;
HYPRE_Int *start_array;
HYPRE_Int *startf_array;
HYPRE_Int start, stop, startf, stopf;
HYPRE_Int cnt_diag, cnt_offd, row, c_pt;
/* Definitions */
//HYPRE_Real wall_time;
HYPRE_Int n_Cpts, n_Fpts;
HYPRE_Int num_threads = hypre_NumThreads();
//if (debug_flag==4) wall_time = time_getWallclockSeconds();
/* BEGIN */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
n_Cpts = num_cpts_global[1]-num_cpts_global[0];
hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF);
As_FC_diag = hypre_ParCSRMatrixDiag(As_FC);
As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag);
As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag);
As_FC_offd = hypre_ParCSRMatrixOffd(As_FC);
As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd);
As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd);
As_FF_diag = hypre_ParCSRMatrixDiag(As_FF);
As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag);
As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag);
As_FF_offd = hypre_ParCSRMatrixOffd(As_FF);
As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd);
As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd);
n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag);
D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
start_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
startf_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,start,stop,startf,stopf,row)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
HYPRE_Real beta, gamma;
start = (n_fine/num_threads)*my_thread_num;
if (my_thread_num == num_threads-1)
{
stop = n_fine;
}
else
{
stop = (n_fine/num_threads)*(my_thread_num+1);
}
start_array[my_thread_num+1] = stop;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
cpt_array[my_thread_num]++;
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num == 0)
{
for (i=1; i < num_threads; i++)
{
cpt_array[i] += cpt_array[i-1];
}
if (num_functions > 1)
{
HYPRE_Int *int_buf_data = NULL;
HYPRE_Int num_sends, startc;
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
index = 0;
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num > 0)
startf = start - cpt_array[my_thread_num-1];
else
startf = 0;
if (my_thread_num < num_threads-1)
stopf = stop - cpt_array[my_thread_num];
else
stopf = n_Fpts;
startf_array[my_thread_num+1] = stopf;
/* Create D_q = D_beta */
for (i=startf; i < stopf; i++)
{
for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++)
{
D_q[i] += As_FC_diag_data[j];
}
for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++)
{
D_q[i] += As_FC_offd_data[j];
}
}
/* Create D_w = D_alpha + D_gamma */
row = startf;
for (i=start; i < stop; i++)
{
if (CF_marker[i] < 0)
{
if (num_functions > 1)
{
HYPRE_Int jA, jS, jC;
jC = A_diag_i[i];
for (j=S_diag_i[i]; j < S_diag_i[i+1]; j++)
{
jS = S_diag_j[j];
jA = A_diag_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func[jA])
{
D_w[row] += A_diag_data[jC++];
}
else
jC++;
jA = A_diag_j[jC];
}
jC++;
}
for (j=jC; j < A_diag_i[i+1]; j++)
{
if (dof_func[i] == dof_func[A_diag_j[j]])
D_w[row] += A_diag_data[j];
}
jC = A_offd_i[i];
for (j=S_offd_i[i]; j < S_offd_i[i+1]; j++)
{
jS = S_offd_j[j];
jA = A_offd_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func_offd[jA])
{
D_w[row] += A_offd_data[jC++];
}
else
jC++;
jA = A_offd_j[jC];
}
jC++;
}
for (j=jC; j < A_offd_i[i+1]; j++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[j]])
D_w[row] += A_offd_data[j];
}
row++;
}
else
{
for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++)
{
D_w[row] += A_diag_data[j];
}
for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
D_w[row] += A_offd_data[j];
}
for (j=As_FF_diag_i[row]+1; j < As_FF_diag_i[row+1]; j++)
{
D_w[row] -= As_FF_diag_data[j];
}
for (j=As_FF_offd_i[row]; j < As_FF_offd_i[row+1]; j++)
{
D_w[row] -= As_FF_offd_data[j];
}
D_w[row] -= D_q[row];
row++;
}
}
}
for (i=startf; i<stopf; i++)
{
j = As_FF_diag_i[i];
if (D_w[i]) beta = 1.0/D_w[i];
else beta = 1.0;
As_FF_diag_data[j] = beta*D_q[i];
if (D_q[i]) gamma = -1.0/D_q[i];
else gamma = 1.0;
for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++)
As_FF_diag_data[j] *= beta;
for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
As_FF_offd_data[j] *= beta;
for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++)
As_FC_diag_data[j] *= gamma;
for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++)
As_FC_offd_data[j] *= gamma;
}
} /* end parallel region */
W = hypre_ParMatmul(As_FF, As_FC);
W_diag = hypre_ParCSRMatrixDiag(W);
W_offd = hypre_ParCSRMatrixOffd(W);
W_diag_i = hypre_CSRMatrixI(W_diag);
W_diag_j = hypre_CSRMatrixJ(W_diag);
W_diag_data = hypre_CSRMatrixData(W_diag);
W_offd_i = hypre_CSRMatrixI(W_offd);
W_offd_j = hypre_CSRMatrixJ(W_offd);
W_offd_data = hypre_CSRMatrixData(W_offd);
num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd);
/*-----------------------------------------------------------------------
* Intialize data for P
*-----------------------------------------------------------------------*/
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts];
P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts];
if (P_diag_size)
{
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P);
}
if (P_offd_size)
{
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
startf = startf_array[my_thread_num];
stopf = startf_array[my_thread_num+1];
start = start_array[my_thread_num];
stop = start_array[my_thread_num+1];
if (my_thread_num > 0)
c_pt = cpt_array[my_thread_num-1];
else
c_pt = 0;
cnt_diag = W_diag_i[startf]+c_pt;
cnt_offd = W_offd_i[startf];
row = startf;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
P_diag_j[cnt_diag] = c_pt++;
P_diag_data[cnt_diag++] = 1.0;
}
else
{
for (j=W_diag_i[row]; j < W_diag_i[row+1]; j++)
{
P_diag_j[cnt_diag] = W_diag_j[j];
P_diag_data[cnt_diag++] = W_diag_data[j];
}
for (j=W_offd_i[row]; j < W_offd_i[row+1]; j++)
{
P_offd_j[cnt_offd] = W_offd_j[j];
P_offd_data[cnt_offd++] = W_offd_data[j];
}
row++;
}
P_diag_i[i+1] = cnt_diag;
P_offd_i[i+1] = cnt_offd;
}
} /* end parallel region */
/*-----------------------------------------------------------------------
* Create matrix
*-----------------------------------------------------------------------*/
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
num_cols_P_offd,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W);
hypre_ParCSRMatrixColMapOffd(W) = NULL;
hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P;
hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
HYPRE_Int *map;
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P);
if (num_cols_P_offd)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
for (i=0; i < P_offd_size; i++)
{
P_marker[P_offd_j[i]] = 1;
}
new_ncols_P_offd = 0;
for (i=0; i < num_cols_P_offd; i++)
{
if (P_marker[i]) new_ncols_P_offd++;
}
new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST);
map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
if (P_marker[i])
{
new_col_map_offd[index] = col_map_offd_P[i];
map[index++] = i;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
{
P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i],
new_ncols_P_offd);
}
hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd;
hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd;
hypre_TFree(map, HYPRE_MEMORY_HOST);
}
}
hypre_MatvecCommPkgCreate(P);
*P_ptr = P;
/* Deallocate memory */
hypre_TFree(D_q, HYPRE_MEMORY_HOST);
hypre_TFree(D_w, HYPRE_MEMORY_HOST);
hypre_TFree(cpt_array, HYPRE_MEMORY_HOST);
hypre_TFree(start_array, HYPRE_MEMORY_HOST);
hypre_TFree(startf_array, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDestroy(As_FF);
hypre_ParCSRMatrixDestroy(As_FC);
hypre_ParCSRMatrixDestroy(W);
return hypre_error_flag;
}
/*-----------------------------------------------------------------------*
* Modularized Extended Interpolation
*-----------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtInterp(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPushRange("ModExtInterp");
#endif
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) );
HYPRE_Int ierr = 0;
if (exec == HYPRE_EXEC_HOST)
{
ierr = hypre_BoomerAMGBuildModExtInterpHost(A,CF_marker,S,num_cpts_global,num_functions,dof_func,
debug_flag,trunc_factor,max_elmts,P_ptr);
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
else
{
ierr = hypre_BoomerAMGBuildExtInterpDevice(A,CF_marker,S,num_cpts_global,1,NULL,
debug_flag,trunc_factor,max_elmts,P_ptr);
}
#endif
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPopRange();
#endif
return ierr;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildModExtPIInterp
* Comment:
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtPIInterpHost(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int debug_flag,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
/* Communication Variables */
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle = NULL;
HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A);
HYPRE_Int my_id, num_procs;
/* Variables to store input variables */
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_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt total_global_cpts;
hypre_CSRMatrix *As_FF_ext = NULL;
HYPRE_Real *As_FF_ext_data = NULL;
HYPRE_Int *As_FF_ext_i = NULL;
HYPRE_BigInt *As_FF_ext_j = NULL;
/* Interpolation matrix P */
hypre_ParCSRMatrix *P;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data = NULL;
HYPRE_Int *P_diag_i, *P_diag_j = NULL;
HYPRE_Real *P_offd_data = NULL;
HYPRE_Int *P_offd_i, *P_offd_j = NULL;
/* Intermediate matrices */
hypre_ParCSRMatrix *As_FF, *As_FC, *W;
HYPRE_Real *D_q, *D_w, *D_theta, *D_q_offd = NULL;
hypre_CSRMatrix *As_FF_diag;
hypre_CSRMatrix *As_FF_offd;
hypre_CSRMatrix *As_FC_diag;
hypre_CSRMatrix *As_FC_offd;
hypre_CSRMatrix *W_diag;
hypre_CSRMatrix *W_offd;
HYPRE_Int *As_FF_diag_i;
HYPRE_Int *As_FF_diag_j;
HYPRE_Int *As_FF_offd_i;
HYPRE_Int *As_FF_offd_j = NULL;
HYPRE_Int *As_FC_diag_i;
HYPRE_Int *As_FC_offd_i;
HYPRE_Int *W_diag_i;
HYPRE_Int *W_offd_i;
HYPRE_Int *W_diag_j;
HYPRE_Int *W_offd_j = NULL;
HYPRE_Real *As_FF_diag_data;
HYPRE_Real *As_FF_offd_data = NULL;
HYPRE_Real *As_FC_diag_data;
HYPRE_Real *As_FC_offd_data = NULL;
HYPRE_Real *W_diag_data;
HYPRE_Real *W_offd_data = NULL;
HYPRE_Real *buf_data = NULL;
HYPRE_Real *tmp_FF_diag_data = NULL;
HYPRE_BigInt *col_map_offd_P = NULL;
HYPRE_BigInt *new_col_map_offd = NULL;
HYPRE_BigInt first_index;
HYPRE_Int P_diag_size;
HYPRE_Int P_offd_size;
HYPRE_Int new_ncols_P_offd;
HYPRE_Int num_cols_P_offd;
HYPRE_Int *P_marker = NULL;
HYPRE_Int *dof_func_offd = NULL;
/* Loop variables */
HYPRE_Int index, startc, num_sends;
HYPRE_Int i, j, jj, k, kk;
HYPRE_Int *cpt_array;
HYPRE_Int *start_array;
HYPRE_Int *startf_array;
HYPRE_Int start, stop, startf, stopf;
HYPRE_Int cnt_diag, cnt_offd, row, c_pt;
HYPRE_Int num_cols_A_FF_offd;
HYPRE_Real value, value1, theta;
/* Definitions */
//HYPRE_Real wall_time;
HYPRE_Int n_Cpts, n_Fpts;
HYPRE_Int num_threads = hypre_NumThreads();
//if (debug_flag==4) wall_time = time_getWallclockSeconds();
/* BEGIN */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
n_Cpts = num_cpts_global[1]-num_cpts_global[0];
hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF);
if (num_procs > 1)
{
As_FF_ext = hypre_ParCSRMatrixExtractBExt(As_FF,As_FF,1);
As_FF_ext_i = hypre_CSRMatrixI(As_FF_ext);
As_FF_ext_j = hypre_CSRMatrixBigJ(As_FF_ext);
As_FF_ext_data = hypre_CSRMatrixData(As_FF_ext);
}
As_FC_diag = hypre_ParCSRMatrixDiag(As_FC);
As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag);
As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag);
As_FC_offd = hypre_ParCSRMatrixOffd(As_FC);
As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd);
As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd);
As_FF_diag = hypre_ParCSRMatrixDiag(As_FF);
As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag);
As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag);
As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag);
As_FF_offd = hypre_ParCSRMatrixOffd(As_FF);
As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd);
As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd);
As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd);
n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag);
num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd);
first_index = hypre_ParCSRMatrixRowStarts(As_FF)[0];
tmp_FF_diag_data = hypre_CTAlloc(HYPRE_Real, As_FF_diag_i[n_Fpts], HYPRE_MEMORY_HOST);
D_q = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_theta = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
start_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
startf_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,jj,k,kk,start,stop,startf,stopf,row,theta,value,value1)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
start = (n_fine/num_threads)*my_thread_num;
if (my_thread_num == num_threads-1)
{
stop = n_fine;
}
else
{
stop = (n_fine/num_threads)*(my_thread_num+1);
}
start_array[my_thread_num+1] = stop;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
cpt_array[my_thread_num]++;
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num == 0)
{
for (i=1; i < num_threads; i++)
{
cpt_array[i] += cpt_array[i-1];
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num > 0)
startf = start - cpt_array[my_thread_num-1];
else
startf = 0;
if (my_thread_num < num_threads-1)
stopf = stop - cpt_array[my_thread_num];
else
stopf = n_Fpts;
startf_array[my_thread_num+1] = stopf;
for (i=startf; i < stopf; i++)
{
for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++)
{
D_q[i] += As_FC_diag_data[j];
}
for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++)
{
D_q[i] += As_FC_offd_data[j];
}
}
for (j = As_FF_diag_i[startf]; j < As_FF_diag_i[stopf]; j++)
{
tmp_FF_diag_data[j] = As_FF_diag_data[j];
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num == 0)
{
if (num_cols_A_FF_offd)
{
D_q_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, HYPRE_MEMORY_HOST);
}
index = 0;
comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF);
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(As_FF);
comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
buf_data[index++] = D_q[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_q_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
if (num_functions > 1)
{
HYPRE_Int *int_buf_data = NULL;
HYPRE_Int num_sends, startc;
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
index = 0;
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
row = startf;
for (i=start; i < stop; i++)
{
HYPRE_Int jA, jC, jS;
if (CF_marker[i] < 0)
{
if (num_functions > 1)
{
jC = A_diag_i[i];
for (j=S_diag_i[i]; j < S_diag_i[i+1]; j++)
{
jS = S_diag_j[j];
jA = A_diag_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func[jA])
{
D_w[row] += A_diag_data[jC++];
}
else
jC++;
jA = A_diag_j[jC];
}
jC++;
}
for (j=jC; j < A_diag_i[i+1]; j++)
{
if (dof_func[i] == dof_func[A_diag_j[j]])
D_w[row] += A_diag_data[j];
}
jC = A_offd_i[i];
for (j=S_offd_i[i]; j < S_offd_i[i+1]; j++)
{
jS = S_offd_j[j];
jA = A_offd_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func_offd[jA])
{
D_w[row] += A_offd_data[jC++];
}
else
jC++;
jA = A_offd_j[jC];
}
jC++;
}
for (j=jC; j < A_offd_i[i+1]; j++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[j]])
D_w[row] += A_offd_data[j];
}
row++;
}
else
{
for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++)
{
D_w[row] += A_diag_data[j];
}
for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
D_w[row] += A_offd_data[j];
}
for (j=As_FF_diag_i[row]+1; j < As_FF_diag_i[row+1]; j++)
{
D_w[row] -= As_FF_diag_data[j];
}
for (j=As_FF_offd_i[row]; j < As_FF_offd_i[row+1]; j++)
{
D_w[row] -= As_FF_offd_data[j];
}
D_w[row] -= D_q[row];
row++;
}
}
}
for (i=startf; i<stopf; i++)
{
for (j = As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++)
{
jj = As_FF_diag_j[j];
value = D_q[jj];
for (k = As_FF_diag_i[jj]+1; k < As_FF_diag_i[jj+1]; k++)
{
kk = As_FF_diag_j[k];
if (kk == i)
{
value1 = tmp_FF_diag_data[k];
value += value1;
D_theta[i] += As_FF_diag_data[j]*value1/value;
break;
}
}
As_FF_diag_data[j] /= value;
}
for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
{
jj = As_FF_offd_j[j];
value = D_q_offd[jj];
for (k = As_FF_ext_i[jj]; k < As_FF_ext_i[jj+1]; k++)
{
kk = (HYPRE_Int)(As_FF_ext_j[k] - first_index);
if (kk == i)
{
value1 = As_FF_ext_data[k];
value += value1;
D_theta[i] += As_FF_offd_data[j]*value1/value;
break;
}
}
As_FF_offd_data[j] /= value;
}
As_FF_diag_data[As_FF_diag_i[i]] = 1.0;
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
for (i=startf; i<stopf; i++)
{
theta = (D_theta[i]+D_w[i]);
if (theta)
{
theta = -1.0/theta;
for (j=As_FF_diag_i[i]; j < As_FF_diag_i[i+1]; j++)
As_FF_diag_data[j] *= theta;
for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
As_FF_offd_data[j] *= theta;
}
}
} /* end parallel region */
W = hypre_ParMatmul(As_FF, As_FC);
W_diag = hypre_ParCSRMatrixDiag(W);
W_offd = hypre_ParCSRMatrixOffd(W);
W_diag_i = hypre_CSRMatrixI(W_diag);
W_diag_j = hypre_CSRMatrixJ(W_diag);
W_diag_data = hypre_CSRMatrixData(W_diag);
W_offd_i = hypre_CSRMatrixI(W_offd);
W_offd_j = hypre_CSRMatrixJ(W_offd);
W_offd_data = hypre_CSRMatrixData(W_offd);
num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd);
/*-----------------------------------------------------------------------
* Intialize data for P
*-----------------------------------------------------------------------*/
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts];
P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts];
if (P_diag_size)
{
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P);
}
if (P_offd_size)
{
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
startf = startf_array[my_thread_num];
stopf = startf_array[my_thread_num+1];
start = start_array[my_thread_num];
stop = start_array[my_thread_num+1];
if (my_thread_num > 0)
c_pt = cpt_array[my_thread_num-1];
else
c_pt = 0;
cnt_diag = W_diag_i[startf]+c_pt;
cnt_offd = W_offd_i[startf];
row = startf;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
P_diag_j[cnt_diag] = c_pt++;
P_diag_data[cnt_diag++] = 1.0;
}
else
{
for (j=W_diag_i[row]; j < W_diag_i[row+1]; j++)
{
P_diag_j[cnt_diag] = W_diag_j[j];
P_diag_data[cnt_diag++] = W_diag_data[j];
}
for (j=W_offd_i[row]; j < W_offd_i[row+1]; j++)
{
P_offd_j[cnt_offd] = W_offd_j[j];
P_offd_data[cnt_offd++] = W_offd_data[j];
}
row++;
}
P_diag_i[i+1] = cnt_diag;
P_offd_i[i+1] = cnt_offd;
}
} /* end parallel region */
/*-----------------------------------------------------------------------
* Create matrix
*-----------------------------------------------------------------------*/
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
num_cols_P_offd,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W);
hypre_ParCSRMatrixColMapOffd(W) = NULL;
hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P;
hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
HYPRE_Int *map;
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P);
if (num_cols_P_offd)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
for (i=0; i < P_offd_size; i++)
P_marker[P_offd_j[i]] = 1;
new_ncols_P_offd = 0;
for (i=0; i < num_cols_P_offd; i++)
if (P_marker[i]) new_ncols_P_offd++;
new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST);
map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
if (P_marker[i])
{
new_col_map_offd[index] = col_map_offd_P[i];
map[index++] = i;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
{
P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i],
new_ncols_P_offd);
}
hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd;
hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd;
hypre_TFree(map, HYPRE_MEMORY_HOST);
}
}
hypre_MatvecCommPkgCreate(P);
*P_ptr = P;
/* Deallocate memory */
hypre_TFree(D_q, HYPRE_MEMORY_HOST);
hypre_TFree(D_q_offd, HYPRE_MEMORY_HOST);
hypre_TFree(D_w, HYPRE_MEMORY_HOST);
hypre_TFree(D_theta, HYPRE_MEMORY_HOST);
hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST);
hypre_TFree(cpt_array, HYPRE_MEMORY_HOST);
hypre_TFree(start_array, HYPRE_MEMORY_HOST);
hypre_TFree(startf_array, HYPRE_MEMORY_HOST);
hypre_TFree(buf_data, HYPRE_MEMORY_HOST);
hypre_TFree(tmp_FF_diag_data, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDestroy(As_FF);
hypre_ParCSRMatrixDestroy(As_FC);
hypre_ParCSRMatrixDestroy(W);
hypre_CSRMatrixDestroy(As_FF_ext);
return hypre_error_flag;
}
/*-----------------------------------------------------------------------*
* Modularized Extended+i Interpolation
*-----------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtPIInterp(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPushRange("ModExtPIInterp");
#endif
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) );
HYPRE_Int ierr = 0;
if (exec == HYPRE_EXEC_HOST)
{
ierr = hypre_BoomerAMGBuildModExtPIInterpHost(A, CF_marker, S, num_cpts_global,
debug_flag, num_functions, dof_func,
trunc_factor, max_elmts, P_ptr);
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
else
{
ierr = hypre_BoomerAMGBuildExtPIInterpDevice(A, CF_marker, S, num_cpts_global, 1, NULL,
debug_flag, trunc_factor, max_elmts, P_ptr);
}
#endif
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPopRange();
#endif
return ierr;
}
/*---------------------------------------------------------------------------
* hypre_BoomerAMGBuildModExtPEInterp
* Comment:
*--------------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtPEInterpHost(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
/* Communication Variables */
MPI_Comm comm = hypre_ParCSRMatrixComm(A);
HYPRE_MemoryLocation memory_location_P = hypre_ParCSRMatrixMemoryLocation(A);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A);
hypre_ParCSRCommHandle *comm_handle = NULL;
HYPRE_Int my_id, num_procs;
/* Variables to store input variables */
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_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag);
HYPRE_BigInt total_global_cpts;
/* Interpolation matrix P */
hypre_ParCSRMatrix *P;
hypre_CSRMatrix *P_diag;
hypre_CSRMatrix *P_offd;
HYPRE_Real *P_diag_data = NULL;
HYPRE_Int *P_diag_i, *P_diag_j = NULL;
HYPRE_Real *P_offd_data = NULL;
HYPRE_Int *P_offd_i, *P_offd_j = NULL;
/* Intermediate matrices */
hypre_ParCSRMatrix *As_FF, *As_FC, *W;
HYPRE_Real *D_beta, *D_w, *D_lambda, *D_tmp, *D_tau, *D_tmp_offd = NULL;
hypre_CSRMatrix *As_FF_diag;
hypre_CSRMatrix *As_FF_offd;
hypre_CSRMatrix *As_FC_diag;
hypre_CSRMatrix *As_FC_offd;
hypre_CSRMatrix *W_diag;
hypre_CSRMatrix *W_offd;
HYPRE_Int *As_FF_diag_i;
HYPRE_Int *As_FF_diag_j;
HYPRE_Int *As_FF_offd_i;
HYPRE_Int *As_FF_offd_j;
HYPRE_Int *As_FC_diag_i;
HYPRE_Int *As_FC_offd_i;
HYPRE_Int *W_diag_i;
HYPRE_Int *W_offd_i;
HYPRE_Int *W_diag_j;
HYPRE_Int *W_offd_j = NULL;
HYPRE_Real *As_FF_diag_data;
HYPRE_Real *As_FF_offd_data = NULL;
HYPRE_Real *As_FC_diag_data;
HYPRE_Real *As_FC_offd_data = NULL;
HYPRE_Real *W_diag_data;
HYPRE_Real *W_offd_data = NULL;
HYPRE_Real *buf_data = NULL;
HYPRE_BigInt *col_map_offd_P = NULL;
HYPRE_BigInt *new_col_map_offd = NULL;
HYPRE_Int P_diag_size;
HYPRE_Int P_offd_size;
HYPRE_Int new_ncols_P_offd;
HYPRE_Int num_cols_P_offd;
HYPRE_Int *P_marker = NULL;
HYPRE_Int *dof_func_offd = NULL;
/* Loop variables */
HYPRE_Int index, startc, num_sends;
HYPRE_Int i, j;
HYPRE_Int *cpt_array;
HYPRE_Int *start_array;
HYPRE_Int *startf_array;
HYPRE_Int start, stop, startf, stopf;
HYPRE_Int cnt_diag, cnt_offd, row, c_pt;
HYPRE_Int num_cols_A_FF_offd;
HYPRE_Real value, theta;
/* Definitions */
//HYPRE_Real wall_time;
HYPRE_Int n_Cpts, n_Fpts;
HYPRE_Int num_threads = hypre_NumThreads();
//if (debug_flag==4) wall_time = time_getWallclockSeconds();
/* BEGIN */
hypre_MPI_Comm_size(comm, &num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
if (my_id == (num_procs -1)) total_global_cpts = num_cpts_global[1];
hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs-1, comm);
n_Cpts = num_cpts_global[1]-num_cpts_global[0];
hypre_ParCSRMatrixGenerateFFFC(A, CF_marker, num_cpts_global, S, &As_FC, &As_FF);
As_FC_diag = hypre_ParCSRMatrixDiag(As_FC);
As_FC_diag_i = hypre_CSRMatrixI(As_FC_diag);
As_FC_diag_data = hypre_CSRMatrixData(As_FC_diag);
As_FC_offd = hypre_ParCSRMatrixOffd(As_FC);
As_FC_offd_i = hypre_CSRMatrixI(As_FC_offd);
As_FC_offd_data = hypre_CSRMatrixData(As_FC_offd);
As_FF_diag = hypre_ParCSRMatrixDiag(As_FF);
As_FF_diag_i = hypre_CSRMatrixI(As_FF_diag);
As_FF_diag_j = hypre_CSRMatrixJ(As_FF_diag);
As_FF_diag_data = hypre_CSRMatrixData(As_FF_diag);
As_FF_offd = hypre_ParCSRMatrixOffd(As_FF);
As_FF_offd_i = hypre_CSRMatrixI(As_FF_offd);
As_FF_offd_j = hypre_CSRMatrixJ(As_FF_offd);
As_FF_offd_data = hypre_CSRMatrixData(As_FF_offd);
n_Fpts = hypre_CSRMatrixNumRows(As_FF_diag);
num_cols_A_FF_offd = hypre_CSRMatrixNumCols(As_FF_offd);
D_beta = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_lambda = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_tmp = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_tau = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
D_w = hypre_CTAlloc(HYPRE_Real, n_Fpts, HYPRE_MEMORY_HOST);
cpt_array = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST);
start_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
startf_array = hypre_CTAlloc(HYPRE_Int, num_threads+1, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,start,stop,startf,stopf,row,theta,value)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
start = (n_fine/num_threads)*my_thread_num;
if (my_thread_num == num_threads-1)
{
stop = n_fine;
}
else
{
stop = (n_fine/num_threads)*(my_thread_num+1);
}
start_array[my_thread_num+1] = stop;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
cpt_array[my_thread_num]++;
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num == 0)
{
for (i=1; i < num_threads; i++)
{
cpt_array[i] += cpt_array[i-1];
}
if (num_functions > 1)
{
HYPRE_Int *int_buf_data = NULL;
HYPRE_Int num_sends, startc;
HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd);
dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_A_offd, HYPRE_MEMORY_HOST);
index = 0;
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST);
}
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num > 0)
startf = start - cpt_array[my_thread_num-1];
else
startf = 0;
if (my_thread_num < num_threads-1)
stopf = stop - cpt_array[my_thread_num];
else
stopf = n_Fpts;
startf_array[my_thread_num+1] = stopf;
for (i=startf; i < stopf; i++)
{
HYPRE_Real number;
for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++)
{
D_lambda[i] += As_FF_diag_data[j];
}
for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
{
D_lambda[i] += As_FF_offd_data[j];
}
number = (HYPRE_Real)(As_FF_diag_i[i+1]-As_FF_diag_i[i]-1+As_FF_offd_i[i+1]-As_FF_offd_i[i]);
if (number) D_lambda[i] /= number;
for (j=As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++)
{
D_beta[i] += As_FC_diag_data[j];
}
for (j=As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++)
{
D_beta[i] += As_FC_offd_data[j];
}
if (D_lambda[i]+D_beta[i]) D_tmp[i] = D_lambda[i]/(D_beta[i]+D_lambda[i]);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
if (my_thread_num == 0)
{
if (num_cols_A_FF_offd)
{
D_tmp_offd = hypre_CTAlloc(HYPRE_Real, num_cols_A_FF_offd, HYPRE_MEMORY_HOST);
}
index = 0;
comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF);
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(As_FF);
comm_pkg = hypre_ParCSRMatrixCommPkg(As_FF);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);
for (i = 0; i < num_sends; i++)
{
startc = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = startc; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
{
buf_data[index++] = D_tmp[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
}
comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, D_tmp_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp barrier
#endif
row = startf;
for (i=start; i < stop; i++)
{
if (CF_marker[i] < 0)
{
if (num_functions > 1)
{
HYPRE_Int jA, jC, jS;
jC = A_diag_i[i];
for (j=S_diag_i[i]; j < S_diag_i[i+1]; j++)
{
jS = S_diag_j[j];
jA = A_diag_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func[jA])
{
D_w[row] += A_diag_data[jC++];
}
else
jC++;
jA = A_diag_j[jC];
}
jC++;
}
for (j=jC; j < A_diag_i[i+1]; j++)
{
if (dof_func[i] == dof_func[A_diag_j[j]])
D_w[row] += A_diag_data[j];
}
jC = A_offd_i[i];
for (j=S_offd_i[i]; j < S_offd_i[i+1]; j++)
{
jS = S_offd_j[j];
jA = A_offd_j[jC];
while (jA != jS)
{
if (dof_func[i] == dof_func_offd[jA])
{
D_w[row] += A_offd_data[jC++];
}
else
jC++;
jA = A_offd_j[jC];
}
jC++;
}
for (j=jC; j < A_offd_i[i+1]; j++)
{
if (dof_func[i] == dof_func_offd[A_offd_j[j]])
D_w[row] += A_offd_data[j];
}
row++;
}
else
{
for (j=A_diag_i[i]; j < A_diag_i[i+1]; j++)
{
D_w[row] += A_diag_data[j];
}
for (j=A_offd_i[i]; j < A_offd_i[i+1]; j++)
{
D_w[row] += A_offd_data[j];
}
for (j=As_FF_diag_i[row]+1; j < As_FF_diag_i[row+1]; j++)
{
D_w[row] -= As_FF_diag_data[j];
}
for (j=As_FF_offd_i[row]; j < As_FF_offd_i[row+1]; j++)
{
D_w[row] -= As_FF_offd_data[j];
}
D_w[row] -= D_beta[row];
row++;
}
}
}
for (i=startf; i<stopf; i++)
{
for (j=As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++)
{
index = As_FF_diag_j[j];
D_tau[i] += As_FF_diag_data[j]*D_tmp[index];
}
for (j=As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
{
index = As_FF_offd_j[j];
D_tau[i] += As_FF_offd_data[j]*D_tmp_offd[index];
}
}
for (i=startf; i<stopf; i++)
{
value = D_w[i]+D_tau[i];
if (value) value = -1.0/value;
theta = D_beta[i]+D_lambda[i];
As_FF_diag_data[As_FF_diag_i[i]] = value*theta;
if (theta) theta = 1.0/theta;
for (j = As_FF_diag_i[i]+1; j < As_FF_diag_i[i+1]; j++)
{
As_FF_diag_data[j] *= value;
}
for (j = As_FF_offd_i[i]; j < As_FF_offd_i[i+1]; j++)
{
As_FF_offd_data[j] *= value;
}
for (j = As_FC_diag_i[i]; j < As_FC_diag_i[i+1]; j++)
{
As_FC_diag_data[j] *= theta;
}
for (j = As_FC_offd_i[i]; j < As_FC_offd_i[i+1]; j++)
{
As_FC_offd_data[j] *= theta;
}
}
} /* end parallel region */
W = hypre_ParMatmul(As_FF, As_FC);
W_diag = hypre_ParCSRMatrixDiag(W);
W_offd = hypre_ParCSRMatrixOffd(W);
W_diag_i = hypre_CSRMatrixI(W_diag);
W_diag_j = hypre_CSRMatrixJ(W_diag);
W_diag_data = hypre_CSRMatrixData(W_diag);
W_offd_i = hypre_CSRMatrixI(W_offd);
W_offd_j = hypre_CSRMatrixJ(W_offd);
W_offd_data = hypre_CSRMatrixData(W_offd);
num_cols_P_offd = hypre_CSRMatrixNumCols(W_offd);
/*-----------------------------------------------------------------------
* Intialize data for P
*-----------------------------------------------------------------------*/
P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine+1, memory_location_P);
P_diag_size = n_Cpts + hypre_CSRMatrixI(W_diag)[n_Fpts];
P_offd_size = hypre_CSRMatrixI(W_offd)[n_Fpts];
if (P_diag_size)
{
P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, memory_location_P);
P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, memory_location_P);
}
if (P_offd_size)
{
P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, memory_location_P);
P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, memory_location_P);
}
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel private(i,j,start,stop,startf,stopf,c_pt,row,cnt_diag,cnt_offd)
#endif
{
HYPRE_Int my_thread_num = hypre_GetThreadNum();
startf = startf_array[my_thread_num];
stopf = startf_array[my_thread_num+1];
start = start_array[my_thread_num];
stop = start_array[my_thread_num+1];
if (my_thread_num > 0)
c_pt = cpt_array[my_thread_num-1];
else
c_pt = 0;
cnt_diag = W_diag_i[startf]+c_pt;
cnt_offd = W_offd_i[startf];
row = startf;
for (i=start; i < stop; i++)
{
if (CF_marker[i] > 0)
{
P_diag_j[cnt_diag] = c_pt++;
P_diag_data[cnt_diag++] = 1.0;
}
else
{
for (j=W_diag_i[row]; j < W_diag_i[row+1]; j++)
{
P_diag_j[cnt_diag] = W_diag_j[j];
P_diag_data[cnt_diag++] = W_diag_data[j];
}
for (j=W_offd_i[row]; j < W_offd_i[row+1]; j++)
{
P_offd_j[cnt_offd] = W_offd_j[j];
P_offd_data[cnt_offd++] = W_offd_data[j];
}
row++;
}
P_diag_i[i+1] = cnt_diag;
P_offd_i[i+1] = cnt_offd;
}
} /* end parallel region */
/*-----------------------------------------------------------------------
* Create matrix
*-----------------------------------------------------------------------*/
P = hypre_ParCSRMatrixCreate(comm,
hypre_ParCSRMatrixGlobalNumRows(A),
total_global_cpts,
hypre_ParCSRMatrixColStarts(A),
num_cpts_global,
num_cols_P_offd,
P_diag_i[n_fine],
P_offd_i[n_fine]);
P_diag = hypre_ParCSRMatrixDiag(P);
hypre_CSRMatrixData(P_diag) = P_diag_data;
hypre_CSRMatrixI(P_diag) = P_diag_i;
hypre_CSRMatrixJ(P_diag) = P_diag_j;
P_offd = hypre_ParCSRMatrixOffd(P);
hypre_CSRMatrixData(P_offd) = P_offd_data;
hypre_CSRMatrixI(P_offd) = P_offd_i;
hypre_CSRMatrixJ(P_offd) = P_offd_j;
hypre_ParCSRMatrixColMapOffd(P) = hypre_ParCSRMatrixColMapOffd(W);
hypre_ParCSRMatrixColMapOffd(W) = NULL;
hypre_CSRMatrixMemoryLocation(P_diag) = memory_location_P;
hypre_CSRMatrixMemoryLocation(P_offd) = memory_location_P;
/* Compress P, removing coefficients smaller than trunc_factor * Max */
if (trunc_factor != 0.0 || max_elmts > 0)
{
HYPRE_Int *map;
hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts);
P_diag_data = hypre_CSRMatrixData(P_diag);
P_diag_i = hypre_CSRMatrixI(P_diag);
P_diag_j = hypre_CSRMatrixJ(P_diag);
P_offd_data = hypre_CSRMatrixData(P_offd);
P_offd_i = hypre_CSRMatrixI(P_offd);
P_offd_j = hypre_CSRMatrixJ(P_offd);
P_diag_size = P_diag_i[n_fine];
P_offd_size = P_offd_i[n_fine];
col_map_offd_P = hypre_ParCSRMatrixColMapOffd(P);
if (num_cols_P_offd)
{
P_marker = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST);
for (i=0; i < P_offd_size; i++)
P_marker[P_offd_j[i]] = 1;
new_ncols_P_offd = 0;
for (i=0; i < num_cols_P_offd; i++)
if (P_marker[i]) new_ncols_P_offd++;
new_col_map_offd = hypre_CTAlloc(HYPRE_BigInt, new_ncols_P_offd, HYPRE_MEMORY_HOST);
map = hypre_CTAlloc(HYPRE_Int, new_ncols_P_offd, HYPRE_MEMORY_HOST);
index = 0;
for (i=0; i < num_cols_P_offd; i++)
if (P_marker[i])
{
new_col_map_offd[index] = col_map_offd_P[i];
map[index++] = i;
}
hypre_TFree(P_marker, HYPRE_MEMORY_HOST);
#ifdef HYPRE_USING_OPENMP
#pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE
#endif
for (i=0; i < P_offd_size; i++)
{
P_offd_j[i] = hypre_BinarySearch(map, P_offd_j[i],
new_ncols_P_offd);
}
hypre_TFree(col_map_offd_P, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixColMapOffd(P) = new_col_map_offd;
hypre_CSRMatrixNumCols(P_offd) = new_ncols_P_offd;
hypre_TFree(map, HYPRE_MEMORY_HOST);
}
}
hypre_MatvecCommPkgCreate(P);
*P_ptr = P;
/* Deallocate memory */
hypre_TFree(D_tmp, HYPRE_MEMORY_HOST);
hypre_TFree(D_tmp_offd, HYPRE_MEMORY_HOST);
hypre_TFree(D_w, HYPRE_MEMORY_HOST);
hypre_TFree(D_tau, HYPRE_MEMORY_HOST);
hypre_TFree(D_beta, HYPRE_MEMORY_HOST);
hypre_TFree(D_lambda, HYPRE_MEMORY_HOST);
hypre_TFree(cpt_array, HYPRE_MEMORY_HOST);
hypre_TFree(start_array, HYPRE_MEMORY_HOST);
hypre_TFree(startf_array, HYPRE_MEMORY_HOST);
hypre_TFree(buf_data, HYPRE_MEMORY_HOST);
hypre_ParCSRMatrixDestroy(As_FF);
hypre_ParCSRMatrixDestroy(As_FC);
hypre_ParCSRMatrixDestroy(W);
return hypre_error_flag;
}
/*-----------------------------------------------------------------------*
* Modularized Extended+e Interpolation
*-----------------------------------------------------------------------*/
HYPRE_Int
hypre_BoomerAMGBuildModExtPEInterp(hypre_ParCSRMatrix *A,
HYPRE_Int *CF_marker,
hypre_ParCSRMatrix *S,
HYPRE_BigInt *num_cpts_global,
HYPRE_Int num_functions,
HYPRE_Int *dof_func,
HYPRE_Int debug_flag,
HYPRE_Real trunc_factor,
HYPRE_Int max_elmts,
hypre_ParCSRMatrix **P_ptr)
{
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPushRange("ModExtPEInterp");
#endif
HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_ParCSRMatrixMemoryLocation(A) );
HYPRE_Int ierr = 0;
if (exec == HYPRE_EXEC_HOST)
{
ierr = hypre_BoomerAMGBuildModExtPEInterpHost(A, CF_marker, S, num_cpts_global,
num_functions, dof_func,
debug_flag, trunc_factor, max_elmts, P_ptr);
}
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
else
{
ierr = hypre_BoomerAMGBuildExtPEInterpDevice(A,CF_marker,S,num_cpts_global,1,NULL,
debug_flag,trunc_factor,max_elmts,P_ptr);
}
#endif
#if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP)
hypre_GpuProfilingPopRange();
#endif
return ierr;
}
|
9971.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4096x4096. */
#include "convolution-2d.h"
/* Array initialization. */
static
void init_array (int ni, int nj,
DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj))
{
// printf("Initializing Array\n");
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nj; j++)
{
A[i][j] = ((DATA_TYPE) (i + j) / nj);
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int ni, int nj,
DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj))
{
int i, j;
for (i = 0; i < ni; i++)
for (j = 0; j < nj; j++) {
fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]);
if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n");
}
fprintf(stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_conv2d(int ni,
int nj,
DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj),
DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj))
{
int i, j;
#pragma scop
#pragma omp parallel for schedule(static, 1) simd
for (i = 1; i < _PB_NI - 1; ++i)
{
#pragma omp target teams distribute thread_limit(128) schedule(static, 1)
for (j = 1; j < _PB_NJ - 1; ++j)
{
B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1]
+ -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1]
+ 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1];
}
}
#pragma endscop
// printf("Kernal computation complete !!\n");
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int ni = NI;
int nj = NJ;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj);
POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj);
/* Initialize array(s). */
init_array (ni, nj, POLYBENCH_ARRAY(A));
/* Start timer. */
//polybench_start_instruments;
polybench_timer_start();
/* Run kernel. */
kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B));
/* Stop and print timer. */
polybench_timer_stop();
polybench_timer_print();
//polybench_stop_instruments;
//polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(B);
return 0;
}
|
core_ztradd.c | /**
*
* @file
*
* PLASMA is a software package provided by:
* University of Tennessee, US,
* University of Manchester, UK.
*
* @precisions normal z -> c d s
*
**/
#include "core_blas.h"
#include "plasma_internal.h"
#include "plasma_types.h"
#include "core_lapack.h"
/***************************************************************************//**
*
* @ingroup core_tradd
*
* Performs an addition of two trapezoidal matrices similarly to the
* 'pztradd()' function from the PBLAS library:
*
* \f[ B = \alpha * op( A ) + \beta * B, \f]
*
* where op( X ) is one of:
* \f[ op( X ) = X, \f]
* \f[ op( X ) = X^T, \f]
* \f[ op( X ) = X^H, \f]
*
* alpha and beta are scalars and A, B are matrices with op( A ) an m-by-n or
* n-by-m matrix depending on the value of transa and B an m-by-n matrix.
*
*******************************************************************************
*
* @param[in] uplo
* Specifies the shape of A and B matrices:
* - PlasmaUpper: op( A ) and B are upper trapezoidal matrices.
* - PlasmaLower: op( A ) and B are lower trapezoidal matrices.
*
* @param[in] transa
* Specifies whether the matrix A is non-transposed, transposed, or
* conjugate transposed
* - PlasmaNoTrans: op( A ) = A
* - PlasmaTrans: op( A ) = A^T
* - PlasmaConjTrans: op( A ) = A^H
*
* @param[in] m
* Number of rows of the matrices op( A ) and B.
* m >= 0.
*
* @param[in] n
* Number of columns of the matrices op( A ) and B.
* n >= 0.
*
* @param[in] alpha
* Scalar factor of A.
*
* @param[in] A
* Matrix of size lda-by-k, where k is n when transa == PlasmaNoTrans
* and m otherwise.
*
* @param[in] lda
* Leading dimension of the array A. lda >= max(1,l), where l is m
* when transa = PlasmaNoTrans and n otherwise.
*
* @param[in] beta
* Scalar factor of B.
*
* @param[in,out] B
* Matrix of size ldb-by-n.
* On exit, B = alpha * op( A ) + beta * B
*
* @param[in] ldb
* Leading dimension of the array B.
* ldb >= max(1,m).
*
******************************************************************************/
int core_ztradd(plasma_enum_t uplo, plasma_enum_t transa,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t beta, plasma_complex64_t *B, int ldb)
{
// Check input arguments
if ((uplo != PlasmaUpper) &&
(uplo != PlasmaLower)) {
coreblas_error("illegal value of uplo");
return -1;
}
if ((transa != PlasmaNoTrans) &&
(transa != PlasmaTrans) &&
(transa != PlasmaConjTrans)) {
coreblas_error("illegal value of transa");
return -2;
}
if (m < 0) {
coreblas_error("illegal value of m");
return -3;
}
if (n < 0) {
coreblas_error("illegal value of n");
return -4;
}
if (A == NULL) {
coreblas_error("NULL A");
return -6;
}
if ((transa == PlasmaNoTrans && lda < imax(1, m) && m > 0) ||
(transa != PlasmaNoTrans && lda < imax(1, n) && n > 0)) {
coreblas_error("illegal value of lda");
return -7;
}
if (B == NULL) {
coreblas_error("NULL B");
return -9;
}
if (ldb < imax(1, m) && (m > 0)) {
coreblas_error("illegal value of ldb");
return -10;
}
// quick return
if (m == 0 || n == 0 || (alpha == 0.0 && beta == 1.0))
return PlasmaSuccess;
//==============
// PlasmaLower
//==============
if (uplo == PlasmaLower) {
switch (transa) {
case PlasmaConjTrans:
for (int j = 0; j < n; j++)
for (int i = j; i < m; i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * conj(A[lda*i+j]);
break;
case PlasmaTrans:
for (int j = 0; j < n; j++)
for (int i = j; i < m; i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * A[lda*i+j];
break;
case PlasmaNoTrans:
default:
for (int j = 0; j < n; j++)
for (int i = j; i < m; i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * A[lda*j+i];
}
}
//==============
// PlasmaUpper
//==============
else {
switch (transa) {
case PlasmaConjTrans:
for (int j = 0; j < n; j++)
for (int i = 0; i < imin(j+1, m); i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * conj(A[lda*i+j]);
break;
case PlasmaTrans:
for (int j = 0; j < n; j++)
for (int i = 0; i < imin(j+1, m); i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * A[lda*i+j];
break;
case PlasmaNoTrans:
default:
for (int j = 0; j < n; j++)
for (int i = 0; i < imin(j+1, m); i++)
B[ldb*j+i] = beta * B[ldb*j+i] + alpha * A[lda*j+i];
}
}
return PlasmaSuccess;
}
/******************************************************************************/
void core_omp_ztradd(
plasma_enum_t uplo, plasma_enum_t transa,
int m, int n,
plasma_complex64_t alpha, const plasma_complex64_t *A, int lda,
plasma_complex64_t beta, plasma_complex64_t *B, int ldb,
plasma_sequence_t *sequence, plasma_request_t *request)
{
int k = (transa == PlasmaNoTrans) ? n : m;
#pragma omp task depend(in:A[0:lda*k]) \
depend(inout:B[0:ldb*n])
{
if (sequence->status == PlasmaSuccess) {
int retval = core_ztradd(uplo, transa,
m, n,
alpha, A, lda,
beta, B, ldb);
if (retval != PlasmaSuccess) {
plasma_error("core_ztradd() failed");
plasma_request_fail(sequence, request, PlasmaErrorInternal);
}
}
}
}
|
GB_binop__plus_uint32.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__plus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_01__plus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_02__plus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_03__plus_uint32)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_uint32)
// A*D function (colscale): GB (_AxD__plus_uint32)
// D*A function (rowscale): GB (_DxB__plus_uint32)
// C+=B function (dense accum): GB (_Cdense_accumB__plus_uint32)
// C+=b function (dense accum): GB (_Cdense_accumb__plus_uint32)
// C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_uint32)
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_uint32)
// C=scalar+B GB (_bind1st__plus_uint32)
// C=scalar+B' GB (_bind1st_tran__plus_uint32)
// C=A+scalar GB (_bind2nd__plus_uint32)
// C=A'+scalar GB (_bind2nd_tran__plus_uint32)
// C type: uint32_t
// A type: uint32_t
// B,b type: uint32_t
// BinaryOp: cij = (aij + bij)
#define GB_ATYPE \
uint32_t
#define GB_BTYPE \
uint32_t
#define GB_CTYPE \
uint32_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
uint32_t aij = GBX (Ax, pA, A_iso)
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
uint32_t bij = GBX (Bx, pB, B_iso)
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
uint32_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = (x + y) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_PLUS || GxB_NO_UINT32 || GxB_NO_PLUS_UINT32)
//------------------------------------------------------------------------------
// C += A+B, all 3 matrices dense
//------------------------------------------------------------------------------
// The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV.
void GB (_Cdense_ewise3_accum__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_accum_template.c"
}
//------------------------------------------------------------------------------
// C = A+B, all 3 matrices dense
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__plus_uint32)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type uint32_t
uint32_t bwork = (*((uint32_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_AxD__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A, bool A_is_pattern,
const GrB_Matrix D, bool D_is_pattern,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *restrict Cx = (uint32_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__plus_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
#include "GB_add_template.c"
GB_FREE_WORK ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C = A.*B or C<M> = A.*B
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_01__plus_uint32)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_01_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_03__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_03_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__plus_uint32)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__plus_uint32)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t x = (*((uint32_t *) x_input)) ;
uint32_t *Bx = (uint32_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
uint32_t bij = GBX (Bx, p, false) ;
Cx [p] = (x + bij) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__plus_uint32)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
uint32_t *Cx = (uint32_t *) Cx_output ;
uint32_t *Ax = (uint32_t *) Ax_input ;
uint32_t y = (*((uint32_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
uint32_t aij = GBX (Ax, p, false) ;
Cx [p] = (aij + y) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (x + aij) ; \
}
GrB_Info GB (_bind1st_tran__plus_uint32)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t x = (*((const uint32_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
uint32_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
uint32_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = (aij + y) ; \
}
GrB_Info GB (_bind2nd_tran__plus_uint32)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
uint32_t y = (*((const uint32_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
GB_unop__isfinite_bool_fc32.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__isfinite_bool_fc32)
// op(A') function: GB (_unop_tran__isfinite_bool_fc32)
// C type: bool
// A type: GxB_FC32_t
// cast: GxB_FC32_t cij = (aij)
// unaryop: cij = GB_cisfinitef (aij)
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
bool
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_cisfinitef (x) ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = (aij) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = (aij) ; \
Cx [pC] = GB_cisfinitef (z) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_ISFINITE || GxB_NO_BOOL || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__isfinite_bool_fc32)
(
bool *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = (aij) ;
Cx [p] = GB_cisfinitef (z) ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
GxB_FC32_t z = (aij) ;
Cx [p] = GB_cisfinitef (z) ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__isfinite_bool_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
pixel.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP IIIII X X EEEEE L %
% P P I X X E L %
% PPPP I X EEE L %
% P I X X E L %
% P IIIII X X EEEEE LLLLL %
% %
% MagickCore Methods to Import/Export Pixels %
% %
% Software Design %
% Cristy %
% October 1998 %
% %
% %
% Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/property.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/draw.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/constitute.h"
#include "MagickCore/delegate.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/semaphore.h"
#include "MagickCore/statistic.h"
#include "MagickCore/stream.h"
#include "MagickCore/string_.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ A c q u i r e P i x e l C h a n n e l M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquirePixelChannelMap() acquires a pixel component map.
%
% The format of the AcquirePixelChannelMap() method is:
%
% PixelChannelMap *AcquirePixelChannelMap(void)
%
*/
MagickExport PixelChannelMap *AcquirePixelChannelMap(void)
{
PixelChannelMap
*channel_map;
ssize_t
i;
channel_map=(PixelChannelMap *) AcquireQuantumMemory(MaxPixelChannels,
sizeof(*channel_map));
if (channel_map == (PixelChannelMap *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
(void) memset(channel_map,0,MaxPixelChannels*sizeof(*channel_map));
for (i=0; i < MaxPixelChannels; i++)
channel_map[i].channel=(PixelChannel) i;
return(channel_map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l C h a n n e l M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelChannelMap() clones a pixel component map.
%
% The format of the ClonePixelChannelMap() method is:
%
% PixelChannelMap *ClonePixelChannelMap(PixelChannelMap *channel_map)
%
% A description of each parameter follows:
%
% o channel_map: the pixel component map.
%
*/
MagickExport PixelChannelMap *ClonePixelChannelMap(PixelChannelMap *channel_map)
{
PixelChannelMap
*clone_map;
assert(channel_map != (PixelChannelMap *) NULL);
clone_map=AcquirePixelChannelMap();
if (clone_map == (PixelChannelMap *) NULL)
return((PixelChannelMap *) NULL);
(void) memcpy(clone_map,channel_map,MaxPixelChannels*
sizeof(*channel_map));
return(clone_map);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C l o n e P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ClonePixelInfo() makes a duplicate of the given pixel info structure, or if
% pixel info is NULL, a new one.
%
% The format of the ClonePixelInfo method is:
%
% PixelInfo *ClonePixelInfo(const PixelInfo *pixel)
%
% A description of each parameter follows:
%
% o pixel: the pixel info.
%
*/
MagickExport PixelInfo *ClonePixelInfo(const PixelInfo *pixel)
{
PixelInfo
*pixel_info;
pixel_info=(PixelInfo *) AcquireMagickMemory(sizeof(*pixel_info));
if (pixel_info == (PixelInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
*pixel_info=(*pixel);
return(pixel_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n f o r m P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConformPixelInfo() ensures the pixel conforms with the colorspace and alpha
% attribute of the image.
%
% The format of the ConformPixelInfo method is:
%
% void *ConformPixelInfo((Image *image,const PixelInfo *source,
% PixelInfo *destination,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source pixel info.
%
% o destination: the destination pixel info.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport void ConformPixelInfo(Image *image,const PixelInfo *source,
PixelInfo *destination,ExceptionInfo *exception)
{
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(destination != (const PixelInfo *) NULL);
*destination=(*source);
if (image->colorspace == CMYKColorspace)
{
if (IssRGBCompatibleColorspace(destination->colorspace) != MagickFalse)
ConvertRGBToCMYK(destination);
}
else
if (destination->colorspace == CMYKColorspace)
{
if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse)
ConvertCMYKToRGB(destination);
}
if ((IsPixelInfoGray(&image->background_color) == MagickFalse) &&
(IsGrayColorspace(image->colorspace) != MagickFalse))
(void) TransformImageColorspace(image,sRGBColorspace,exception);
if ((destination->alpha_trait != UndefinedPixelTrait) &&
(image->alpha_trait == UndefinedPixelTrait))
(void) SetImageAlpha(image,OpaqueAlpha,exception);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e c o d e P i x e l G a m m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DecodePixelGamma() applies the expansive power-law nonlinearity to the pixel.
%
% The format of the DecodePixelGamma method is:
%
% double DecodePixelGamma(const MagickRealType pixel)
%
% A description of each parameter follows:
%
% o pixel: the pixel.
%
*/
static inline double DecodeGamma(const double x)
{
div_t
quotient;
double
p,
term[9];
int
exponent;
static const double coefficient[] = /* terms for x^(7/5), x=1.5 */
{
1.7917488588043277509,
0.82045614371976854984,
0.027694100686325412819,
-0.00094244335181762134018,
0.000064355540911469709545,
-5.7224404636060757485e-06,
5.8767669437311184313e-07,
-6.6139920053589721168e-08,
7.9323242696227458163e-09
};
static const double powers_of_two[] = /* (2^x)^(7/5) */
{
1.0,
2.6390158215457883983,
6.9644045063689921093,
1.8379173679952558018e+01,
4.8502930128332728543e+01
};
/*
Compute x^2.4 == x*x^(7/5) == pow(x,2.4).
*/
term[0]=1.0;
term[1]=4.0*frexp(x,&exponent)-3.0;
term[2]=2.0*term[1]*term[1]-term[0];
term[3]=2.0*term[1]*term[2]-term[1];
term[4]=2.0*term[1]*term[3]-term[2];
term[5]=2.0*term[1]*term[4]-term[3];
term[6]=2.0*term[1]*term[5]-term[4];
term[7]=2.0*term[1]*term[6]-term[5];
term[8]=2.0*term[1]*term[7]-term[6];
p=coefficient[0]*term[0]+coefficient[1]*term[1]+coefficient[2]*term[2]+
coefficient[3]*term[3]+coefficient[4]*term[4]+coefficient[5]*term[5]+
coefficient[6]*term[6]+coefficient[7]*term[7]+coefficient[8]*term[8];
quotient=div(exponent-1,5);
if (quotient.rem < 0)
{
quotient.quot-=1;
quotient.rem+=5;
}
return(x*ldexp(powers_of_two[quotient.rem]*p,7*quotient.quot));
}
MagickExport MagickRealType DecodePixelGamma(const MagickRealType pixel)
{
if (pixel <= (0.0404482362771076*QuantumRange))
return(pixel/12.92f);
return((MagickRealType) (QuantumRange*DecodeGamma((double) (QuantumScale*
pixel+0.055)/1.055)));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P i x e l C h a n n e l M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPixelChannelMap() deallocates memory associated with the pixel
% channel map.
%
% The format of the DestroyPixelChannelMap() method is:
%
% PixelChannelMap *DestroyPixelChannelMap(PixelChannelMap *channel_map)
%
% A description of each parameter follows:
%
% o channel_map: the pixel component map.
%
*/
MagickExport PixelChannelMap *DestroyPixelChannelMap(
PixelChannelMap *channel_map)
{
assert(channel_map != (PixelChannelMap *) NULL);
channel_map=(PixelChannelMap *) RelinquishMagickMemory(channel_map);
return((PixelChannelMap *) RelinquishMagickMemory(channel_map));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ E n c o d e P i x e l G a m m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% EncodePixelGamma() cancels any nonlinearity in the pixel.
%
% The format of the EncodePixelGamma method is:
%
% MagickRealType EncodePixelGamma(const double MagickRealType)
%
% A description of each parameter follows:
%
% o pixel: the pixel.
%
*/
static inline double EncodeGamma(const double x)
{
div_t
quotient;
double
p,
term[9];
int
exponent;
static const double coefficient[] = /* Chebychevi poly: x^(5/12), x=1.5 */
{
1.1758200232996901923,
0.16665763094889061230,
-0.0083154894939042125035,
0.00075187976780420279038,
-0.000083240178519391795367,
0.000010229209410070008679,
-1.3400466409860246e-06,
1.8333422241635376682e-07,
-2.5878596761348859722e-08
};
static const double powers_of_two[] = /* (2^N)^(5/12) */
{
1.0,
1.3348398541700343678,
1.7817974362806785482,
2.3784142300054420538,
3.1748021039363991669,
4.2378523774371812394,
5.6568542494923805819,
7.5509945014535482244,
1.0079368399158985525e1,
1.3454342644059433809e1,
1.7959392772949968275e1,
2.3972913230026907883e1
};
/*
Compute x^(1/2.4) == x^(5/12) == pow(x,1.0/2.4).
*/
term[0]=1.0;
term[1]=4.0*frexp(x,&exponent)-3.0;
term[2]=2.0*term[1]*term[1]-term[0];
term[3]=2.0*term[1]*term[2]-term[1];
term[4]=2.0*term[1]*term[3]-term[2];
term[5]=2.0*term[1]*term[4]-term[3];
term[6]=2.0*term[1]*term[5]-term[4];
term[7]=2.0*term[1]*term[6]-term[5];
term[8]=2.0*term[1]*term[7]-term[6];
p=coefficient[0]*term[0]+coefficient[1]*term[1]+coefficient[2]*term[2]+
coefficient[3]*term[3]+coefficient[4]*term[4]+coefficient[5]*term[5]+
coefficient[6]*term[6]+coefficient[7]*term[7]+coefficient[8]*term[8];
quotient=div(exponent-1,12);
if (quotient.rem < 0)
{
quotient.quot-=1;
quotient.rem+=12;
}
return(ldexp(powers_of_two[quotient.rem]*p,5*quotient.quot));
}
MagickExport MagickRealType EncodePixelGamma(const MagickRealType pixel)
{
if (pixel <= (0.0031306684425005883*QuantumRange))
return(12.92f*pixel);
return((MagickRealType) QuantumRange*(1.055*EncodeGamma((double) QuantumScale*
pixel)-0.055));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% E x p o r t I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ExportImagePixels() extracts pixel data from an image and returns it to you.
% The method returns MagickTrue on success otherwise MagickFalse if an error is
% encountered. The data is returned as char, short int, Quantum, unsigned int,
% unsigned long long, float, or double in the order specified by map.
%
% Suppose you want to extract the first scanline of a 640x480 image as
% character data in red-green-blue order:
%
% ExportImagePixels(image,0,0,640,1,"RGB",CharPixel,pixels,exception);
%
% The format of the ExportImagePixels method is:
%
% MagickBooleanType ExportImagePixels(const Image *image,const ssize_t x,
% const ssize_t y,const size_t width,const size_t height,
% const char *map,const StorageType type,void *pixels,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,width,height: These values define the perimeter
% of a region of pixels you want to extract.
%
% o map: This string reflects the expected ordering of the pixel array.
% It can be any combination or order of R = red, G = green, B = blue,
% A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan,
% Y = yellow, M = magenta, K = black, I = intensity (for grayscale),
% P = pad.
%
% o type: Define the data type of the pixels. Float and double types are
% normalized to [0..1] otherwise [0..QuantumRange]. Choose from these
% types: CharPixel (char *), DoublePixel (double *), FloatPixel (float *),
% LongPixel (unsigned int *), LongLongPixel (unsigned long long *),
% QuantumPixel (Quantum *), or ShortPixel (unsigned short *).
%
% o pixels: This array of values contain the pixel components as defined by
% map and type. You must preallocate this array where the expected
% length varies depending on the values of width, height, map, and type.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ExportCharPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
ssize_t
x;
unsigned char
*magick_restrict q;
size_t
length;
ssize_t
y;
q=(unsigned char *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar((Quantum) 0);
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(image,p)));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToChar(GetPixelRed(image,p));
*q++=ScaleQuantumToChar(GetPixelGreen(image,p));
*q++=ScaleQuantumToChar(GetPixelBlue(image,p));
*q++=ScaleQuantumToChar((Quantum) 0);
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=ScaleQuantumToChar(GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=ScaleQuantumToChar(GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=ScaleQuantumToChar(GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=ScaleQuantumToChar(GetPixelAlpha(image,p));
break;
}
case OpacityQuantum:
{
*q=ScaleQuantumToChar(GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=ScaleQuantumToChar(GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(image,p)));
break;
}
default:
break;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportDoublePixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
double
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
q=(double *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelRed(image,p));
*q++=(double) (QuantumScale*GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelRed(image,p));
*q++=0.0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelIntensity(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelRed(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelRed(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
*q++=(double) (QuantumScale*GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(double) (QuantumScale*GetPixelRed(image,p));
*q++=(double) (QuantumScale*GetPixelGreen(image,p));
*q++=(double) (QuantumScale*GetPixelBlue(image,p));
*q++=0.0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=(double) (QuantumScale*GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=(double) (QuantumScale*GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=(double) (QuantumScale*GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=(double) (QuantumScale*GetPixelAlpha(image,p));
break;
}
case OpacityQuantum:
{
*q=(double) (QuantumScale*GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=(double) (QuantumScale*
GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=(double) (QuantumScale*GetPixelIntensity(image,p));
break;
}
default:
*q=0;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportFloatPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
float
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
q=(float *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelRed(image,p));
*q++=(float) (QuantumScale*GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelRed(image,p));
*q++=0.0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelIntensity(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelRed(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelRed(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
*q++=(float) (QuantumScale*GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=(float) (QuantumScale*GetPixelRed(image,p));
*q++=(float) (QuantumScale*GetPixelGreen(image,p));
*q++=(float) (QuantumScale*GetPixelBlue(image,p));
*q++=0.0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=(float) (QuantumScale*GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=(float) (QuantumScale*GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=(float) (QuantumScale*GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=(float) (QuantumScale*((Quantum) (GetPixelAlpha(image,p))));
break;
}
case OpacityQuantum:
{
*q=(float) (QuantumScale*GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=(float) (QuantumScale* GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=(float) (QuantumScale*GetPixelIntensity(image,p));
break;
}
default:
*q=0;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportLongPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
ssize_t
x;
unsigned int
*magick_restrict q;
size_t
length;
ssize_t
y;
q=(unsigned int *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLong(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(ClampToQuantum(GetPixelIntensity(image,p)));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLong(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLong(GetPixelBlue(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=ScaleQuantumToLong(GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=ScaleQuantumToLong(GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=ScaleQuantumToLong(GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=ScaleQuantumToLong(GetPixelAlpha(image,p));
break;
}
case OpacityQuantum:
{
*q=ScaleQuantumToLong(GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=ScaleQuantumToLong(GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=ScaleQuantumToLong(ClampToQuantum(GetPixelIntensity(image,p)));
break;
}
default:
break;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportLongLongPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
ssize_t
x;
MagickSizeType
*magick_restrict q;
size_t
length;
ssize_t
y;
q=(MagickSizeType *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLongLong(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(ClampToQuantum(
GetPixelIntensity(image,p)));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
*q++=ScaleQuantumToLongLong(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToLongLong(GetPixelRed(image,p));
*q++=ScaleQuantumToLongLong(GetPixelGreen(image,p));
*q++=ScaleQuantumToLongLong(GetPixelBlue(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=ScaleQuantumToLongLong(GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=ScaleQuantumToLongLong(GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=ScaleQuantumToLongLong(GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=ScaleQuantumToLongLong(GetPixelAlpha(image,p));
break;
}
case OpacityQuantum:
{
*q=ScaleQuantumToLongLong(GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=ScaleQuantumToLongLong(GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=ScaleQuantumToLongLong(ClampToQuantum(
GetPixelIntensity(image,p)));
break;
}
default:
break;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportQuantumPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
q=(Quantum *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelBlue(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelRed(image,p);
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelBlue(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelRed(image,p);
*q++=(Quantum) (GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelBlue(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelRed(image,p);
*q++=(Quantum) 0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ClampToQuantum(GetPixelIntensity(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelRed(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelBlue(image,p);
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelRed(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelBlue(image,p);
*q++=(Quantum) (GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=GetPixelRed(image,p);
*q++=GetPixelGreen(image,p);
*q++=GetPixelBlue(image,p);
*q++=(Quantum) 0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=(Quantum) 0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=GetPixelRed(image,p);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=GetPixelGreen(image,p);
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=GetPixelBlue(image,p);
break;
}
case AlphaQuantum:
{
*q=GetPixelAlpha(image,p);
break;
}
case OpacityQuantum:
{
*q=GetPixelAlpha(image,p);
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=GetPixelBlack(image,p);
break;
}
case IndexQuantum:
{
*q=ClampToQuantum(GetPixelIntensity(image,p));
break;
}
default:
{
*q=(Quantum) 0;
break;
}
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ExportShortPixel(const Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
ssize_t
x;
unsigned short
*magick_restrict q;
size_t
length;
ssize_t
y;
q=(unsigned short *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(ClampToQuantum(GetPixelIntensity(image,p)));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=ScaleQuantumToShort(GetPixelAlpha(image,p));
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
*q++=ScaleQuantumToShort(GetPixelRed(image,p));
*q++=ScaleQuantumToShort(GetPixelGreen(image,p));
*q++=ScaleQuantumToShort(GetPixelBlue(image,p));
*q++=0;
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (p == (const Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
*q=0;
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
*q=ScaleQuantumToShort(GetPixelRed(image,p));
break;
}
case GreenQuantum:
case MagentaQuantum:
{
*q=ScaleQuantumToShort(GetPixelGreen(image,p));
break;
}
case BlueQuantum:
case YellowQuantum:
{
*q=ScaleQuantumToShort(GetPixelBlue(image,p));
break;
}
case AlphaQuantum:
{
*q=ScaleQuantumToShort(GetPixelAlpha(image,p));
break;
}
case OpacityQuantum:
{
*q=ScaleQuantumToShort(GetPixelAlpha(image,p));
break;
}
case BlackQuantum:
{
if (image->colorspace == CMYKColorspace)
*q=ScaleQuantumToShort(GetPixelBlack(image,p));
break;
}
case IndexQuantum:
{
*q=ScaleQuantumToShort(ClampToQuantum(GetPixelIntensity(image,p)));
break;
}
default:
break;
}
q++;
}
p+=GetPixelChannels(image);
}
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
MagickExport MagickBooleanType ExportImagePixels(const Image *image,
const ssize_t x,const ssize_t y,const size_t width,const size_t height,
const char *map,const StorageType type,void *pixels,ExceptionInfo *exception)
{
MagickBooleanType
status;
QuantumType
*quantum_map;
RectangleInfo
roi;
ssize_t
i;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=strlen(map);
quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map));
if (quantum_map == (QuantumType *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename);
return(MagickFalse);
}
for (i=0; i < (ssize_t) length; i++)
{
switch (map[i])
{
case 'A':
case 'a':
{
quantum_map[i]=AlphaQuantum;
break;
}
case 'B':
case 'b':
{
quantum_map[i]=BlueQuantum;
break;
}
case 'C':
case 'c':
{
quantum_map[i]=CyanQuantum;
if (image->colorspace == CMYKColorspace)
break;
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",map);
return(MagickFalse);
}
case 'g':
case 'G':
{
quantum_map[i]=GreenQuantum;
break;
}
case 'I':
case 'i':
{
quantum_map[i]=IndexQuantum;
break;
}
case 'K':
case 'k':
{
quantum_map[i]=BlackQuantum;
if (image->colorspace == CMYKColorspace)
break;
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",map);
return(MagickFalse);
}
case 'M':
case 'm':
{
quantum_map[i]=MagentaQuantum;
if (image->colorspace == CMYKColorspace)
break;
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",map);
return(MagickFalse);
}
case 'o':
case 'O':
{
quantum_map[i]=OpacityQuantum;
break;
}
case 'P':
case 'p':
{
quantum_map[i]=UndefinedQuantum;
break;
}
case 'R':
case 'r':
{
quantum_map[i]=RedQuantum;
break;
}
case 'Y':
case 'y':
{
quantum_map[i]=YellowQuantum;
if (image->colorspace == CMYKColorspace)
break;
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),ImageError,
"ColorSeparatedImageRequired","`%s'",map);
return(MagickFalse);
}
default:
{
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedPixelMap","`%s'",map);
return(MagickFalse);
}
}
}
roi.width=width;
roi.height=height;
roi.x=x;
roi.y=y;
switch (type)
{
case CharPixel:
{
status=ExportCharPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case DoublePixel:
{
status=ExportDoublePixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case FloatPixel:
{
status=ExportFloatPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case LongPixel:
{
status=ExportLongPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case LongLongPixel:
{
status=ExportLongLongPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case QuantumPixel:
{
status=ExportQuantumPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case ShortPixel:
{
status=ExportShortPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
default:
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedPixelMap","`%s'",map);
status=MagickFalse;
}
}
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelInfo() initializes the PixelInfo structure.
%
% The format of the GetPixelInfo method is:
%
% GetPixelInfo(const Image *image,PixelInfo *pixel)
%
% A description of each parameter follows:
%
% o image: the image. (optional - may be NULL)
%
% o pixel: Specifies a pointer to a PixelInfo structure.
%
*/
MagickExport void GetPixelInfo(const Image *image,PixelInfo *pixel)
{
(void) memset(pixel,0,sizeof(*pixel));
pixel->storage_class=DirectClass;
pixel->colorspace=sRGBColorspace;
pixel->depth=MAGICKCORE_QUANTUM_DEPTH;
pixel->alpha_trait=UndefinedPixelTrait;
pixel->alpha=(double) OpaqueAlpha;
if (image == (const Image *) NULL)
return;
pixel->storage_class=image->storage_class;
pixel->colorspace=image->colorspace;
pixel->alpha_trait=image->alpha_trait;
pixel->depth=image->depth;
pixel->fuzz=image->fuzz;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t P i x e l I n d o I n t e n s i t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelInfoIntensity() returns a single sample intensity value from the red,
% green, and blue components of a pixel based on the selected method:
%
% Rec601Luma 0.298839R' + 0.586811G' + 0.114350B'
% Rec601Luminance 0.298839R + 0.586811G + 0.114350B
% Rec709Luma 0.212656R' + 0.715158G' + 0.072186B'
% Rec709Luminance 0.212656R + 0.715158G + 0.072186B
% Brightness max(R', G', B')
% Lightness (min(R', G', B') + max(R', G', B')) / 2.0
%
% MS (R^2 + G^2 + B^2) / 3.0
% RMS sqrt((R^2 + G^2 + B^2) / 3.0
% Average (R + G + B') / 3.0
%
% The format of the GetPixelInfoIntensity method is:
%
% MagickRealType GetPixelInfoIntensity(const Image *image,
% const Quantum *pixel)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pixel: Specifies a pointer to a Quantum structure.
%
*/
MagickExport MagickRealType GetPixelInfoIntensity(
const Image *magick_restrict image,const PixelInfo *magick_restrict pixel)
{
MagickRealType
blue,
green,
red,
intensity;
PixelIntensityMethod
method;
method=Rec709LumaPixelIntensityMethod;
if (image != (const Image *) NULL)
method=image->intensity;
red=pixel->red;
green=pixel->green;
blue=pixel->blue;
switch (method)
{
case AveragePixelIntensityMethod:
{
intensity=(red+green+blue)/3.0;
break;
}
case BrightnessPixelIntensityMethod:
{
intensity=MagickMax(MagickMax(red,green),blue);
break;
}
case LightnessPixelIntensityMethod:
{
intensity=(MagickMin(MagickMin(red,green),blue)+
MagickMax(MagickMax(red,green),blue))/2.0;
break;
}
case MSPixelIntensityMethod:
{
intensity=(MagickRealType) (((double) red*red+green*green+blue*blue)/
(3.0*QuantumRange));
break;
}
case Rec601LumaPixelIntensityMethod:
{
if (pixel->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec601LuminancePixelIntensityMethod:
{
if (pixel->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec709LumaPixelIntensityMethod:
default:
{
if (pixel->colorspace == RGBColorspace)
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case Rec709LuminancePixelIntensityMethod:
{
if (pixel->colorspace == sRGBColorspace)
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case RMSPixelIntensityMethod:
{
intensity=(MagickRealType) (sqrt((double) red*red+green*green+blue*blue)/
sqrt(3.0));
break;
}
}
return(intensity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t P i x e l I n t e n s i t y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetPixelIntensity() returns a single sample intensity value from the red,
% green, and blue components of a pixel based on the selected method:
%
% Rec601Luma 0.298839R' + 0.586811G' + 0.114350B'
% Rec601Luminance 0.298839R + 0.586811G + 0.114350B
% Rec709Luma 0.212656R' + 0.715158G' + 0.072186B'
% Rec709Luminance 0.212656R + 0.715158G + 0.072186B
% Brightness max(R', G', B')
% Lightness (min(R', G', B') + max(R', G', B')) / 2.0
%
% MS (R^2 + G^2 + B^2) / 3.0
% RMS sqrt((R^2 + G^2 + B^2) / 3.0
% Average (R + G + B') / 3.0
%
% The format of the GetPixelIntensity method is:
%
% MagickRealType GetPixelIntensity(const Image *image,
% const Quantum *pixel)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o pixel: Specifies a pointer to a Quantum structure.
%
*/
MagickExport MagickRealType GetPixelIntensity(
const Image *magick_restrict image,const Quantum *magick_restrict pixel)
{
MagickRealType
blue,
green,
red,
intensity;
red=(MagickRealType) GetPixelRed(image,pixel);
if (image->number_channels == 1)
return(red);
green=(MagickRealType) GetPixelGreen(image,pixel);
blue=(MagickRealType) GetPixelBlue(image,pixel);
switch (image->intensity)
{
case AveragePixelIntensityMethod:
{
intensity=(red+green+blue)/3.0;
break;
}
case BrightnessPixelIntensityMethod:
{
intensity=MagickMax(MagickMax(red,green),blue);
break;
}
case LightnessPixelIntensityMethod:
{
intensity=(MagickMin(MagickMin(red,green),blue)+
MagickMax(MagickMax(red,green),blue))/2.0;
break;
}
case MSPixelIntensityMethod:
{
intensity=(MagickRealType) (((double) red*red+green*green+blue*blue)/
(3.0*QuantumRange));
break;
}
case Rec601LumaPixelIntensityMethod:
{
if ((image->colorspace == RGBColorspace) ||
(image->colorspace == LinearGRAYColorspace))
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec601LuminancePixelIntensityMethod:
{
if ((image->colorspace == sRGBColorspace) ||
(image->colorspace == GRAYColorspace))
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.298839*red+0.586811*green+0.114350*blue;
break;
}
case Rec709LumaPixelIntensityMethod:
default:
{
if ((image->colorspace == RGBColorspace) ||
(image->colorspace == LinearGRAYColorspace))
{
red=EncodePixelGamma(red);
green=EncodePixelGamma(green);
blue=EncodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case Rec709LuminancePixelIntensityMethod:
{
if ((image->colorspace == sRGBColorspace) ||
(image->colorspace == GRAYColorspace))
{
red=DecodePixelGamma(red);
green=DecodePixelGamma(green);
blue=DecodePixelGamma(blue);
}
intensity=0.212656*red+0.715158*green+0.072186*blue;
break;
}
case RMSPixelIntensityMethod:
{
intensity=(MagickRealType) (sqrt((double) red*red+green*green+blue*blue)/
sqrt(3.0));
break;
}
}
return(intensity);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I m p o r t I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ImportImagePixels() accepts pixel data and stores in the image at the
% location you specify. The method returns MagickTrue on success otherwise
% MagickFalse if an error is encountered. The pixel data can be either char,
% Quantum, short int, unsigned int, unsigned long long, float, or double in
% the order specified by map.
%
% Suppose your want to upload the first scanline of a 640x480 image from
% character data in red-green-blue order:
%
% ImportImagePixels(image,0,0,640,1,"RGB",CharPixel,pixels);
%
% The format of the ImportImagePixels method is:
%
% MagickBooleanType ImportImagePixels(Image *image,const ssize_t x,
% const ssize_t y,const size_t width,const size_t height,
% const char *map,const StorageType type,const void *pixels,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o x,y,width,height: These values define the perimeter
% of a region of pixels you want to define.
%
% o map: This string reflects the expected ordering of the pixel array.
% It can be any combination or order of R = red, G = green, B = blue,
% A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan,
% Y = yellow, M = magenta, K = black, I = intensity (for grayscale),
% P = pad.
%
% o type: Define the data type of the pixels. Float and double types are
% normalized to [0..1] otherwise [0..QuantumRange]. Choose from these
% types: CharPixel (char *), DoublePixel (double *), FloatPixel (float *),
% LongPixel (unsigned int *), LongLongPixel (unsigned long long *),
% QuantumPixel (Quantum *), or ShortPixel (unsigned short *).
%
% o pixels: This array of values contain the pixel components as defined by
% map and type. You must preallocate this array where the expected
% length varies depending on the values of width, height, map, and type.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType ImportCharPixel(Image *image,const RectangleInfo *roi,
const char *magick_restrict map,const QuantumType *quantum_map,
const void *pixels,ExceptionInfo *exception)
{
const unsigned char
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const unsigned char *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRO") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBO") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
SetPixelAlpha(image,ScaleCharToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleCharToQuantum(*p++),q);
SetPixelGreen(image,ScaleCharToQuantum(*p++),q);
SetPixelBlue(image,ScaleCharToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ScaleCharToQuantum(*p),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ScaleCharToQuantum(*p),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ScaleCharToQuantum(*p),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ScaleCharToQuantum(*p),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ScaleCharToQuantum(*p),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ScaleCharToQuantum(*p),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ScaleCharToQuantum(*p),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportDoublePixel(Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception)
{
const double
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const double *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportFloatPixel(Image *image,const RectangleInfo *roi,
const char *magick_restrict map,const QuantumType *quantum_map,
const void *pixels,ExceptionInfo *exception)
{
const float
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const float *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportLongPixel(Image *image,const RectangleInfo *roi,
const char *magick_restrict map,const QuantumType *quantum_map,
const void *pixels,ExceptionInfo *exception)
{
const unsigned int
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const unsigned int *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
SetPixelAlpha(image,ScaleLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ScaleLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
SetPixelAlpha(image,ScaleLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ScaleLongToQuantum(*p),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ScaleLongToQuantum(*p),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ScaleLongToQuantum(*p),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ScaleLongToQuantum(*p),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ScaleLongToQuantum(*p),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ScaleLongToQuantum(*p),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ScaleLongToQuantum(*p),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportLongLongPixel(Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception)
{
const MagickSizeType
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const MagickSizeType *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
SetPixelAlpha(image,ScaleLongLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ScaleLongLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
SetPixelAlpha(image,ScaleLongLongToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleLongLongToQuantum(*p++),q);
SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q);
SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ScaleLongLongToQuantum(*p),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ScaleLongLongToQuantum(*p),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ScaleLongLongToQuantum(*p),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ScaleLongLongToQuantum(*p),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ScaleLongLongToQuantum(*p),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ScaleLongLongToQuantum(*p),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ScaleLongLongToQuantum(*p),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportQuantumPixel(Image *image,
const RectangleInfo *roi,const char *magick_restrict map,
const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception)
{
const Quantum
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const Quantum *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelRed(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelRed(image,*p++,q);
SetPixelAlpha(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelRed(image,*p++,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelBlue(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelBlue(image,*p++,q);
SetPixelAlpha(image,*p++,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,*p++,q);
SetPixelGreen(image,*p++,q);
SetPixelBlue(image,*p++,q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,*p,q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,*p,q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,*p,q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,*p,q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,*p,q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,*p,q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,*p,q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
static MagickBooleanType ImportShortPixel(Image *image,const RectangleInfo *roi,
const char *magick_restrict map,const QuantumType *quantum_map,
const void *pixels,ExceptionInfo *exception)
{
const unsigned short
*magick_restrict p;
Quantum
*magick_restrict q;
ssize_t
x;
size_t
length;
ssize_t
y;
p=(const unsigned short *) pixels;
if (LocaleCompare(map,"BGR") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
SetPixelAlpha(image,ScaleShortToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"BGRP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"I") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelGray(image,ScaleShortToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGB") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBA") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
SetPixelAlpha(image,ScaleShortToQuantum(*p++),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
if (LocaleCompare(map,"RGBP") == 0)
{
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
SetPixelRed(image,ScaleShortToQuantum(*p++),q);
SetPixelGreen(image,ScaleShortToQuantum(*p++),q);
SetPixelBlue(image,ScaleShortToQuantum(*p++),q);
p++;
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
length=strlen(map);
for (y=0; y < (ssize_t) roi->height; y++)
{
q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) roi->width; x++)
{
ssize_t
i;
for (i=0; i < (ssize_t) length; i++)
{
switch (quantum_map[i])
{
case RedQuantum:
case CyanQuantum:
{
SetPixelRed(image,ScaleShortToQuantum(*p),q);
break;
}
case GreenQuantum:
case MagentaQuantum:
{
SetPixelGreen(image,ScaleShortToQuantum(*p),q);
break;
}
case BlueQuantum:
case YellowQuantum:
{
SetPixelBlue(image,ScaleShortToQuantum(*p),q);
break;
}
case AlphaQuantum:
{
SetPixelAlpha(image,ScaleShortToQuantum(*p),q);
break;
}
case OpacityQuantum:
{
SetPixelAlpha(image,ScaleShortToQuantum(*p),q);
break;
}
case BlackQuantum:
{
SetPixelBlack(image,ScaleShortToQuantum(*p),q);
break;
}
case IndexQuantum:
{
SetPixelGray(image,ScaleShortToQuantum(*p),q);
break;
}
default:
break;
}
p++;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue);
}
MagickExport MagickBooleanType ImportImagePixels(Image *image,const ssize_t x,
const ssize_t y,const size_t width,const size_t height,const char *map,
const StorageType type,const void *pixels,ExceptionInfo *exception)
{
MagickBooleanType
status;
QuantumType
*quantum_map;
RectangleInfo
roi;
ssize_t
i;
size_t
length;
/*
Allocate image structure.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=strlen(map);
quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map));
if (quantum_map == (QuantumType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
for (i=0; i < (ssize_t) length; i++)
{
switch (map[i])
{
case 'a':
case 'A':
{
quantum_map[i]=AlphaQuantum;
image->alpha_trait=BlendPixelTrait;
break;
}
case 'B':
case 'b':
{
quantum_map[i]=BlueQuantum;
break;
}
case 'C':
case 'c':
{
quantum_map[i]=CyanQuantum;
(void) SetImageColorspace(image,CMYKColorspace,exception);
break;
}
case 'g':
case 'G':
{
quantum_map[i]=GreenQuantum;
break;
}
case 'K':
case 'k':
{
quantum_map[i]=BlackQuantum;
(void) SetImageColorspace(image,CMYKColorspace,exception);
break;
}
case 'I':
case 'i':
{
quantum_map[i]=IndexQuantum;
(void) SetImageColorspace(image,GRAYColorspace,exception);
break;
}
case 'm':
case 'M':
{
quantum_map[i]=MagentaQuantum;
(void) SetImageColorspace(image,CMYKColorspace,exception);
break;
}
case 'O':
case 'o':
{
quantum_map[i]=OpacityQuantum;
image->alpha_trait=BlendPixelTrait;
break;
}
case 'P':
case 'p':
{
quantum_map[i]=UndefinedQuantum;
break;
}
case 'R':
case 'r':
{
quantum_map[i]=RedQuantum;
break;
}
case 'Y':
case 'y':
{
quantum_map[i]=YellowQuantum;
(void) SetImageColorspace(image,CMYKColorspace,exception);
break;
}
default:
{
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedPixelMap","`%s'",map);
return(MagickFalse);
}
}
}
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
/*
Transfer the pixels from the pixel data to the image.
*/
roi.width=width;
roi.height=height;
roi.x=x;
roi.y=y;
switch (type)
{
case CharPixel:
{
status=ImportCharPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case DoublePixel:
{
status=ImportDoublePixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case FloatPixel:
{
status=ImportFloatPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case LongPixel:
{
status=ImportLongPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case LongLongPixel:
{
status=ImportLongLongPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case QuantumPixel:
{
status=ImportQuantumPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
case ShortPixel:
{
status=ImportShortPixel(image,&roi,map,quantum_map,pixels,exception);
break;
}
default:
{
(void) ThrowMagickException(exception,GetMagickModule(),OptionError,
"UnrecognizedStorageType","`%d'",type);
status=MagickFalse;
}
}
quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I n i t i a l i z e P i x e l C h a n n e l M a p %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InitializePixelChannelMap() defines the standard pixel component map.
%
% The format of the InitializePixelChannelMap() method is:
%
% void InitializePixelChannelMap(Image *image)
%
% A description of each parameter follows:
%
% o image: the image.
%
*/
MagickExport void InitializePixelChannelMap(Image *image)
{
PixelTrait
trait;
ssize_t
i;
ssize_t
n;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
(void) memset(image->channel_map,0,MaxPixelChannels*
sizeof(*image->channel_map));
trait=UpdatePixelTrait;
if (image->alpha_trait != UndefinedPixelTrait)
trait=(PixelTrait) (trait | BlendPixelTrait);
n=0;
if ((image->colorspace == LinearGRAYColorspace) ||
(image->colorspace == GRAYColorspace))
{
SetPixelChannelAttributes(image,BluePixelChannel,trait,n);
SetPixelChannelAttributes(image,GreenPixelChannel,trait,n);
SetPixelChannelAttributes(image,RedPixelChannel,trait,n++);
}
else
{
SetPixelChannelAttributes(image,RedPixelChannel,trait,n++);
SetPixelChannelAttributes(image,GreenPixelChannel,trait,n++);
SetPixelChannelAttributes(image,BluePixelChannel,trait,n++);
}
if (image->colorspace == CMYKColorspace)
SetPixelChannelAttributes(image,BlackPixelChannel,trait,n++);
for (i=0; i < (ssize_t) image->number_meta_channels; i++)
{
SetPixelChannelAttributes(image,(PixelChannel) n,UpdatePixelTrait,n);
n++;
}
if (image->alpha_trait != UndefinedPixelTrait)
SetPixelChannelAttributes(image,AlphaPixelChannel,CopyPixelTrait,n++);
if (image->storage_class == PseudoClass)
SetPixelChannelAttributes(image,IndexPixelChannel,CopyPixelTrait,n++);
if ((image->channels & ReadMaskChannel) != 0)
SetPixelChannelAttributes(image,ReadMaskPixelChannel,CopyPixelTrait,n++);
if ((image->channels & WriteMaskChannel) != 0)
SetPixelChannelAttributes(image,WriteMaskPixelChannel,CopyPixelTrait,n++);
if ((image->channels & CompositeMaskChannel) != 0)
SetPixelChannelAttributes(image,CompositeMaskPixelChannel,CopyPixelTrait,
n++);
image->number_channels=(size_t) n;
(void) SetPixelChannelMask(image,image->channel_mask);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p o l a t e P i x e l C h a n n e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpolatePixelChannel() applies a pixel interpolation method between a
% floating point coordinate and the pixels surrounding that coordinate. No
% pixel area resampling, or scaling of the result is performed.
%
% Interpolation is restricted to just the specified channel.
%
% The format of the InterpolatePixelChannel method is:
%
% MagickBooleanType InterpolatePixelChannel(
% const Image *magick_restrict image,const CacheView *image_view,
% const PixelChannel channel,const PixelInterpolateMethod method,
% const double x,const double y,double *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o image_view: the image view.
%
% o channel: the pixel channel to interpolate.
%
% o method: the pixel color interpolation method.
%
% o x,y: A double representing the current (x,y) position of the pixel.
%
% o pixel: return the interpolated pixel here.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void CatromWeights(const double x,double (*weights)[4])
{
double
alpha,
beta,
gamma;
/*
Nicolas Robidoux' 10 flops (4* + 5- + 1+) refactoring of the computation
of the standard four 1D Catmull-Rom weights. The sampling location is
assumed between the second and third input pixel locations, and x is the
position relative to the second input pixel location. Formulas originally
derived for the VIPS (Virtual Image Processing System) library.
*/
alpha=(double) 1.0-x;
beta=(double) (-0.5)*x*alpha;
(*weights)[0]=alpha*beta;
(*weights)[3]=x*beta;
/*
The following computation of the inner weights from the outer ones work
for all Keys cubics.
*/
gamma=(*weights)[3]-(*weights)[0];
(*weights)[1]=alpha-(*weights)[0]+gamma;
(*weights)[2]=x-(*weights)[3]-gamma;
}
static inline void SplineWeights(const double x,double (*weights)[4])
{
double
alpha,
beta;
/*
Nicolas Robidoux' 12 flops (6* + 5- + 1+) refactoring of the computation
of the standard four 1D cubic B-spline smoothing weights. The sampling
location is assumed between the second and third input pixel locations,
and x is the position relative to the second input pixel location.
*/
alpha=(double) 1.0-x;
(*weights)[3]=(double) (1.0/6.0)*x*x*x;
(*weights)[0]=(double) (1.0/6.0)*alpha*alpha*alpha;
beta=(*weights)[3]-(*weights)[0];
(*weights)[1]=alpha-(*weights)[0]+beta;
(*weights)[2]=x-(*weights)[3]-beta;
}
static inline double MeshInterpolate(const PointInfo *delta,const double p,
const double x,const double y)
{
return(delta->x*x+delta->y*y+(1.0-delta->x-delta->y)*p);
}
MagickExport MagickBooleanType InterpolatePixelChannel(
const Image *magick_restrict image,const CacheView_ *image_view,
const PixelChannel channel,const PixelInterpolateMethod method,
const double x,const double y,double *pixel,ExceptionInfo *exception)
{
double
alpha[16],
gamma,
pixels[16];
MagickBooleanType
status;
PixelInterpolateMethod
interpolate;
PixelTrait
traits;
const Quantum
*magick_restrict p;
ssize_t
i;
ssize_t
x_offset,
y_offset;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image_view != (CacheView *) NULL);
status=MagickTrue;
*pixel=0.0;
traits=GetPixelChannelTraits(image,channel);
x_offset=CastDoubleToLong(floor(x));
y_offset=CastDoubleToLong(floor(y));
interpolate=method;
if (interpolate == UndefinedInterpolatePixel)
interpolate=image->interpolate;
switch (interpolate)
{
case AverageInterpolatePixel: /* nearest 4 neighbours */
case Average9InterpolatePixel: /* nearest 9 neighbours */
case Average16InterpolatePixel: /* nearest 16 neighbours */
{
ssize_t
count;
count=2; /* size of the area to average - default nearest 4 */
if (interpolate == Average9InterpolatePixel)
{
count=3;
x_offset=CastDoubleToLong(floor(x+0.5)-1.0);
y_offset=CastDoubleToLong(floor(y+0.5)-1.0);
}
else
if (interpolate == Average16InterpolatePixel)
{
count=4;
x_offset--;
y_offset--;
}
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,(size_t) count,
(size_t) count,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
count*=count; /* Number of pixels to average */
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < (ssize_t) count; i++)
{
alpha[i]=1.0;
pixels[i]=(double) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < (ssize_t) count; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
for (i=0; i < (ssize_t) count; i++)
{
gamma=PerceptibleReciprocal(alpha[i])/count;
*pixel+=gamma*pixels[i];
}
break;
}
case BilinearInterpolatePixel:
default:
{
PointInfo
delta,
epsilon;
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < 4; i++)
{
alpha[i]=1.0;
pixels[i]=(double) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < 4; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
delta.x=x-x_offset;
delta.y=y-y_offset;
epsilon.x=1.0-delta.x;
epsilon.y=1.0-delta.y;
gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y*
(epsilon.x*alpha[2]+delta.x*alpha[3])));
gamma=PerceptibleReciprocal(gamma);
*pixel=gamma*(epsilon.y*(epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y*
(epsilon.x*pixels[2]+delta.x*pixels[3]));
break;
}
case BlendInterpolatePixel:
{
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < 4; i++)
{
alpha[i]=1.0;
pixels[i]=(MagickRealType) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < 4; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
gamma=1.0; /* number of pixels blended together (its variable) */
for (i=0; i <= 1L; i++) {
if ((y-y_offset) >= 0.75)
{
alpha[i]=alpha[i+2]; /* take right pixels */
pixels[i]=pixels[i+2];
}
else
if ((y-y_offset) > 0.25)
{
gamma=2.0; /* blend both pixels in row */
alpha[i]+=alpha[i+2]; /* add up alpha weights */
pixels[i]+=pixels[i+2];
}
}
if ((x-x_offset) >= 0.75)
{
alpha[0]=alpha[1]; /* take bottom row blend */
pixels[0]=pixels[1];
}
else
if ((x-x_offset) > 0.25)
{
gamma*=2.0; /* blend both rows */
alpha[0]+=alpha[1]; /* add up alpha weights */
pixels[0]+=pixels[1];
}
if (channel != AlphaPixelChannel)
gamma=PerceptibleReciprocal(alpha[0]); /* (color) 1/alpha_weights */
else
gamma=PerceptibleReciprocal(gamma); /* (alpha) 1/number_of_pixels */
*pixel=gamma*pixels[0];
break;
}
case CatromInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < 16; i++)
{
alpha[i]=1.0;
pixels[i]=(double) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < 16; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
CatromWeights((double) (x-x_offset),&cx);
CatromWeights((double) (y-y_offset),&cy);
gamma=(channel == AlphaPixelChannel ? (double) 1.0 :
PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]*
alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]*
alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]*
alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+
cx[2]*alpha[14]+cx[3]*alpha[15])));
*pixel=gamma*(cy[0]*(cx[0]*pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+
cx[3]*pixels[3])+cy[1]*(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*
pixels[6]+cx[3]*pixels[7])+cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+
cx[2]*pixels[10]+cx[3]*pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*
pixels[13]+cx[2]*pixels[14]+cx[3]*pixels[15]));
break;
}
case IntegerInterpolatePixel:
{
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
*pixel=(double) GetPixelChannel(image,channel,p);
break;
}
case NearestInterpolatePixel:
{
x_offset=CastDoubleToLong(floor(x+0.5));
y_offset=CastDoubleToLong(floor(y+0.5));
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
*pixel=(double) GetPixelChannel(image,channel,p);
break;
}
case MeshInterpolatePixel:
{
PointInfo
delta,
luminance;
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < 4; i++)
{
alpha[i]=1.0;
pixels[i]=(double) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < 4; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
delta.x=x-x_offset;
delta.y=y-y_offset;
luminance.x=GetPixelLuma(image,p)-(double)
GetPixelLuma(image,p+3*GetPixelChannels(image));
luminance.y=GetPixelLuma(image,p+GetPixelChannels(image))-(double)
GetPixelLuma(image,p+2*GetPixelChannels(image));
if (fabs((double) luminance.x) < fabs((double) luminance.y))
{
/*
Diagonal 0-3 NW-SE.
*/
if (delta.x <= delta.y)
{
/*
Bottom-left triangle (pixel: 2, diagonal: 0-3).
*/
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]);
gamma=PerceptibleReciprocal(gamma);
*pixel=gamma*MeshInterpolate(&delta,pixels[2],pixels[3],
pixels[0]);
}
else
{
/*
Top-right triangle (pixel: 1, diagonal: 0-3).
*/
delta.x=1.0-delta.x;
gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]);
gamma=PerceptibleReciprocal(gamma);
*pixel=gamma*MeshInterpolate(&delta,pixels[1],pixels[0],
pixels[3]);
}
}
else
{
/*
Diagonal 1-2 NE-SW.
*/
if (delta.x <= (1.0-delta.y))
{
/*
Top-left triangle (pixel: 0, diagonal: 1-2).
*/
gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]);
gamma=PerceptibleReciprocal(gamma);
*pixel=gamma*MeshInterpolate(&delta,pixels[0],pixels[1],
pixels[2]);
}
else
{
/*
Bottom-right triangle (pixel: 3, diagonal: 1-2).
*/
delta.x=1.0-delta.x;
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]);
gamma=PerceptibleReciprocal(gamma);
*pixel=gamma*MeshInterpolate(&delta,pixels[3],pixels[2],
pixels[1]);
}
}
break;
}
case SplineInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
if ((traits & BlendPixelTrait) == 0)
for (i=0; i < 16; i++)
{
alpha[i]=1.0;
pixels[i]=(double) p[i*GetPixelChannels(image)+channel];
}
else
for (i=0; i < 16; i++)
{
alpha[i]=QuantumScale*GetPixelAlpha(image,p+i*
GetPixelChannels(image));
pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel];
}
SplineWeights((double) (x-x_offset),&cx);
SplineWeights((double) (y-y_offset),&cy);
gamma=(channel == AlphaPixelChannel ? (double) 1.0 :
PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]*
alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]*
alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]*
alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+
cx[2]*alpha[14]+cx[3]*alpha[15])));
*pixel=gamma*(cy[0]*(cx[0]*pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+
cx[3]*pixels[3])+cy[1]*(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*
pixels[6]+cx[3]*pixels[7])+cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+
cx[2]*pixels[10]+cx[3]*pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*
pixels[13]+cx[2]*pixels[14]+cx[3]*pixels[15]));
break;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p o l a t e P i x e l C h a n n e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpolatePixelChannels() applies a pixel interpolation method between a
% floating point coordinate and the pixels surrounding that coordinate. No
% pixel area resampling, or scaling of the result is performed.
%
% Interpolation is restricted to just the current channel setting of the
% destination image into which the color is to be stored
%
% The format of the InterpolatePixelChannels method is:
%
% MagickBooleanType InterpolatePixelChannels(
% const Image *magick_restrict source,const CacheView *source_view,
% const Image *magick_restrict destination,
% const PixelInterpolateMethod method,const double x,const double y,
% Quantum *pixel,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o source: the source.
%
% o source_view: the source view.
%
% o destination: the destination image, for the interpolated color
%
% o method: the pixel color interpolation method.
%
% o x,y: A double representing the current (x,y) position of the pixel.
%
% o pixel: return the interpolated pixel here.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType InterpolatePixelChannels(
const Image *magick_restrict source,const CacheView_ *source_view,
const Image *magick_restrict destination,const PixelInterpolateMethod method,
const double x,const double y,Quantum *pixel,ExceptionInfo *exception)
{
MagickBooleanType
status;
double
alpha[16],
gamma,
pixels[16];
const Quantum
*magick_restrict p;
ssize_t
i;
ssize_t
x_offset,
y_offset;
PixelInterpolateMethod
interpolate;
assert(source != (Image *) NULL);
assert(source->signature == MagickCoreSignature);
assert(source_view != (CacheView *) NULL);
status=MagickTrue;
x_offset=CastDoubleToLong(floor(x));
y_offset=CastDoubleToLong(floor(y));
interpolate=method;
if (interpolate == UndefinedInterpolatePixel)
interpolate=source->interpolate;
switch (interpolate)
{
case AverageInterpolatePixel: /* nearest 4 neighbours */
case Average9InterpolatePixel: /* nearest 9 neighbours */
case Average16InterpolatePixel: /* nearest 16 neighbours */
{
ssize_t
count;
count=2; /* size of the area to average - default nearest 4 */
if (interpolate == Average9InterpolatePixel)
{
count=3;
x_offset=CastDoubleToLong(floor(x+0.5)-1.0);
y_offset=CastDoubleToLong(floor(y+0.5)-1.0);
}
else
if (interpolate == Average16InterpolatePixel)
{
count=4;
x_offset--;
y_offset--;
}
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,(size_t) count,
(size_t) count,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
count*=count; /* Number of pixels to average */
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
double
sum;
ssize_t
j;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
for (j=0; j < (ssize_t) count; j++)
pixels[j]=(double) p[j*GetPixelChannels(source)+i];
sum=0.0;
if ((traits & BlendPixelTrait) == 0)
{
for (j=0; j < (ssize_t) count; j++)
sum+=pixels[j];
sum/=count;
SetPixelChannel(destination,channel,ClampToQuantum(sum),pixel);
continue;
}
for (j=0; j < (ssize_t) count; j++)
{
alpha[j]=QuantumScale*GetPixelAlpha(source,p+j*
GetPixelChannels(source));
pixels[j]*=alpha[j];
gamma=PerceptibleReciprocal(alpha[j]);
sum+=gamma*pixels[j];
}
sum/=count;
SetPixelChannel(destination,channel,ClampToQuantum(sum),pixel);
}
break;
}
case BilinearInterpolatePixel:
default:
{
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PointInfo
delta,
epsilon;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
delta.x=x-x_offset;
delta.y=y-y_offset;
epsilon.x=1.0-delta.x;
epsilon.y=1.0-delta.y;
pixels[0]=(double) p[i];
pixels[1]=(double) p[GetPixelChannels(source)+i];
pixels[2]=(double) p[2*GetPixelChannels(source)+i];
pixels[3]=(double) p[3*GetPixelChannels(source)+i];
if ((traits & BlendPixelTrait) == 0)
{
gamma=((epsilon.y*(epsilon.x+delta.x)+delta.y*(epsilon.x+delta.x)));
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*(epsilon.y*
(epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y*(epsilon.x*
pixels[2]+delta.x*pixels[3]))),pixel);
continue;
}
alpha[0]=QuantumScale*GetPixelAlpha(source,p);
alpha[1]=QuantumScale*GetPixelAlpha(source,p+GetPixelChannels(source));
alpha[2]=QuantumScale*GetPixelAlpha(source,p+2*
GetPixelChannels(source));
alpha[3]=QuantumScale*GetPixelAlpha(source,p+3*
GetPixelChannels(source));
pixels[0]*=alpha[0];
pixels[1]*=alpha[1];
pixels[2]*=alpha[2];
pixels[3]*=alpha[3];
gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y*
(epsilon.x*alpha[2]+delta.x*alpha[3])));
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*(epsilon.y*
(epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y*(epsilon.x*pixels[2]+
delta.x*pixels[3]))),pixel);
}
break;
}
case BlendInterpolatePixel:
{
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
ssize_t
j;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
if (source->alpha_trait != BlendPixelTrait)
for (j=0; j < 4; j++)
{
alpha[j]=1.0;
pixels[j]=(double) p[j*GetPixelChannels(source)+i];
}
else
for (j=0; j < 4; j++)
{
alpha[j]=QuantumScale*GetPixelAlpha(source,p+j*
GetPixelChannels(source));
pixels[j]=(double) p[j*GetPixelChannels(source)+i];
if (channel != AlphaPixelChannel)
pixels[j]*=alpha[j];
}
gamma=1.0; /* number of pixels blended together (its variable) */
for (j=0; j <= 1L; j++)
{
if ((y-y_offset) >= 0.75)
{
alpha[j]=alpha[j+2]; /* take right pixels */
pixels[j]=pixels[j+2];
}
else
if ((y-y_offset) > 0.25)
{
gamma=2.0; /* blend both pixels in row */
alpha[j]+=alpha[j+2]; /* add up alpha weights */
pixels[j]+=pixels[j+2];
}
}
if ((x-x_offset) >= 0.75)
{
alpha[0]=alpha[1]; /* take bottom row blend */
pixels[0]=pixels[1];
}
else
if ((x-x_offset) > 0.25)
{
gamma*=2.0; /* blend both rows */
alpha[0]+=alpha[1]; /* add up alpha weights */
pixels[0]+=pixels[1];
}
if (channel != AlphaPixelChannel)
gamma=PerceptibleReciprocal(alpha[0]); /* (color) 1/alpha_weights */
else
gamma=PerceptibleReciprocal(gamma); /* (alpha) 1/number_of_pixels */
SetPixelChannel(destination,channel,ClampToQuantum(gamma*pixels[0]),
pixel);
}
break;
}
case CatromInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(source_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
ssize_t
j;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
if ((traits & BlendPixelTrait) == 0)
for (j=0; j < 16; j++)
{
alpha[j]=1.0;
pixels[j]=(double) p[j*GetPixelChannels(source)+i];
}
else
for (j=0; j < 16; j++)
{
alpha[j]=QuantumScale*GetPixelAlpha(source,p+j*
GetPixelChannels(source));
pixels[j]=alpha[j]*p[j*GetPixelChannels(source)+i];
}
CatromWeights((double) (x-x_offset),&cx);
CatromWeights((double) (y-y_offset),&cy);
gamma=((traits & BlendPixelTrait) ? (double) (1.0) :
PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]*
alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]*
alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]*
alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+
cx[2]*alpha[14]+cx[3]*alpha[15])));
SetPixelChannel(destination,channel,ClampToQuantum(gamma*(cy[0]*(cx[0]*
pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+cx[3]*pixels[3])+cy[1]*
(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*pixels[6]+cx[3]*pixels[7])+
cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+cx[2]*pixels[10]+cx[3]*
pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*pixels[13]+cx[2]*
pixels[14]+cx[3]*pixels[15]))),pixel);
}
break;
}
case IntegerInterpolatePixel:
{
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(destination,channel,p[i],pixel);
}
break;
}
case NearestInterpolatePixel:
{
x_offset=CastDoubleToLong(floor(x+0.5));
y_offset=CastDoubleToLong(floor(y+0.5));
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
SetPixelChannel(destination,channel,p[i],pixel);
}
break;
}
case MeshInterpolatePixel:
{
p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
PointInfo
delta,
luminance;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
pixels[0]=(double) p[i];
pixels[1]=(double) p[GetPixelChannels(source)+i];
pixels[2]=(double) p[2*GetPixelChannels(source)+i];
pixels[3]=(double) p[3*GetPixelChannels(source)+i];
if ((traits & BlendPixelTrait) == 0)
{
alpha[0]=1.0;
alpha[1]=1.0;
alpha[2]=1.0;
alpha[3]=1.0;
}
else
{
alpha[0]=QuantumScale*GetPixelAlpha(source,p);
alpha[1]=QuantumScale*GetPixelAlpha(source,p+
GetPixelChannels(source));
alpha[2]=QuantumScale*GetPixelAlpha(source,p+2*
GetPixelChannels(source));
alpha[3]=QuantumScale*GetPixelAlpha(source,p+3*
GetPixelChannels(source));
}
delta.x=x-x_offset;
delta.y=y-y_offset;
luminance.x=fabs((double) (GetPixelLuma(source,p)-
GetPixelLuma(source,p+3*GetPixelChannels(source))));
luminance.y=fabs((double) (GetPixelLuma(source,p+
GetPixelChannels(source))-GetPixelLuma(source,p+2*
GetPixelChannels(source))));
if (luminance.x < luminance.y)
{
/*
Diagonal 0-3 NW-SE.
*/
if (delta.x <= delta.y)
{
/*
Bottom-left triangle (pixel: 2, diagonal: 0-3).
*/
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]);
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*
MeshInterpolate(&delta,pixels[2],pixels[3],pixels[0])),pixel);
}
else
{
/*
Top-right triangle (pixel: 1, diagonal: 0-3).
*/
delta.x=1.0-delta.x;
gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]);
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*
MeshInterpolate(&delta,pixels[1],pixels[0],pixels[3])),pixel);
}
}
else
{
/*
Diagonal 1-2 NE-SW.
*/
if (delta.x <= (1.0-delta.y))
{
/*
Top-left triangle (pixel: 0, diagonal: 1-2).
*/
gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]);
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*
MeshInterpolate(&delta,pixels[0],pixels[1],pixels[2])),pixel);
}
else
{
/*
Bottom-right triangle (pixel: 3, diagonal: 1-2).
*/
delta.x=1.0-delta.x;
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]);
gamma=PerceptibleReciprocal(gamma);
SetPixelChannel(destination,channel,ClampToQuantum(gamma*
MeshInterpolate(&delta,pixels[3],pixels[2],pixels[1])),pixel);
}
}
}
break;
}
case SplineInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(source_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < (ssize_t) GetPixelChannels(source); i++)
{
ssize_t
j;
PixelChannel channel = GetPixelChannelChannel(source,i);
PixelTrait traits = GetPixelChannelTraits(source,channel);
PixelTrait destination_traits=GetPixelChannelTraits(destination,
channel);
if ((traits == UndefinedPixelTrait) ||
(destination_traits == UndefinedPixelTrait))
continue;
if ((traits & BlendPixelTrait) == 0)
for (j=0; j < 16; j++)
{
alpha[j]=1.0;
pixels[j]=(double) p[j*GetPixelChannels(source)+i];
}
else
for (j=0; j < 16; j++)
{
alpha[j]=QuantumScale*GetPixelAlpha(source,p+j*
GetPixelChannels(source));
pixels[j]=alpha[j]*p[j*GetPixelChannels(source)+i];
}
SplineWeights((double) (x-x_offset),&cx);
SplineWeights((double) (y-y_offset),&cy);
gamma=((traits & BlendPixelTrait) ? (double) (1.0) :
PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]*
alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]*
alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]*
alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+
cx[2]*alpha[14]+cx[3]*alpha[15])));
SetPixelChannel(destination,channel,ClampToQuantum(gamma*(cy[0]*(cx[0]*
pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+cx[3]*pixels[3])+cy[1]*
(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*pixels[6]+cx[3]*pixels[7])+
cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+cx[2]*pixels[10]+cx[3]*
pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*pixels[13]+cx[2]*
pixels[14]+cx[3]*pixels[15]))),pixel);
}
break;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I n t e r p o l a t e P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% InterpolatePixelInfo() applies a pixel interpolation method between a
% floating point coordinate and the pixels surrounding that coordinate. No
% pixel area resampling, or scaling of the result is performed.
%
% Interpolation is restricted to just RGBKA channels.
%
% The format of the InterpolatePixelInfo method is:
%
% MagickBooleanType InterpolatePixelInfo(const Image *image,
% const CacheView *image_view,const PixelInterpolateMethod method,
% const double x,const double y,PixelInfo *pixel,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o image_view: the image view.
%
% o method: the pixel color interpolation method.
%
% o x,y: A double representing the current (x,y) position of the pixel.
%
% o pixel: return the interpolated pixel here.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline void AlphaBlendPixelInfo(const Image *image,
const Quantum *pixel,PixelInfo *pixel_info,double *alpha)
{
if (image->alpha_trait == UndefinedPixelTrait)
{
*alpha=1.0;
pixel_info->red=(double) GetPixelRed(image,pixel);
pixel_info->green=(double) GetPixelGreen(image,pixel);
pixel_info->blue=(double) GetPixelBlue(image,pixel);
pixel_info->black=0.0;
if (image->colorspace == CMYKColorspace)
pixel_info->black=(double) GetPixelBlack(image,pixel);
pixel_info->alpha=(double) GetPixelAlpha(image,pixel);
return;
}
*alpha=QuantumScale*GetPixelAlpha(image,pixel);
pixel_info->red=(*alpha*GetPixelRed(image,pixel));
pixel_info->green=(*alpha*GetPixelGreen(image,pixel));
pixel_info->blue=(*alpha*GetPixelBlue(image,pixel));
pixel_info->black=0.0;
if (image->colorspace == CMYKColorspace)
pixel_info->black=(*alpha*GetPixelBlack(image,pixel));
pixel_info->alpha=(double) GetPixelAlpha(image,pixel);
}
MagickExport MagickBooleanType InterpolatePixelInfo(const Image *image,
const CacheView_ *image_view,const PixelInterpolateMethod method,
const double x,const double y,PixelInfo *pixel,ExceptionInfo *exception)
{
MagickBooleanType
status;
double
alpha[16],
gamma;
PixelInfo
pixels[16];
const Quantum
*p;
ssize_t
i;
ssize_t
x_offset,
y_offset;
PixelInterpolateMethod
interpolate;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(image_view != (CacheView *) NULL);
status=MagickTrue;
x_offset=CastDoubleToLong(floor(x));
y_offset=CastDoubleToLong(floor(y));
interpolate=method;
if (interpolate == UndefinedInterpolatePixel)
interpolate=image->interpolate;
GetPixelInfoPixel(image,(const Quantum *) NULL,pixel);
(void) memset(&pixels,0,sizeof(pixels));
switch (interpolate)
{
case AverageInterpolatePixel: /* nearest 4 neighbours */
case Average9InterpolatePixel: /* nearest 9 neighbours */
case Average16InterpolatePixel: /* nearest 16 neighbours */
{
ssize_t
count;
count=2; /* size of the area to average - default nearest 4 */
if (interpolate == Average9InterpolatePixel)
{
count=3;
x_offset=CastDoubleToLong(floor(x+0.5)-1.0);
y_offset=CastDoubleToLong(floor(y+0.5)-1.0);
}
else if (interpolate == Average16InterpolatePixel)
{
count=4;
x_offset--;
y_offset--;
}
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,(size_t) count,
(size_t) count,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
count*=count; /* number of pixels - square of size */
for (i=0; i < (ssize_t) count; i++)
{
AlphaBlendPixelInfo(image,p,pixels,alpha);
gamma=PerceptibleReciprocal(alpha[0]);
pixel->red+=gamma*pixels[0].red;
pixel->green+=gamma*pixels[0].green;
pixel->blue+=gamma*pixels[0].blue;
pixel->black+=gamma*pixels[0].black;
pixel->alpha+=pixels[0].alpha;
p += GetPixelChannels(image);
}
gamma=1.0/count; /* average weighting of each pixel in area */
pixel->red*=gamma;
pixel->green*=gamma;
pixel->blue*=gamma;
pixel->black*=gamma;
pixel->alpha*=gamma;
break;
}
case BackgroundInterpolatePixel:
{
*pixel=image->background_color; /* Copy PixelInfo Structure */
break;
}
case BilinearInterpolatePixel:
default:
{
PointInfo
delta,
epsilon;
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < 4L; i++)
AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i);
delta.x=x-x_offset;
delta.y=y-y_offset;
epsilon.x=1.0-delta.x;
epsilon.y=1.0-delta.y;
gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y*
(epsilon.x*alpha[2]+delta.x*alpha[3])));
gamma=PerceptibleReciprocal(gamma);
pixel->red=gamma*(epsilon.y*(epsilon.x*pixels[0].red+delta.x*
pixels[1].red)+delta.y*(epsilon.x*pixels[2].red+delta.x*pixels[3].red));
pixel->green=gamma*(epsilon.y*(epsilon.x*pixels[0].green+delta.x*
pixels[1].green)+delta.y*(epsilon.x*pixels[2].green+delta.x*
pixels[3].green));
pixel->blue=gamma*(epsilon.y*(epsilon.x*pixels[0].blue+delta.x*
pixels[1].blue)+delta.y*(epsilon.x*pixels[2].blue+delta.x*
pixels[3].blue));
if (image->colorspace == CMYKColorspace)
pixel->black=gamma*(epsilon.y*(epsilon.x*pixels[0].black+delta.x*
pixels[1].black)+delta.y*(epsilon.x*pixels[2].black+delta.x*
pixels[3].black));
gamma=((epsilon.y*(epsilon.x+delta.x)+delta.y*(epsilon.x+delta.x)));
gamma=PerceptibleReciprocal(gamma);
pixel->alpha=gamma*(epsilon.y*(epsilon.x*pixels[0].alpha+delta.x*
pixels[1].alpha)+delta.y*(epsilon.x*pixels[2].alpha+delta.x*
pixels[3].alpha));
break;
}
case BlendInterpolatePixel:
{
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < 4L; i++)
{
GetPixelInfoPixel(image,p+i*GetPixelChannels(image),pixels+i);
AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i);
}
gamma=1.0; /* number of pixels blended together (its variable) */
for (i=0; i <= 1L; i++)
{
if ((y-y_offset) >= 0.75)
{
alpha[i]=alpha[i+2]; /* take right pixels */
pixels[i]=pixels[i+2];
}
else
if ((y-y_offset) > 0.25)
{
gamma=2.0; /* blend both pixels in row */
alpha[i]+=alpha[i+2]; /* add up alpha weights */
pixels[i].red+=pixels[i+2].red;
pixels[i].green+=pixels[i+2].green;
pixels[i].blue+=pixels[i+2].blue;
pixels[i].black+=pixels[i+2].black;
pixels[i].alpha+=pixels[i+2].alpha;
}
}
if ((x-x_offset) >= 0.75)
{
alpha[0]=alpha[1];
pixels[0]=pixels[1];
}
else
if ((x-x_offset) > 0.25)
{
gamma*=2.0; /* blend both rows */
alpha[0]+= alpha[1]; /* add up alpha weights */
pixels[0].red+=pixels[1].red;
pixels[0].green+=pixels[1].green;
pixels[0].blue+=pixels[1].blue;
pixels[0].black+=pixels[1].black;
pixels[0].alpha+=pixels[1].alpha;
}
gamma=1.0/gamma;
alpha[0]=PerceptibleReciprocal(alpha[0]);
pixel->red=alpha[0]*pixels[0].red;
pixel->green=alpha[0]*pixels[0].green; /* divide by sum of alpha */
pixel->blue=alpha[0]*pixels[0].blue;
pixel->black=alpha[0]*pixels[0].black;
pixel->alpha=gamma*pixels[0].alpha; /* divide by number of pixels */
break;
}
case CatromInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < 16L; i++)
AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i);
CatromWeights((double) (x-x_offset),&cx);
CatromWeights((double) (y-y_offset),&cy);
pixel->red=(cy[0]*(cx[0]*pixels[0].red+cx[1]*pixels[1].red+cx[2]*
pixels[2].red+cx[3]*pixels[3].red)+cy[1]*(cx[0]*pixels[4].red+cx[1]*
pixels[5].red+cx[2]*pixels[6].red+cx[3]*pixels[7].red)+cy[2]*(cx[0]*
pixels[8].red+cx[1]*pixels[9].red+cx[2]*pixels[10].red+cx[3]*
pixels[11].red)+cy[3]*(cx[0]*pixels[12].red+cx[1]*pixels[13].red+cx[2]*
pixels[14].red+cx[3]*pixels[15].red));
pixel->green=(cy[0]*(cx[0]*pixels[0].green+cx[1]*pixels[1].green+cx[2]*
pixels[2].green+cx[3]*pixels[3].green)+cy[1]*(cx[0]*pixels[4].green+
cx[1]*pixels[5].green+cx[2]*pixels[6].green+cx[3]*pixels[7].green)+
cy[2]*(cx[0]*pixels[8].green+cx[1]*pixels[9].green+cx[2]*
pixels[10].green+cx[3]*pixels[11].green)+cy[3]*(cx[0]*
pixels[12].green+cx[1]*pixels[13].green+cx[2]*pixels[14].green+cx[3]*
pixels[15].green));
pixel->blue=(cy[0]*(cx[0]*pixels[0].blue+cx[1]*pixels[1].blue+cx[2]*
pixels[2].blue+cx[3]*pixels[3].blue)+cy[1]*(cx[0]*pixels[4].blue+cx[1]*
pixels[5].blue+cx[2]*pixels[6].blue+cx[3]*pixels[7].blue)+cy[2]*(cx[0]*
pixels[8].blue+cx[1]*pixels[9].blue+cx[2]*pixels[10].blue+cx[3]*
pixels[11].blue)+cy[3]*(cx[0]*pixels[12].blue+cx[1]*pixels[13].blue+
cx[2]*pixels[14].blue+cx[3]*pixels[15].blue));
if (image->colorspace == CMYKColorspace)
pixel->black=(cy[0]*(cx[0]*pixels[0].black+cx[1]*pixels[1].black+cx[2]*
pixels[2].black+cx[3]*pixels[3].black)+cy[1]*(cx[0]*pixels[4].black+
cx[1]*pixels[5].black+cx[2]*pixels[6].black+cx[3]*pixels[7].black)+
cy[2]*(cx[0]*pixels[8].black+cx[1]*pixels[9].black+cx[2]*
pixels[10].black+cx[3]*pixels[11].black)+cy[3]*(cx[0]*
pixels[12].black+cx[1]*pixels[13].black+cx[2]*pixels[14].black+cx[3]*
pixels[15].black));
pixel->alpha=(cy[0]*(cx[0]*pixels[0].alpha+cx[1]*pixels[1].alpha+cx[2]*
pixels[2].alpha+cx[3]*pixels[3].alpha)+cy[1]*(cx[0]*pixels[4].alpha+
cx[1]*pixels[5].alpha+cx[2]*pixels[6].alpha+cx[3]*pixels[7].alpha)+
cy[2]*(cx[0]*pixels[8].alpha+cx[1]*pixels[9].alpha+cx[2]*
pixels[10].alpha+cx[3]*pixels[11].alpha)+cy[3]*(cx[0]*pixels[12].alpha+
cx[1]*pixels[13].alpha+cx[2]*pixels[14].alpha+cx[3]*pixels[15].alpha));
break;
}
case IntegerInterpolatePixel:
{
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
GetPixelInfoPixel(image,p,pixel);
break;
}
case MeshInterpolatePixel:
{
PointInfo
delta,
luminance;
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
delta.x=x-x_offset;
delta.y=y-y_offset;
luminance.x=GetPixelLuma(image,p)-(double)
GetPixelLuma(image,p+3*GetPixelChannels(image));
luminance.y=GetPixelLuma(image,p+GetPixelChannels(image))-(double)
GetPixelLuma(image,p+2*GetPixelChannels(image));
AlphaBlendPixelInfo(image,p,pixels+0,alpha+0);
AlphaBlendPixelInfo(image,p+GetPixelChannels(image),pixels+1,alpha+1);
AlphaBlendPixelInfo(image,p+2*GetPixelChannels(image),pixels+2,alpha+2);
AlphaBlendPixelInfo(image,p+3*GetPixelChannels(image),pixels+3,alpha+3);
if (fabs((double) luminance.x) < fabs((double) luminance.y))
{
/*
Diagonal 0-3 NW-SE.
*/
if (delta.x <= delta.y)
{
/*
Bottom-left triangle (pixel: 2, diagonal: 0-3).
*/
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]);
gamma=PerceptibleReciprocal(gamma);
pixel->red=gamma*MeshInterpolate(&delta,pixels[2].red,
pixels[3].red,pixels[0].red);
pixel->green=gamma*MeshInterpolate(&delta,pixels[2].green,
pixels[3].green,pixels[0].green);
pixel->blue=gamma*MeshInterpolate(&delta,pixels[2].blue,
pixels[3].blue,pixels[0].blue);
if (image->colorspace == CMYKColorspace)
pixel->black=gamma*MeshInterpolate(&delta,pixels[2].black,
pixels[3].black,pixels[0].black);
gamma=MeshInterpolate(&delta,1.0,1.0,1.0);
pixel->alpha=gamma*MeshInterpolate(&delta,pixels[2].alpha,
pixels[3].alpha,pixels[0].alpha);
}
else
{
/*
Top-right triangle (pixel:1 , diagonal: 0-3).
*/
delta.x=1.0-delta.x;
gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]);
gamma=PerceptibleReciprocal(gamma);
pixel->red=gamma*MeshInterpolate(&delta,pixels[1].red,
pixels[0].red,pixels[3].red);
pixel->green=gamma*MeshInterpolate(&delta,pixels[1].green,
pixels[0].green,pixels[3].green);
pixel->blue=gamma*MeshInterpolate(&delta,pixels[1].blue,
pixels[0].blue,pixels[3].blue);
if (image->colorspace == CMYKColorspace)
pixel->black=gamma*MeshInterpolate(&delta,pixels[1].black,
pixels[0].black,pixels[3].black);
gamma=MeshInterpolate(&delta,1.0,1.0,1.0);
pixel->alpha=gamma*MeshInterpolate(&delta,pixels[1].alpha,
pixels[0].alpha,pixels[3].alpha);
}
}
else
{
/*
Diagonal 1-2 NE-SW.
*/
if (delta.x <= (1.0-delta.y))
{
/*
Top-left triangle (pixel: 0, diagonal: 1-2).
*/
gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]);
gamma=PerceptibleReciprocal(gamma);
pixel->red=gamma*MeshInterpolate(&delta,pixels[0].red,
pixels[1].red,pixels[2].red);
pixel->green=gamma*MeshInterpolate(&delta,pixels[0].green,
pixels[1].green,pixels[2].green);
pixel->blue=gamma*MeshInterpolate(&delta,pixels[0].blue,
pixels[1].blue,pixels[2].blue);
if (image->colorspace == CMYKColorspace)
pixel->black=gamma*MeshInterpolate(&delta,pixels[0].black,
pixels[1].black,pixels[2].black);
gamma=MeshInterpolate(&delta,1.0,1.0,1.0);
pixel->alpha=gamma*MeshInterpolate(&delta,pixels[0].alpha,
pixels[1].alpha,pixels[2].alpha);
}
else
{
/*
Bottom-right triangle (pixel: 3, diagonal: 1-2).
*/
delta.x=1.0-delta.x;
delta.y=1.0-delta.y;
gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]);
gamma=PerceptibleReciprocal(gamma);
pixel->red=gamma*MeshInterpolate(&delta,pixels[3].red,
pixels[2].red,pixels[1].red);
pixel->green=gamma*MeshInterpolate(&delta,pixels[3].green,
pixels[2].green,pixels[1].green);
pixel->blue=gamma*MeshInterpolate(&delta,pixels[3].blue,
pixels[2].blue,pixels[1].blue);
if (image->colorspace == CMYKColorspace)
pixel->black=gamma*MeshInterpolate(&delta,pixels[3].black,
pixels[2].black,pixels[1].black);
gamma=MeshInterpolate(&delta,1.0,1.0,1.0);
pixel->alpha=gamma*MeshInterpolate(&delta,pixels[3].alpha,
pixels[2].alpha,pixels[1].alpha);
}
}
break;
}
case NearestInterpolatePixel:
{
x_offset=CastDoubleToLong(floor(x+0.5));
y_offset=CastDoubleToLong(floor(y+0.5));
p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
GetPixelInfoPixel(image,p,pixel);
break;
}
case SplineInterpolatePixel:
{
double
cx[4],
cy[4];
p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4,
exception);
if (p == (const Quantum *) NULL)
{
status=MagickFalse;
break;
}
for (i=0; i < 16L; i++)
AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i);
SplineWeights((double) (x-x_offset),&cx);
SplineWeights((double) (y-y_offset),&cy);
pixel->red=(cy[0]*(cx[0]*pixels[0].red+cx[1]*pixels[1].red+cx[2]*
pixels[2].red+cx[3]*pixels[3].red)+cy[1]*(cx[0]*pixels[4].red+cx[1]*
pixels[5].red+cx[2]*pixels[6].red+cx[3]*pixels[7].red)+cy[2]*(cx[0]*
pixels[8].red+cx[1]*pixels[9].red+cx[2]*pixels[10].red+cx[3]*
pixels[11].red)+cy[3]*(cx[0]*pixels[12].red+cx[1]*pixels[13].red+cx[2]*
pixels[14].red+cx[3]*pixels[15].red));
pixel->green=(cy[0]*(cx[0]*pixels[0].green+cx[1]*pixels[1].green+cx[2]*
pixels[2].green+cx[3]*pixels[3].green)+cy[1]*(cx[0]*pixels[4].green+
cx[1]*pixels[5].green+cx[2]*pixels[6].green+cx[3]*pixels[7].green)+
cy[2]*(cx[0]*pixels[8].green+cx[1]*pixels[9].green+cx[2]*
pixels[10].green+cx[3]*pixels[11].green)+cy[3]*(cx[0]*pixels[12].green+
cx[1]*pixels[13].green+cx[2]*pixels[14].green+cx[3]*pixels[15].green));
pixel->blue=(cy[0]*(cx[0]*pixels[0].blue+cx[1]*pixels[1].blue+cx[2]*
pixels[2].blue+cx[3]*pixels[3].blue)+cy[1]*(cx[0]*pixels[4].blue+cx[1]*
pixels[5].blue+cx[2]*pixels[6].blue+cx[3]*pixels[7].blue)+cy[2]*(cx[0]*
pixels[8].blue+cx[1]*pixels[9].blue+cx[2]*pixels[10].blue+cx[3]*
pixels[11].blue)+cy[3]*(cx[0]*pixels[12].blue+cx[1]*pixels[13].blue+
cx[2]*pixels[14].blue+cx[3]*pixels[15].blue));
if (image->colorspace == CMYKColorspace)
pixel->black=(cy[0]*(cx[0]*pixels[0].black+cx[1]*pixels[1].black+cx[2]*
pixels[2].black+cx[3]*pixels[3].black)+cy[1]*(cx[0]*pixels[4].black+
cx[1]*pixels[5].black+cx[2]*pixels[6].black+cx[3]*pixels[7].black)+
cy[2]*(cx[0]*pixels[8].black+cx[1]*pixels[9].black+cx[2]*
pixels[10].black+cx[3]*pixels[11].black)+cy[3]*(cx[0]*
pixels[12].black+cx[1]*pixels[13].black+cx[2]*pixels[14].black+cx[3]*
pixels[15].black));
pixel->alpha=(cy[0]*(cx[0]*pixels[0].alpha+cx[1]*pixels[1].alpha+cx[2]*
pixels[2].alpha+cx[3]*pixels[3].alpha)+cy[1]*(cx[0]*pixels[4].alpha+
cx[1]*pixels[5].alpha+cx[2]*pixels[6].alpha+cx[3]*pixels[7].alpha)+
cy[2]*(cx[0]*pixels[8].alpha+cx[1]*pixels[9].alpha+cx[2]*
pixels[10].alpha+cx[3]*pixels[11].alpha)+cy[3]*(cx[0]*pixels[12].alpha+
cx[1]*pixels[13].alpha+cx[2]*pixels[14].alpha+cx[3]*pixels[15].alpha));
break;
}
}
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I s F u z z y E q u i v a l e n c e P i x e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsFuzzyEquivalencePixel() returns MagickTrue if the distance between two
% pixels is less than the specified distance in a linear three (or four)
% dimensional color space.
%
% The format of the IsFuzzyEquivalencePixel method is:
%
% void IsFuzzyEquivalencePixel(const Image *source,const Quantum *p,
% const Image *destination,const Quantum *q)
%
% A description of each parameter follows:
%
% o source: the source image.
%
% o p: Pixel p.
%
% o destination: the destination image.
%
% o q: Pixel q.
%
*/
MagickExport MagickBooleanType IsFuzzyEquivalencePixel(const Image *source,
const Quantum *p,const Image *destination,const Quantum *q)
{
double
distance,
fuzz,
pixel,
scale;
fuzz=GetFuzzyColorDistance(source,destination);
scale=1.0;
distance=0.0;
if ((source->alpha_trait != UndefinedPixelTrait) ||
(destination->alpha_trait != UndefinedPixelTrait))
{
/*
Transparencies are involved - set alpha distance.
*/
pixel=GetPixelAlpha(source,p)-(double) GetPixelAlpha(destination,q);
distance=pixel*pixel;
if (distance > fuzz)
return(MagickFalse);
/*
Generate a alpha scaling factor to generate a 4D cone on colorspace.
Note that if one color is transparent, distance has no color component.
*/
if (source->alpha_trait != UndefinedPixelTrait)
scale*=QuantumScale*GetPixelAlpha(source,p);
if (destination->alpha_trait != UndefinedPixelTrait)
scale*=QuantumScale*GetPixelAlpha(destination,q);
if (scale <= MagickEpsilon)
return(MagickTrue);
}
/*
RGB or CMY color cube.
*/
distance*=3.0; /* rescale appropriately */
fuzz*=3.0;
pixel=GetPixelRed(source,p)-(double) GetPixelRed(destination,q);
if (IsHueCompatibleColorspace(source->colorspace) != MagickFalse)
{
/*
Compute an arc distance for hue. It should be a vector angle of
'S'/'W' length with 'L'/'B' forming appropriate cones.
*/
if (fabs((double) pixel) > (QuantumRange/2))
pixel-=QuantumRange;
pixel*=2.0;
}
distance+=scale*pixel*pixel;
if (distance > fuzz)
return(MagickFalse);
pixel=GetPixelGreen(source,p)-(double) GetPixelGreen(destination,q);
distance+=scale*pixel*pixel;
if (distance > fuzz)
return(MagickFalse);
pixel=GetPixelBlue(source,p)-(double) GetPixelBlue(destination,q);
distance+=scale*pixel*pixel;
if (distance > fuzz)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ I s F u z z y E q u i v a l e n c e P i x e l I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsFuzzyEquivalencePixelInfo() returns true if the distance between two
% colors is less than the specified distance in a linear three (or four)
% dimensional color space.
%
% This implements the equivalent of:
% fuzz < sqrt(color_distance^2 * u.a*v.a + alpha_distance^2)
%
% Which produces a multi-dimensional cone for that colorspace along the
% transparency vector.
%
% For example for an RGB:
% color_distance^2 = ( (u.r-v.r)^2 + (u.g-v.g)^2 + (u.b-v.b)^2 ) / 3
%
% See https://imagemagick.org/Usage/bugs/fuzz_distance/
%
% Hue colorspace distances need more work. Hue is not a distance, it is an
% angle!
%
% A check that q is in the same color space as p should be made and the
% appropriate mapping made. -- Anthony Thyssen 8 December 2010
%
% The format of the IsFuzzyEquivalencePixelInfo method is:
%
% MagickBooleanType IsFuzzyEquivalencePixelInfo(const PixelInfo *p,
% const PixelInfo *q)
%
% A description of each parameter follows:
%
% o p: Pixel p.
%
% o q: Pixel q.
%
*/
MagickExport MagickBooleanType IsFuzzyEquivalencePixelInfo(const PixelInfo *p,
const PixelInfo *q)
{
double
fuzz,
pixel;
double
scale,
distance;
fuzz=(double) MagickMax(MagickMax(p->fuzz,q->fuzz),(MagickRealType)
MagickSQ1_2);
fuzz*=fuzz;
scale=1.0;
distance=0.0;
if ((p->alpha_trait != UndefinedPixelTrait) ||
(q->alpha_trait != UndefinedPixelTrait))
{
/*
Transparencies are involved - set alpha distance.
*/
pixel=(p->alpha_trait != UndefinedPixelTrait ? p->alpha : OpaqueAlpha)-
(q->alpha_trait != UndefinedPixelTrait ? q->alpha : OpaqueAlpha);
distance=pixel*pixel;
if (distance > fuzz)
return(MagickFalse);
/*
Generate a alpha scaling factor to generate a 4D cone on colorspace.
If one color is transparent, distance has no color component.
*/
if (p->alpha_trait != UndefinedPixelTrait)
scale=(QuantumScale*p->alpha);
if (q->alpha_trait != UndefinedPixelTrait)
scale*=(QuantumScale*q->alpha);
if (scale <= MagickEpsilon )
return(MagickTrue);
}
/*
CMYK create a CMY cube with a multi-dimensional cone toward black.
*/
if (p->colorspace == CMYKColorspace)
{
pixel=p->black-q->black;
distance+=pixel*pixel*scale;
if (distance > fuzz)
return(MagickFalse);
scale*=(double) (QuantumScale*(QuantumRange-p->black));
scale*=(double) (QuantumScale*(QuantumRange-q->black));
}
/*
RGB or CMY color cube.
*/
distance*=3.0; /* rescale appropriately */
fuzz*=3.0;
pixel=p->red-q->red;
if (IsHueCompatibleColorspace(p->colorspace) != MagickFalse)
{
/*
This calculates a arc distance for hue-- it should be a vector
angle of 'S'/'W' length with 'L'/'B' forming appropriate cones.
In other words this is a hack - Anthony.
*/
if (fabs((double) pixel) > (QuantumRange/2))
pixel-=QuantumRange;
pixel*=2.0;
}
distance+=pixel*pixel*scale;
if (distance > fuzz)
return(MagickFalse);
pixel=p->green-q->green;
distance+=pixel*pixel*scale;
if (distance > fuzz)
return(MagickFalse);
pixel=p->blue-q->blue;
distance+=pixel*pixel*scale;
if (distance > fuzz)
return(MagickFalse);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t P i x e l C h a n n e l M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelChannelMask() sets the pixel channel map from the specified channel
% mask.
%
% The format of the SetPixelChannelMask method is:
%
% ChannelType SetPixelChannelMask(Image *image,
% const ChannelType channel_mask)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel_mask: the channel mask.
%
*/
static void LogPixelChannels(const Image *image)
{
ssize_t
i;
(void) LogMagickEvent(PixelEvent,GetMagickModule(),"%s[%08x]",
image->filename,image->channel_mask);
for (i=0; i < (ssize_t) image->number_channels; i++)
{
char
channel_name[MagickPathExtent],
traits[MagickPathExtent];
const char
*name;
PixelChannel
channel;
channel=GetPixelChannelChannel(image,i);
switch (channel)
{
case RedPixelChannel:
{
name="red";
if (image->colorspace == CMYKColorspace)
name="cyan";
if ((image->colorspace == LinearGRAYColorspace) ||
(image->colorspace == GRAYColorspace))
name="gray";
break;
}
case GreenPixelChannel:
{
name="green";
if (image->colorspace == CMYKColorspace)
name="magenta";
break;
}
case BluePixelChannel:
{
name="blue";
if (image->colorspace == CMYKColorspace)
name="yellow";
break;
}
case BlackPixelChannel:
{
name="black";
if (image->storage_class == PseudoClass)
name="index";
break;
}
case IndexPixelChannel:
{
name="index";
break;
}
case AlphaPixelChannel:
{
name="alpha";
break;
}
case ReadMaskPixelChannel:
{
name="read-mask";
break;
}
case WriteMaskPixelChannel:
{
name="write-mask";
break;
}
case CompositeMaskPixelChannel:
{
name="composite-mask";
break;
}
case MetaPixelChannel:
{
name="meta";
break;
}
default:
name="undefined";
}
if (image->colorspace == UndefinedColorspace)
{
(void) FormatLocaleString(channel_name,MagickPathExtent,"%.20g",
(double) channel);
name=(const char *) channel_name;
}
*traits='\0';
if ((GetPixelChannelTraits(image,channel) & UpdatePixelTrait) != 0)
(void) ConcatenateMagickString(traits,"update,",MagickPathExtent);
if ((GetPixelChannelTraits(image,channel) & BlendPixelTrait) != 0)
(void) ConcatenateMagickString(traits,"blend,",MagickPathExtent);
if ((GetPixelChannelTraits(image,channel) & CopyPixelTrait) != 0)
(void) ConcatenateMagickString(traits,"copy,",MagickPathExtent);
if (*traits == '\0')
(void) ConcatenateMagickString(traits,"undefined,",MagickPathExtent);
traits[strlen(traits)-1]='\0';
(void) LogMagickEvent(PixelEvent,GetMagickModule()," %.20g: %s (%s)",
(double) i,name,traits);
}
}
MagickExport ChannelType SetPixelChannelMask(Image *image,
const ChannelType channel_mask)
{
#define GetChannelBit(mask,bit) (((size_t) (mask) >> (size_t) (bit)) & 0x01)
ChannelType
mask;
ssize_t
i;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(PixelEvent,GetMagickModule(),"%s[%08x]",
image->filename,channel_mask);
mask=image->channel_mask;
image->channel_mask=channel_mask;
for (i=0; i < (ssize_t) GetPixelChannels(image); i++)
{
PixelChannel channel = GetPixelChannelChannel(image,i);
if (GetChannelBit(channel_mask,channel) == 0)
{
SetPixelChannelTraits(image,channel,CopyPixelTrait);
continue;
}
if (channel == AlphaPixelChannel)
{
if ((image->alpha_trait & CopyPixelTrait) != 0)
{
SetPixelChannelTraits(image,channel,CopyPixelTrait);
continue;
}
SetPixelChannelTraits(image,channel,UpdatePixelTrait);
continue;
}
if (image->alpha_trait != UndefinedPixelTrait)
{
SetPixelChannelTraits(image,channel,(const PixelTrait)
(UpdatePixelTrait | BlendPixelTrait));
continue;
}
SetPixelChannelTraits(image,channel,UpdatePixelTrait);
}
if (image->storage_class == PseudoClass)
SetPixelChannelTraits(image,IndexPixelChannel,CopyPixelTrait);
if ((image->channels & ReadMaskChannel) != 0)
SetPixelChannelTraits(image,ReadMaskPixelChannel,CopyPixelTrait);
if ((image->channels & WriteMaskChannel) != 0)
SetPixelChannelTraits(image,WriteMaskPixelChannel,CopyPixelTrait);
if ((image->channels & CompositeMaskChannel) != 0)
SetPixelChannelTraits(image,CompositeMaskPixelChannel,CopyPixelTrait);
if (image->debug != MagickFalse)
LogPixelChannels(image);
return(mask);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S e t P i x e l M e t a C h a n n e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SetPixelMetaChannels() sets the image meta channels.
%
% The format of the SetPixelMetaChannels method is:
%
% MagickBooleanType SetPixelMetaChannels(Image *image,
% const size_t number_meta_channels,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o number_meta_channels: the number of meta channels.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType SetPixelMetaChannels(Image *image,
const size_t number_meta_channels,ExceptionInfo *exception)
{
image->number_meta_channels=number_meta_channels;
InitializePixelChannelMap(image);
return(SyncImagePixelCache(image,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% S o r t I m a g e P i x e l s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% SortImagePixels() sorts pixels within each scanline in ascending order of
% intensity.
%
% The format of the SortImagePixels method is:
%
% MagickBooleanType SortImagePixels(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 SortImagePixels(Image *image,
ExceptionInfo *exception)
{
#define SolarizeImageTag "Solarize/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
/*
Sort image pixels.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
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-1; x++)
{
MagickRealType
current,
previous;
ssize_t
j;
previous=GetPixelIntensity(image,q);
for (j=0; j < (ssize_t) (image->columns-x-1); j++)
{
current=GetPixelIntensity(image,q+(j+1)*GetPixelChannels(image));
if (previous > current)
{
Quantum
pixel[MaxPixelChannels];
/*
Swap adjacent pixels.
*/
(void) memcpy(pixel,q+j*GetPixelChannels(image),
GetPixelChannels(image)*sizeof(Quantum));
(void) memcpy(q+j*GetPixelChannels(image),q+(j+1)*
GetPixelChannels(image),GetPixelChannels(image)*sizeof(Quantum));
(void) memcpy(q+(j+1)*GetPixelChannels(image),pixel,
GetPixelChannels(image)*sizeof(Quantum));
}
else
previous=current;
}
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp atomic
#endif
progress++;
proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
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-2021 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
*next;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelChannels
**magick_restrict evaluate_pixels;
RandomInfo
**magick_restrict random_info;
size_t
number_images;
ssize_t
j,
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);
}
next=images;
for (j=0; j < (ssize_t) number_images; j++)
{
image_view[j]=AcquireVirtualCacheView(next,exception);
next=GetNextImageInList(next);
}
/*
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 Image
*next;
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++)
{
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(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;
ssize_t
i,
x;
PixelChannels
*evaluate_pixel;
Quantum
*magick_restrict q;
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++)
{
ssize_t
i;
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++)
{
ssize_t
j;
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(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 (j=0; j < (ssize_t) number_images; j++)
image_view[j]=DestroyCacheView(image_view[j]);
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;
MagickBooleanType
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;
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]=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/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.
%
*/
static size_t GetImageChannels(const Image *image)
{
ssize_t
i;
size_t
channels;
channels=0;
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;
channels++;
}
return((size_t) (channels == 0 ? 1 : channels));
}
MagickExport ChannelMoments *GetImageMoments(const Image *image,
ExceptionInfo *exception)
{
#define MaxNumberImageMoments 8
CacheView
*image_view;
ChannelMoments
*channel_moments;
double
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
channel,
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 (channel=0; channel <= MaxPixelChannels; channel++)
{
/*
Compute center of mass (centroid).
*/
centroid[channel].x=M10[channel]*PerceptibleReciprocal(M00[channel]);
centroid[channel].y=M01[channel]*PerceptibleReciprocal(M00[channel]);
}
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);
}
}
M00[MaxPixelChannels]/=GetImageChannels(image);
M01[MaxPixelChannels]/=GetImageChannels(image);
M02[MaxPixelChannels]/=GetImageChannels(image);
M03[MaxPixelChannels]/=GetImageChannels(image);
M10[MaxPixelChannels]/=GetImageChannels(image);
M11[MaxPixelChannels]/=GetImageChannels(image);
M12[MaxPixelChannels]/=GetImageChannels(image);
M20[MaxPixelChannels]/=GetImageChannels(image);
M21[MaxPixelChannels]/=GetImageChannels(image);
M22[MaxPixelChannels]/=GetImageChannels(image);
M30[MaxPixelChannels]/=GetImageChannels(image);
for (channel=0; channel <= MaxPixelChannels; channel++)
{
/*
Compute elliptical angle, major and minor axes, eccentricity, & intensity.
*/
channel_moments[channel].centroid=centroid[channel];
channel_moments[channel].ellipse_axis.x=sqrt((2.0*
PerceptibleReciprocal(M00[channel]))*((M20[channel]+M02[channel])+
sqrt(4.0*M11[channel]*M11[channel]+(M20[channel]-M02[channel])*
(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_axis.y=sqrt((2.0*
PerceptibleReciprocal(M00[channel]))*((M20[channel]+M02[channel])-
sqrt(4.0*M11[channel]*M11[channel]+(M20[channel]-M02[channel])*
(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_angle=RadiansToDegrees(1.0/2.0*atan(2.0*
M11[channel]*PerceptibleReciprocal(M20[channel]-M02[channel])));
if (fabs(M11[channel]) < 0.0)
{
if ((fabs(M20[channel]-M02[channel]) >= 0.0) &&
((M20[channel]-M02[channel]) < 0.0))
channel_moments[channel].ellipse_angle+=90.0;
}
else
if (M11[channel] < 0.0)
{
if (fabs(M20[channel]-M02[channel]) >= 0.0)
{
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=180.0;
}
}
else
if ((fabs(M20[channel]-M02[channel]) >= 0.0) &&
((M20[channel]-M02[channel]) < 0.0))
channel_moments[channel].ellipse_angle+=90.0;
channel_moments[channel].ellipse_eccentricity=sqrt(1.0-(
channel_moments[channel].ellipse_axis.y*
channel_moments[channel].ellipse_axis.y*PerceptibleReciprocal(
channel_moments[channel].ellipse_axis.x*
channel_moments[channel].ellipse_axis.x)));
channel_moments[channel].ellipse_intensity=M00[channel]*
PerceptibleReciprocal(MagickPI*channel_moments[channel].ellipse_axis.x*
channel_moments[channel].ellipse_axis.y+MagickEpsilon);
}
for (channel=0; channel <= MaxPixelChannels; channel++)
{
/*
Normalize image moments.
*/
M10[channel]=0.0;
M01[channel]=0.0;
M11[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(1.0+1.0)/2.0));
M20[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+0.0)/2.0));
M02[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(0.0+2.0)/2.0));
M21[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+1.0)/2.0));
M12[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(1.0+2.0)/2.0));
M22[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(2.0+2.0)/2.0));
M30[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(3.0+0.0)/2.0));
M03[channel]*=PerceptibleReciprocal(pow(M00[channel],1.0+(0.0+3.0)/2.0));
M00[channel]=1.0;
}
image_view=DestroyCacheView(image_view);
for (channel=0; channel <= MaxPixelChannels; channel++)
{
/*
Compute Hu invariant moments.
*/
channel_moments[channel].invariant[0]=M20[channel]+M02[channel];
channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])*
(M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel];
channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])*
(M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])*
(3.0*M21[channel]-M03[channel]);
channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])+(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]);
channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])*
((M30[channel]+M12[channel])*(M30[channel]+M12[channel])-
(M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+
4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]);
channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+
M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])*
(M03[channel]+M21[channel]))-(M20[channel]-M02[channel])*
(M30[channel]+M12[channel])*(M03[channel]+M21[channel]);
}
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,
*histogram,
standard_deviation;
MagickStatusType
status;
MemoryInfo
*median_info;
Quantum
*median;
QuantumAny
range;
ssize_t
i;
size_t
depth;
ssize_t
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++)
{
ssize_t
i;
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
{
ssize_t
i;
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;
}
channel_statistics[CompositePixelChannel].mean/=(double)
GetImageChannels(image);
channel_statistics[CompositePixelChannel].median/=(double)
GetImageChannels(image);
channel_statistics[CompositePixelChannel].standard_deviation/=(double)
GetImageChannels(image);
channel_statistics[CompositePixelChannel].entropy/=(double)
GetImageChannels(image);
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();
ssize_t
i,
x;
PixelChannels
*polynomial_pixel;
Quantum
*magick_restrict q;
ssize_t
j;
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++)
{
ssize_t
i;
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++)
{
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]=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 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);
}
|
3214.c | /* POLYBENCH/GPU-OPENMP
*
* This file is a part of the Polybench/GPU-OpenMP suite
*
* Contact:
* William Killian <killian@udel.edu>
*
* Copyright 2013, The University of Delaware
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 4000. */
#include "atax.h"
/* Array initialization. */
static
void init_array (int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny))
{
int i, j;
for (i = 0; i < ny; i++)
x[i] = i * M_PI;
for (i = 0; i < nx; i++)
for (j = 0; j < ny; j++)
A[i][j] = ((DATA_TYPE) i*(j+1)) / nx;
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static
void print_array(int nx,
DATA_TYPE POLYBENCH_1D(y,NX,nx))
{
int i;
for (i = 0; i < nx; i++) {
fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]);
if (i % 20 == 0) fprintf (stderr, "\n");
}
fprintf (stderr, "\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static
void kernel_atax(int nx, int ny,
DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny),
DATA_TYPE POLYBENCH_1D(x,NY,ny),
DATA_TYPE POLYBENCH_1D(y,NY,ny),
DATA_TYPE POLYBENCH_1D(tmp,NX,nx))
{
int i, j;
#pragma scop
{
#pragma omp target teams distribute schedule(static, 8)
for (i = 0; i < _PB_NY; i++)
{
y[i] = 0;
}
#pragma omp target teams distribute schedule(static, 8)
for (i = 0; i < _PB_NX; i++)
{
tmp[i] = 0;
for (j = 0; j < _PB_NY; j++)
tmp[i] = tmp[i] + A[i][j] * x[j];
for (j = 0; j < _PB_NY; j++)
y[j] = y[j] + A[i][j] * tmp[i];
}
}
#pragma endscop
}
int main(int argc, char** argv)
{
/* Retrieve problem size. */
int nx = NX;
int ny = NY;
/* Variable declaration/allocation. */
POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny);
POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny);
POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx);
/* Initialize array(s). */
init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x));
/* Start timer. */
polybench_start_instruments;
/* Run kernel. */
kernel_atax (nx, ny,
POLYBENCH_ARRAY(A),
POLYBENCH_ARRAY(x),
POLYBENCH_ARRAY(y),
POLYBENCH_ARRAY(tmp));
/* Stop and print timer. */
polybench_stop_instruments;
polybench_print_instruments;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
polybench_prevent_dce(print_array(nx, POLYBENCH_ARRAY(y)));
/* Be clean. */
POLYBENCH_FREE_ARRAY(A);
POLYBENCH_FREE_ARRAY(x);
POLYBENCH_FREE_ARRAY(y);
POLYBENCH_FREE_ARRAY(tmp);
return 0;
}
|
gemv_c_csr_conj.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
#include <memory.h>
static alphasparse_status_t
gemv_csr_trans_serial(const ALPHA_Number alpha,
const ALPHA_SPMAT_CSR *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
const ALPHA_INT m = A->rows;
for (ALPHA_INT i = 0; i < m; ++i)
{
for (ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ai++)
{
ALPHA_Number val;
cmp_conj(val, A->values[ai]);
alpha_mul(val, alpha, val);
alpha_madde(y[A->col_indx[ai]], val, x[i]);
}
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
static alphasparse_status_t
gemv_csr_trans_omp(const ALPHA_Number alpha,
const ALPHA_SPMAT_CSR *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
const ALPHA_INT m = A->rows;
const ALPHA_INT n = A->cols;
const ALPHA_INT thread_num = alpha_get_thread_num();
ALPHA_INT partition[thread_num + 1];
balanced_partition_row_by_nnz(A->rows_end, m, thread_num, partition);
ALPHA_Number **tmp = (ALPHA_Number **)malloc(sizeof(ALPHA_Number *) * thread_num);
#ifdef _OPENMP
#pragma omp parallel num_threads(thread_num)
#endif
{
const ALPHA_INT tid = alpha_get_thread_id();
const ALPHA_INT local_m_s = partition[tid];
const ALPHA_INT local_m_e = partition[tid + 1];
tmp[tid] = (ALPHA_Number *)malloc(sizeof(ALPHA_Number) * n);
memset(tmp[tid],'\0',sizeof(ALPHA_Number) * n);
for (ALPHA_INT i = local_m_s; i < local_m_e; ++i)
{
const ALPHA_Number x_r = x[i];
int pkl = A->rows_start[i];
int pke = A->rows_end[i];
for (; pkl < pke - 3; pkl += 4)
{
ALPHA_Number conj0, conj1, conj2, conj3;
cmp_conj(conj0, A->values[pkl]);
cmp_conj(conj1, A->values[pkl+1]);
cmp_conj(conj2, A->values[pkl+2]);
cmp_conj(conj3, A->values[pkl+3]);
alpha_madde(tmp[tid][A->col_indx[pkl]], conj0, x_r);
alpha_madde(tmp[tid][A->col_indx[pkl + 1]], conj1, x_r);
alpha_madde(tmp[tid][A->col_indx[pkl + 2]], conj2, x_r);
alpha_madde(tmp[tid][A->col_indx[pkl + 3]], conj3, x_r);
}
for (; pkl < pke; ++pkl)
{
ALPHA_Number conj0;
alpha_conj(conj0, A->values[pkl]);
alpha_madde(tmp[tid][A->col_indx[pkl]], conj0, x_r);
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < n; ++i)
{
ALPHA_Number tmp_y;
alpha_setzero(tmp_y);
for (ALPHA_INT j = 0; j < thread_num; ++j)
{
alpha_adde(tmp_y, tmp[j][i]);
}
alpha_mule(y[i],beta);
alpha_madde(y[i],alpha,tmp_y);
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < thread_num; ++i)
{
alpha_free(tmp[i]);
}
alpha_free(tmp);
return ALPHA_SPARSE_STATUS_SUCCESS;
}
alphasparse_status_t
ONAME(const ALPHA_Number alpha,
const ALPHA_SPMAT_CSR *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
return gemv_csr_trans_omp(alpha, A, x, beta, y);
}
|
omp_task.c | // RUN: %libomp-compile-and-run
#include <stdio.h>
#include <math.h>
#include "omp_testsuite.h"
#include "omp_my_sleep.h"
int test_omp_task()
{
int tids[NUM_TASKS];
int i;
#pragma omp parallel
{
#pragma omp single
{
for (i = 0; i < NUM_TASKS; i++) {
/* First we have to store the value of the loop index in a new variable
* which will be private for each task because otherwise it will be overwritten
* if the execution of the task takes longer than the time which is needed to
* enter the next step of the loop!
*/
int myi;
myi = i;
#pragma omp task
{
my_sleep (SLEEPTIME);
tids[myi] = omp_get_thread_num();
} /* end of omp task */
} /* end of for */
} /* end of single */
} /*end of parallel */
/* Now we ckeck if more than one thread executed the tasks. */
for (i = 1; i < NUM_TASKS; i++) {
if (tids[0] != tids[i])
return 1;
}
return 0;
} /* end of check_parallel_for_private */
int main()
{
int i;
int num_failed=0;
for(i = 0; i < REPETITIONS; i++) {
if(!test_omp_task()) {
num_failed++;
}
}
return num_failed;
}
|
targc-spmd.c | #include <omp.h>
#include <stdio.h>
int main (){
#define N 1024
double x_d[N];
for (size_t i = 0; i < N; ++i)
x_d[i] = -1;
printf("x_d = %p\n",x_d);
#pragma omp target teams distribute parallel for
for (size_t i = 0; i < N; ++i)
x_d[i] = i;
printf("x_d[1] = %f\n", x_d[1]);
return 0;
}
|
GB_binop__lxor_fp64.c | //------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB)
// A.*B function (eWiseMult): GB (_AemultB_02__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_03__lxor_fp64)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__lxor_fp64)
// A*D function (colscale): GB (_AxD__lxor_fp64)
// D*A function (rowscale): GB (_DxB__lxor_fp64)
// C+=B function (dense accum): GB (_Cdense_accumB__lxor_fp64)
// C+=b function (dense accum): GB (_Cdense_accumb__lxor_fp64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__lxor_fp64)
// C=scalar+B GB (_bind1st__lxor_fp64)
// C=scalar+B' GB (_bind1st_tran__lxor_fp64)
// C=A+scalar GB (_bind2nd__lxor_fp64)
// C=A'+scalar GB (_bind2nd_tran__lxor_fp64)
// C type: double
// A type: double
// B,b type: double
// BinaryOp: cij = ((aij != 0) != (bij != 0))
#define GB_ATYPE \
double
#define GB_BTYPE \
double
#define GB_CTYPE \
double
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
double aij = Ax [pA]
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB) \
double bij = Bx [pB]
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
double t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA) \
cij = Ax [pA]
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB) \
cij = Bx [pB]
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z, x, y, i, j) \
z = ((x != 0) != (y != 0)) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_LXOR || GxB_NO_FP64 || GxB_NO_LXOR_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
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_ewise3_noaccum__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_dense_ewise3_noaccum_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__lxor_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__lxor_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__lxor_fp64)
(
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
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_colscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
GrB_Info GB (_DxB__lxor_fp64)
(
GrB_Matrix C,
const GrB_Matrix D, bool D_is_pattern,
const GrB_Matrix B, bool B_is_pattern,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *restrict Cx = (double *) C->x ;
#include "GB_AxB_rowscale_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseAdd: C = A+B or C<M> = A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__lxor_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 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_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_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_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_03__lxor_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_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_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__lxor_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 anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
double *Cx = (double *) Cx_output ;
double x = (*((double *) x_input)) ;
double *Bx = (double *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Bb, p)) continue ;
double bij = Bx [p] ;
Cx [p] = ((x != 0) != (bij != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__lxor_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 = Ax [p] ;
Cx [p] = ((aij != 0) != (y != 0)) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
double aij = Ax [pA] ; \
Cx [pC] = ((x != 0) != (aij != 0)) ; \
}
GrB_Info GB (_bind1st_tran__lxor_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 = Ax [pA] ; \
Cx [pC] = ((aij != 0) != (y != 0)) ; \
}
GrB_Info GB (_bind2nd_tran__lxor_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
|
target-34.c | extern void abort (void);
int
main ()
{
int a = 1, b = 2, c = 4, d[7];
#pragma omp parallel
{
#pragma omp single
{
#pragma omp taskgroup
{
#pragma omp target enter data nowait map (to: a, b, c) depend(out: d[0])
#pragma omp target nowait map (alloc: a, b) depend(in: d[0]) depend(out: d[1])
{
#pragma omp atomic update
a |= 4;
#pragma omp atomic update
b |= 8;
}
#pragma omp target nowait map (alloc: a, c) depend(in: d[0]) depend(out: d[2])
{
#pragma omp atomic update
a |= 16;
#pragma omp atomic update
c |= 32;
}
#pragma omp target exit data nowait map (from: a, b, c) depend(in: d[1], d[2])
}
if (a != 21 || b != 10 || c != 36)
abort ();
#pragma omp target map (tofrom: a, b) nowait
{
a &= ~16;
b &= ~2;
}
#pragma omp target map (tofrom: c) nowait
{
c |= 8;
}
} /* Implicit barrier here. */
#pragma omp single
{
if (a != 5 || b != 8 || c != 44)
abort ();
#pragma omp target map (tofrom: a, b) nowait
{
a |= 32;
b |= 4;
}
#pragma omp target map (tofrom: c) nowait
c &= ~4;
#pragma omp taskwait
if (a != 37 || b != 12 || c != 40)
abort ();
#pragma omp target nowait map (tofrom: a, b) depend(out: d[3])
{
#pragma omp atomic update
a = a + 9;
b -= 8;
}
#pragma omp target nowait map (tofrom: a, c) depend(out: d[4])
{
#pragma omp atomic update
a = a + 4;
c >>= 1;
}
#pragma omp task if (0) depend (in: d[3], d[4]) shared (a, b, c)
if (a != 50 || b != 4 || c != 20)
abort ();
#pragma omp task shared (a)
a += 50;
#pragma omp target nowait map (tofrom: b)
b++;
#pragma omp target map (tofrom: c) nowait
c--;
#pragma omp taskwait
if (a != 100 || b != 5 || c != 19)
abort ();
#pragma omp target map (tofrom: a) nowait depend(out: d[5])
a++;
#pragma omp target map (tofrom: b) nowait depend(out: d[6])
b++;
#pragma omp target map (tofrom: a, b) depend(in: d[5], d[6])
{
if (a != 101 || b != 6)
a = -9;
else
{
a = 24;
b = 38;
}
}
if (a != 24 || b != 38)
abort ();
} /* Implicit barrier here. */
#pragma omp master
{
#pragma omp target nowait map (tofrom: a, b)
{
a *= 2;
b++;
}
#pragma omp target map (tofrom: c) nowait
c--;
}
#pragma omp barrier
if (a != 48 || b != 39 || c != 18)
abort ();
}
return 0;
}
|
GB_subref_template.c | //------------------------------------------------------------------------------
// GB_subref_template: C = A(I,J), or C = pattern (A(I,J))
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#if defined ( GB_SYMBOLIC )
// symbolic method must tolerate zombies
#define GB_Ai(p) GBI_UNFLIP (Ai, p, avlen)
#else
// numeric method will not see any zombies
#define GB_Ai(p) GBI (Ai, p, avlen)
#endif
// to iterate across all entries in a bucket:
#define GB_for_each_index_in_bucket(inew,i) \
for (int64_t inew = Mark[i]-1 ; inew >= 0 ; inew = Inext [inew])
// copy values from A(:,kA) to C(:,kC): Cx [pC:pC+len-1] = ... (pA:pA+len-1).
#if defined ( GB_SYMBOLIC )
// symbolic copy: Cx is int64_t; Ax is ignored
#define GB_COPY_RANGE(pC,pA,len) \
for (int64_t k = 0 ; k < (len) ; k++) \
{ \
Cx [(pC) + k] = (pA) + k ; \
}
#else
// numeric copy: Cx and Ax are both (GB_void *), and point to the same type
#define GB_COPY_RANGE(pC,pA,len) \
memcpy (Cx + (pC)*asize, Ax + (pA)*asize, (len) * asize) ;
#endif
// copy a single value from A(:,kA) to C(:,kC): Cx [pC] = ... (pA])
#if defined ( GB_SYMBOLIC )
// symbolic copy: Cx is int64_t; Ax is ignored
#define GB_COPY_ENTRY(pC,pA) \
Cx [pC] = (pA) ;
#else
// numeric copy: Cx and Ax are both (GB_void *), and point to the same type
#define GB_COPY_ENTRY(pC,pA) \
/* Cx [pC] = Ax [pA] */ \
memcpy (Cx + (pC)*asize, Ax + (pA)*asize, asize) ;
#endif
// the type of Cx
#if defined ( GB_SYMBOLIC )
// C is an int64_t array; the type of A is ignored
#define GB_CTYPE int64_t
#define GB_CSIZE1 1
#define GB_CSIZE2 (sizeof (int64_t))
#else
// C and A have the same type
#define GB_CTYPE GB_void
#define GB_CSIZE1 asize
#define GB_CSIZE2 asize
#endif
{
//--------------------------------------------------------------------------
// get A
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Ai = A->i ;
const int64_t avlen = A->vlen ;
#if defined ( GB_SYMBOLIC )
const int64_t nzombies = A->nzombies ;
#endif
#if defined ( GB_PHASE_2_OF_2 ) && defined ( GB_NUMERIC )
ASSERT (C->type = A->type) ;
const GB_void *GB_RESTRICT Ax = (GB_void *) A->x ;
const int64_t asize = A->type->size ;
#endif
//--------------------------------------------------------------------------
// get C
//--------------------------------------------------------------------------
#if defined ( GB_PHASE_2_OF_2 )
int64_t *GB_RESTRICT Ci = C->i ;
GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ;
#endif
//--------------------------------------------------------------------------
// get I
//--------------------------------------------------------------------------
// these values are ignored if Ikind == GB_LIST
int64_t ibegin = Icolon [GxB_BEGIN] ;
int64_t iinc = Icolon [GxB_INC ] ;
int64_t inc = (iinc < 0) ? (-iinc) : iinc ;
#ifdef GB_DEBUG
int64_t iend = Icolon [GxB_END ] ;
#endif
//--------------------------------------------------------------------------
// phase1: count entries in each C(:,kC); phase2: compute C
//--------------------------------------------------------------------------
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
int64_t kfirst = TaskList [taskid].kfirst ;
int64_t klast = TaskList [taskid].klast ;
bool fine_task = (klast < 0) ;
if (fine_task)
{
// a fine task operates on a slice of a single vector
klast = kfirst ;
}
// a coarse task accesses all of I for all its vectors
int64_t pI = 0 ;
int64_t pI_end = nI ;
int64_t ilen = nI ;
ASSERT (0 <= kfirst && kfirst <= klast && klast < Cnvec) ;
//----------------------------------------------------------------------
// compute all vectors C(:,kfirst:klast) for this task
//----------------------------------------------------------------------
for (int64_t kC = kfirst ; kC <= klast ; kC++)
{
//------------------------------------------------------------------
// get C(:,kC)
//------------------------------------------------------------------
#if defined ( GB_PHASE_1_OF_2 )
// phase1 simply counts the # of entries in C(*,kC).
int64_t clen = 0 ;
#else
// This task computes all or part of C(:,kC), which are the entries
// in Ci,Cx [pC:pC_end-1].
int64_t pC, pC_end ;
if (fine_task)
{
// A fine task computes a slice of C(:,kC)
pC = TaskList [taskid ].pC ;
pC_end = TaskList [taskid+1].pC ;
ASSERT (Cp [kC] <= pC && pC <= pC_end && pC_end <= Cp [kC+1]) ;
}
else
{
// The vectors of C are never sliced for a coarse task, so this
// task computes all of C(:,kC).
pC = Cp [kC] ;
pC_end = Cp [kC+1] ;
}
int64_t clen = pC_end - pC ;
if (clen == 0) continue ;
#endif
//------------------------------------------------------------------
// get A(:,kA)
//------------------------------------------------------------------
int64_t pA, pA_end ;
if (fine_task)
{
// a fine task computes a slice of a single vector C(:,kC).
// The task accesses Ai,Ax [pA:pA_end-1], which holds either
// the entire vector A(imin:imax,kA) for method 6, the entire
// dense A(:,kA) for methods 1 and 2, or a slice of the
// A(imin:max,kA) vector for all other methods.
pA = TaskList [taskid].pA ;
pA_end = TaskList [taskid].pA_end ;
}
else
{
// a coarse task computes the entire vector C(:,kC). The task
// accesses all of A(imin:imax,kA), for most methods, or all of
// A(:,kA) for methods 1 and 2. The vector A(*,kA) appears in
// Ai,Ax [pA:pA_end-1].
pA = Ap_start [kC] ;
pA_end = Ap_end [kC] ;
}
int64_t alen = pA_end - pA ;
if (alen == 0) continue ;
//------------------------------------------------------------------
// get I
//------------------------------------------------------------------
if (fine_task)
{
// A fine task accesses I [pI:pI_end-1]. For methods 2 and 6,
// pI:pI_end is a subset of the entire 0:nI-1 list. For all
// other methods, pI = 0 and pI_end = nI, and the task can
// access all of I.
pI = TaskList [taskid].pB ;
pI_end = TaskList [taskid].pB_end ;
ilen = pI_end - pI ;
}
//------------------------------------------------------------------
// determine the method to use
//------------------------------------------------------------------
int method ;
if (fine_task)
{
// The method that the fine task uses for its slice of A(*,kA)
// and C(*,kC) has already been determined by GB_subref_slice.
method = (int) (-TaskList [taskid].klast) ;
}
else
{
// determine the method based on A(*,kA) and I
method = GB_subref_method (NULL, NULL, alen, avlen, Ikind, nI,
(Mark != NULL), need_qsort, iinc, nduplicates) ;
}
//------------------------------------------------------------------
// extract C (:,kC) = A (I,kA): consider all cases
//------------------------------------------------------------------
switch (method)
{
//--------------------------------------------------------------
case 1 : // C(:,kC) = A(:,kA) where A(:,kA) is dense
//--------------------------------------------------------------
// A (:,kA) has not been sliced
ASSERT (Ikind == GB_ALL) ;
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// copy the entire vector and construct indices
#if defined ( GB_PHASE_1_OF_2 )
clen = ilen ;
#else
for (int64_t k = 0 ; k < ilen ; k++)
{
int64_t inew = k + pI ;
ASSERT (inew == GB_ijlist (I, inew, Ikind, Icolon)) ;
ASSERT (inew == GB_Ai (pA + inew)) ;
Ci [pC + k] = inew ;
}
GB_COPY_RANGE (pC, pA + pI, ilen) ;
#endif
break ;
//--------------------------------------------------------------
case 2 : // C(:,kC) = A(I,kA) where A(I,kA) is dense
//--------------------------------------------------------------
// This method handles any kind of list I, but A(:,kA)
// must be dense. A(:,kA) has not been sliced.
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// scan I and get the entry in A(:,kA) via direct lookup
#if defined ( GB_PHASE_1_OF_2 )
clen = ilen ;
#else
for (int64_t k = 0 ; k < ilen ; k++)
{
// C(inew,kC) = A(i,kA), and it always exists.
int64_t inew = k + pI ;
int64_t i = GB_ijlist (I, inew, Ikind, Icolon) ;
ASSERT (i == GB_Ai (pA + i)) ;
Ci [pC + k] = inew ;
GB_COPY_ENTRY (pC + k, pA + i) ;
}
#endif
break ;
//--------------------------------------------------------------
case 3 : // the list I has a single index, ibegin
//--------------------------------------------------------------
// binary search in GB_subref_phase0 has already found it.
// This can be any Ikind with nI=1: GB_ALL with A->vlen=1,
// GB_RANGE with ibegin==iend, GB_STRIDE such as 0:-1:0
// (with length 1), or a GB_LIST with ni=1.
// Time: 50x faster than MATLAB
ASSERT (!fine_task) ;
ASSERT (alen == 1) ;
ASSERT (nI == 1) ;
ASSERT (GB_Ai (pA) == GB_ijlist (I, 0, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = 1 ;
#else
Ci [pC] = 0 ;
GB_COPY_ENTRY (pC, pA) ;
#endif
break ;
//--------------------------------------------------------------
case 4 : // Ikind is ":", thus C(:,kC) = A (:,kA)
//--------------------------------------------------------------
// Time: 1x MATLAB but low speedup on the Mac. Why?
// Probably memory bound since it is just memcpy's.
ASSERT (Ikind == GB_ALL && ibegin == 0) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
#if defined ( GB_SYMBOLIC )
if (nzombies == 0)
{
memcpy (Ci + pC, Ai + pA, alen * sizeof (int64_t)) ;
}
else
{
// with zombies
for (int64_t k = 0 ; k < alen ; k++)
{
// symbolic C(:,kC) = A(:,kA) where A has zombies
int64_t i = GB_Ai (pA + k) ;
ASSERT (i == GB_ijlist (I, i, Ikind, Icolon)) ;
Ci [pC + k] = i ;
}
}
#else
memcpy (Ci + pC, Ai + pA, alen * sizeof (int64_t)) ;
#endif
GB_COPY_RANGE (pC, pA, alen) ;
#endif
break ;
//--------------------------------------------------------------
case 5 : // Ikind is GB_RANGE = ibegin:iend
//--------------------------------------------------------------
// Time: much faster than MATLAB. Good speedup too.
ASSERT (Ikind == GB_RANGE) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
for (int64_t k = 0 ; k < alen ; k++)
{
int64_t i = GB_Ai (pA + k) ;
int64_t inew = i - ibegin ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
Ci [pC + k] = inew ;
}
GB_COPY_RANGE (pC, pA, alen) ;
#endif
break ;
//--------------------------------------------------------------
case 6 : // I is short vs nnz (A (:,kA)), use binary search
//--------------------------------------------------------------
// Time: very slow unless I is very short and A(:,kA) is
// very long.
// This case can handle any kind of I, and A(:,kA) of any
// properties. For a fine task, A(:,kA) has not been
// sliced; I has been sliced instead.
// If the I bucket inverse has not been created, this
// method is the only option. Alternatively, if nI =
// length (I) is << nnz (A (:,kA)), then scanning I and
// doing a binary search of A (:,kA) is faster than doing a
// linear-time search of A(:,kA) and a lookup into the I
// bucket inverse.
// The vector of C is constructed in sorted order, so no
// sort is needed.
// A(:,kA) has not been sliced.
ASSERT (pA == Ap_start [kC]) ;
ASSERT (pA_end == Ap_end [kC]) ;
// scan I, in order, and search for the entry in A(:,kA)
for (int64_t k = 0 ; k < ilen ; k++)
{
// C(inew,kC) = A (i,kA), if it exists.
// i = I [inew] ; or from a colon expression
int64_t inew = k + pI ;
int64_t i = GB_ijlist (I, inew, Ikind, Icolon) ;
bool found ;
int64_t pleft = pA ;
int64_t pright = pA_end - 1 ;
#if defined ( GB_SYMBOLIC )
bool is_zombie ;
GB_BINARY_SEARCH_ZOMBIE (i, Ai, pleft, pright, found,
nzombies, is_zombie) ;
#else
GB_BINARY_SEARCH (i, Ai, pleft, pright, found) ;
#endif
if (found)
{
ASSERT (i == GB_Ai (pleft)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pleft) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
case 7 : // I is ibegin:iinc:iend with iinc > 1
//--------------------------------------------------------------
// Time: 1 thread: C=A(1:2:n,:) is 3x slower than MATLAB
// but has good speedup. About as fast as MATLAB with
// enough threads.
ASSERT (Ikind == GB_STRIDE && iinc > 1) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present; see if it is in ibegin:iinc:iend
int64_t i = GB_Ai (pA + k) ;
ASSERT (ibegin <= i && i <= iend) ;
i = i - ibegin ;
if (i % iinc == 0)
{
// i is in the sequence ibegin:iinc:iend
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
int64_t inew = i / iinc ;
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//----------------------------------------------------------
case 8 : // I = ibegin:(-iinc):iend, with iinc < -1
//----------------------------------------------------------
// Time: 2x slower than MATLAB for iinc = -2 or -8.
// Good speedup though. Faster than MATLAB for
// large values (iinc = -128).
ASSERT (Ikind == GB_STRIDE && iinc < -1) ;
for (int64_t k = alen - 1 ; k >= 0 ; k--)
{
// A(i,kA) present; see if it is in ibegin:iinc:iend
int64_t i = GB_Ai (pA + k) ;
ASSERT (iend <= i && i <= ibegin) ;
i = ibegin - i ;
if (i % inc == 0)
{
// i is in the sequence ibegin:iinc:iend
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
int64_t inew = i / inc ;
ASSERT (pC < pC_end) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//----------------------------------------------------------
case 9 : // I = ibegin:(-1):iend
//----------------------------------------------------------
// Time: much faster than MATLAB. Good speedup.
ASSERT (Ikind == GB_STRIDE && iinc == -1) ;
#if defined ( GB_PHASE_1_OF_2 )
clen = alen ;
#else
for (int64_t k = alen - 1 ; k >= 0 ; k--)
{
// A(i,kA) is present
int64_t i = GB_Ai (pA + k) ;
int64_t inew = (ibegin - i) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
}
#endif
break ;
//--------------------------------------------------------------
case 10 : // I unsorted, and C needs qsort, duplicates OK
//--------------------------------------------------------------
// Time: with one thread: 2x slower than MATLAB, probably
// because of the qsort. Good speedup however. This used
// if qsort is needed but ndupl == 0. Try a method that
// needs qsort, but no duplicates?
// Case 10 works well when I has many entries and A(:,kA)
// has few entries. C(:,kC) must be sorted after this pass.
ASSERT (Ikind == GB_LIST) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// traverse bucket i for all indices inew where
// i == I [inew] or where i is from a colon expression
GB_for_each_index_in_bucket (inew, i)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
// TODO: skip the sort if C is allowed to be jumbled on
// output. Flag C as jumbled instead.
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
if (!fine_task)
{
// a coarse task owns this entire C(:,kC) vector, so
// the sort can be done now. The sort for vectors
// handled by multiple fine tasks must wait until all
// task are completed, below in the post sort.
pC = Cp [kC] ;
GB_qsort_1b (Ci + pC, (GB_void *) (Cx + pC*GB_CSIZE1),
GB_CSIZE2, clen) ;
}
#endif
break ;
//--------------------------------------------------------------
case 11 : // I not contiguous, with duplicates. No qsort needed
//--------------------------------------------------------------
// Case 11 works well when I has many entries and A(:,kA)
// has few entries. It requires that I be sorted on input,
// so that no sort is required for C(:,kC). It is
// otherwise identical to Case 10.
ASSERT (Ikind == GB_LIST) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// traverse bucket i for all indices inew where
// i == I [inew] or where i is from a colon expression
GB_for_each_index_in_bucket (inew, i)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
case 12 : // I not contiguous, no duplicates. No qsort needed.
//--------------------------------------------------------------
// Identical to Case 11, except GB_for_each_index_in_bucket
// just needs to iterate 0 or 1 times. Works well when I
// has many entries and A(:,kA) has few entries.
ASSERT (Ikind == GB_LIST && nduplicates == 0) ;
for (int64_t k = 0 ; k < alen ; k++)
{
// A(i,kA) present, look it up in the I inverse buckets
int64_t i = GB_Ai (pA + k) ;
// bucket i has at most one index inew such that
// i == I [inew]
int64_t inew = Mark [i] - 1 ;
if (inew >= 0)
{
ASSERT (inew >= 0 && inew < nI) ;
ASSERT (i == GB_ijlist (I, inew, Ikind, Icolon)) ;
#if defined ( GB_PHASE_1_OF_2 )
clen++ ;
#else
Ci [pC] = inew ;
GB_COPY_ENTRY (pC, pA + k) ;
pC++ ;
#endif
}
}
#if defined ( GB_PHASE_2_OF_2 )
ASSERT (pC == pC_end) ;
#endif
break ;
//--------------------------------------------------------------
default: ;
//--------------------------------------------------------------
}
//------------------------------------------------------------------
// final count of nnz (C (:,j))
//------------------------------------------------------------------
#if defined ( GB_PHASE_1_OF_2 )
if (fine_task)
{
TaskList [taskid].pC = clen ;
}
else
{
Cp [kC] = clen ;
}
#endif
}
}
//--------------------------------------------------------------------------
// phase2: post sort for any vectors handled by fine tasks with method 10
//--------------------------------------------------------------------------
// TODO: skip the sort if C is allowed to be jumbled on output.
// Flag C as jumbled instead.
#if defined ( GB_PHASE_2_OF_2 )
if (post_sort)
{
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
int64_t kC = TaskList [taskid].kfirst ;
bool do_post_sort = (TaskList [taskid].len != 0) ;
if (do_post_sort)
{
// This is the first fine task with method 10 for C(:,kC). The
// vector C(:,kC) must be sorted, since method 10 left it with
// unsorted indices.
int64_t pC = Cp [kC] ;
int64_t clen = Cp [kC+1] - pC ;
GB_qsort_1b (Ci + pC, (GB_void *) (Cx + pC*GB_CSIZE1),
GB_CSIZE2, clen) ;
}
}
}
#endif
}
#undef GB_Ai
#undef GB_for_each_index_in_bucket
#undef GB_COPY_RANGE
#undef GB_COPY_ENTRY
#undef GB_CTYPE
#undef GB_CSIZE1
#undef GB_CSIZE2
|
GB_dense_subassign_06d_template.c | //------------------------------------------------------------------------------
// GB_dense_subassign_06d_template: C<A> = A where C is dense
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
{
//--------------------------------------------------------------------------
// get C and A
//--------------------------------------------------------------------------
const int64_t *GB_RESTRICT Ap = A->p ;
const int64_t *GB_RESTRICT Ah = A->h ;
const int64_t *GB_RESTRICT Ai = A->i ;
const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) A->x ;
GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ;
const int64_t cvlen = C->vlen ;
//--------------------------------------------------------------------------
// C<A> = A
//--------------------------------------------------------------------------
int taskid ;
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (taskid = 0 ; taskid < ntasks ; taskid++)
{
// if kfirst > klast then taskid does no work at all
int64_t kfirst = kfirst_slice [taskid] ;
int64_t klast = klast_slice [taskid] ;
//----------------------------------------------------------------------
// C<A(:,kfirst:klast)> = A(:,kfirst:klast)
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// find the part of A(:,k) to be operated on by this task
//------------------------------------------------------------------
int64_t j = (Ah == NULL) ? k : Ah [k] ;
int64_t pA_start, pA_end ;
GB_get_pA_and_pC (&pA_start, &pA_end, NULL,
taskid, k, kfirst, klast, pstart_slice, NULL, NULL, Ap) ;
// pC points to the start of C(:,j) if C is dense
int64_t pC = j * cvlen ;
//------------------------------------------------------------------
// C<A(:,j)> = A(:,j)
//------------------------------------------------------------------
if (Mask_struct)
{
GB_PRAGMA_SIMD_VECTORIZE
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
int64_t p = pC + Ai [pA] ;
GB_COPY_A_TO_C (Cx, p, Ax, pA) ; // Cx [p] = Ax [pA]
}
}
else
{
GB_PRAGMA_SIMD_VECTORIZE
for (int64_t pA = pA_start ; pA < pA_end ; pA++)
{
if (GB_AX_MASK (Ax, pA, asize))
{
int64_t p = pC + Ai [pA] ;
GB_COPY_A_TO_C (Cx, p, Ax, pA) ; // Cx [p] = Ax [pA]
}
}
}
}
}
}
|
PhysicalSystemRigidBody.h | //
// PhysicalSystemRigidBody.h
// Gauss
//
// Created by David Levin on 5/8/18.
//
#ifndef PhysicalSystemRigidBody_h
#define PhysicalSystemRigidBody_h
//A dynamic rigid body
#include <vector>
#include <DOFParticle.h>
#include <DOFRotation.h>
#include <DOFPair.h>
#include <UtilitiesEigen.h>
#include <UtilitiesRigidBodies.h>
namespace Gauss {
namespace RigidBodies {
template<typename DataType>
class PhysicalSystemRigidBodyImpl
{
public:
using GammaMatrix = Eigen::Matrix<DataType, 3,6>;
//temporary global indices until I update the state to give these to me
//automatically
PhysicalSystemRigidBodyImpl(const Eigen::Ref<Eigen::MatrixXd> &V, const Eigen::Ref<Eigen::MatrixXi> &F, DataType density=1.0) {
m_V = V;
m_F = F;
m_numVerts = m_V.rows();
m_numFaces = m_F.rows();
assert(m_V.cols() == 3); //3D only for now
Eigen::Vector3x<DataType> inertia;
m_mass = computeMoments(m_com, inertia, m_R0, m_V, m_F);
m_mass *= density;
inertia *= density;
m_massMatrix.setConstant(m_mass);
m_massMatrix.segment(0,3) = inertia;
//subtract center of mass off of vertex positions
#pragma omp parallel for
for(unsigned int ii = 0; ii < V.rows(); ++ii)
{
m_V.row(ii) -= m_com.transpose();
}
}
~PhysicalSystemRigidBodyImpl() {
}
DataType getEnergy(const State<DataType> &state) const {
}
DataType getStrainEnergy(const State<DataType> &state) const {
return 0.0;
}
template<typename Assembler>
inline void getMassMatrix(Assembler &assembler, const State<DataType> &state) const {
//Rigid body mass matrix
assign(assembler, m_massMatrix.asDiagonal().toDenseMatrix().eval(), getQDot(0), getQDot(0));
}
//the rigid body jacobian
template<typename Assembler>
inline void getStiffnessMatrix(Assembler &assembler, const State<DataType> &state) const {
//do nothing, rigid body has no constitutive model
}
template<typename Assembler>
inline void getForce(Assembler &assembler, const State<DataType> &state) const {
getBodyForce(assembler, state);
}
template<typename Assembler>
inline void getInternalForce(Assembler &assembler, const State<DataType> &state) const {
//centripedal force and coriolis force
}
template<typename Assembler>
inline void getBodyForce(Assembler &assembler, const State<DataType> &state) const {
//gravity goes here
Eigen::Matrix<DataType, 6,1> g;
g << 0,0,0, 0, m_mass*(-9.8), 0.0;
g.segment(3,3) = mapDOFEigenQuat(m_q.first(), state).toRotationMatrix().transpose()*g.segment(3,3);
//std::cout<<"W: "<<mapDOFEigenQuat(m_q.first(), state).x()<<" "<<mapDOFEigenQuat(m_q.first(), state).y()<<" "<<mapDOFEigenQuat(m_q.first(), state).z()<<" "<<mapDOFEigenQuat(m_q.first(), state).w()<<"\n";
//std::cout<<"ROTATION MATRIX: \n"<<mapDOFEigenQuat(m_q.first(), state).toRotationMatrix()<<"\n";
assign(assembler, g, getQDot(0));
}
//Degree-of-freedom access
inline auto & getQ() { return m_q; }
inline const auto & getQ() const { return m_q; }
inline auto & getQDot() { return m_qDot; }
inline const auto & getQDot() const { return m_qDot; }
//get function supporting a vertex (these return arrays in order to slot directly into assemblers)
inline decltype(auto) getQ(unsigned int vertexId) const {
std::array<const DOFBase<DataType,0> *,1> toReturn = {{&m_q}};
return toReturn;
}
inline decltype(auto) getQDot(unsigned int vertexId) const {
std::array<const DOFBase<DataType,1> *,1> toReturn = {{&m_qDot}};
return toReturn;
}
template<typename Vector>
inline decltype(auto) getQ(Vector &x, unsigned int elementId) const {
std::cout<<"Error not implemented \n";
exit(0);
std::array<const DOFBase<DataType,0> *, 1> toReturn = {{&m_q[elementId]}};
return toReturn;
}
template<typename Vector>
inline decltype(auto) getQDot(Vector &x, unsigned int elementId) const {
std::cout<<"Error not implemented \n";
exit(0);
std::array<const DOFBase<DataType,1> *,1> toReturn = {{&m_qDot[elementId]}};
return toReturn;
}
//Geometry
inline const auto getPosition(const State<DataType> &state, unsigned int vertexId) const {
return (mapDOFEigenQuat(m_q.first(), state).toRotationMatrix()*(m_V.row(vertexId).transpose()) + m_com + mapDOFEigen(m_q.second(), state)).eval();
}
inline const auto getVelocity(const State<DataType> &state, unsigned int vertexId) const {
return getDPDQ(state,vertexId)*mapDOFEigen(m_qDot, state);
}
inline const auto getDPDQ(const State<DataType> &state, unsigned int vertexId) const {
GammaMatrix gamma;
gamma.setZero();
gamma.block(0,0,3,3) << 0, m_V(vertexId,2), -m_V(vertexId,1), -m_V(vertexId,2), 0, m_V(vertexId,0), m_V(vertexId,1), -m_V(vertexId,0), 0;
gamma.block(0,3,3,3).setIdentity();
return mapDOFEigen(m_q.first(), state).toRotationMatrix()*gamma;
}
//Rigid body Jacobian goes here
inline const auto getDPDQ(const State<DataType> &state, unsigned int elementId, const Eigen::Vector3x<DataType> &pos) const {
std::cout<<"position-based DPDQ not implemented in rigid body system \n";
exit(0);
}
inline auto getGeometry() { return std::make_pair(std::ref(m_V), std::ref(m_F)); }
protected:
//Mesh
unsigned int m_numVerts, m_numFaces;
Eigen::MatrixXd m_V;
Eigen::MatrixXi m_F;
DataType m_mass;
Eigen::Matrix33x<DataType> m_R0; //initial rotation from inertia frame to initial state
Eigen::Vector3x<DataType> m_com; //center of mass in body frame
Eigen::Vector6x<DataType> m_massMatrix; //mass matrix is diagonal for rigid bodies (yay!)
//positions are a rotation and a particle (for the translation) -- stored in body frame
DOFPair<DataType, DOFRotation, DOFParticle, 0> m_q;
//velocities are an angular velocity (particle) and a linear velocity (particle) -- stored in body frame
DOFPair<DataType, DOFParticle, DOFParticle, 1> m_qDot;
private:
};
template<typename DataType>
using PhysicalSystemRigidBody = PhysicalSystem<DataType, PhysicalSystemRigidBodyImpl<DataType> >;
}
}
#endif /* PhysicalSystemRigidBody_h */
|
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/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/Frontend/OpenMP/OMPContext.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;
struct OMPTraitProperty;
struct OMPTraitSelector;
struct OMPTraitSet;
class OMPTraitInfo;
/// 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> FloatControlHandler;
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> CilkHintHandler;
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> STDCFenvAccessHandler;
std::unique_ptr<PragmaHandler> STDCFenvRoundHandler;
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;
/// Current kind of OpenMP clause
OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown;
/// 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;
void MaybeDestroyTemplateIds() {
if (!TemplateIds.empty() &&
(Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens()))
DestroyTemplateIds();
}
void DestroyTemplateIds();
/// RAII object to destroy TemplateIdAnnotations where possible, from a
/// likely-good position during parsing.
struct DestroyTemplateIdAnnotationsRAIIObj {
Parser &Self;
DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {}
~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); }
};
/// 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();
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();
/// Handle the annotation token produced for
/// #pragma STDC FENV_ROUND...
void HandlePragmaFEnvRound();
/// Handle the annotation token produced for
/// #pragma float_control
void HandlePragmaFloatControl();
/// \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 TypeResult getTypeAnnotation(const Token &Tok) {
if (!Tok.getAnnotationValue())
return TypeError();
return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue());
}
private:
static void setTypeAnnotation(Token &Tok, TypeResult T) {
assert((T.isInvalid() || T.get()) &&
"produced a valid-but-null type annotation?");
Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().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();
/// Kinds of compound pseudo-tokens formed by a sequence of two real tokens.
enum class CompoundToken {
/// A '(' '{' beginning a statement-expression.
StmtExprBegin,
/// A '}' ')' ending a statement-expression.
StmtExprEnd,
/// A '[' '[' beginning a C++11 or C2x attribute.
AttrBegin,
/// A ']' ']' ending a C++11 or C2x attribute.
AttrEnd,
/// A '::' '*' forming a C++ pointer-to-member declaration.
MemberPtr,
};
/// Check that a compound operator was written in a "sensible" way, and warn
/// if not.
void checkCompoundToken(SourceLocation FirstTokLoc,
tok::TokenKind FirstTokKind, CompoundToken Op);
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();
}
};
/// Introduces zero or more scopes for parsing. The scopes will all be exited
/// when the object is destroyed.
class MultiParseScope {
Parser &Self;
unsigned NumScopes = 0;
MultiParseScope(const MultiParseScope&) = delete;
public:
MultiParseScope(Parser &Self) : Self(Self) {}
void Enter(unsigned ScopeFlags) {
Self.EnterScope(ScopeFlags);
++NumScopes;
}
void Exit() {
while (NumScopes) {
Self.ExitScope();
--NumScopes;
}
}
~MultiParseScope() {
Exit();
}
};
/// EnterScope - Start a new scope.
void EnterScope(unsigned ScopeFlags);
/// ExitScope - Pop a scope off the scope stack.
void ExitScope();
/// Re-enter the template scopes for a declaration that might be a template.
unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D);
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. Balances (), [], and {} delimiter tokens while
/// skipping.
///
/// 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;
explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {}
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), ExceptionSpecTokens(nullptr) {}
void ParseLexedMethodDeclarations() override;
Parser *Self;
/// Method - The method declaration.
Decl *Method;
/// 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), 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 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;
};
// In ParseCXXInlineMethods.cpp.
struct ReenterTemplateScopeRAII;
struct ReenterClassScopeRAII;
void LexTemplateFunctionForLateParsing(CachedTokens &Toks);
void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT);
static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT);
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);
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);
ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false);
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<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 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 ObjectHasErrors,
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,
SourceLocation *LParenLoc = nullptr,
SourceLocation *RParenLoc = nullptr);
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 ParseCilkSpawnStatement();
StmtResult ParseCilkSyncStatement();
StmtResult ParseCilkForStatement(SourceLocation *TrailingElseLoc);
StmtResult ParseCilkScopeStatement();
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");
}
/// Whether a defining-type-specifier is permitted in a given context.
enum class AllowDefiningTypeSpec {
/// The grammar doesn't allow a defining-type-specifier here, and we must
/// not parse one (eg, because a '{' could mean something else).
No,
/// The grammar doesn't allow a defining-type-specifier here, but we permit
/// one for error recovery purposes. Sema will reject.
NoButErrorRecovery,
/// The grammar allows a defining-type-specifier here, even though it's
/// always invalid. Sema will reject.
YesButInvalid,
/// The grammar allows a defining-type-specifier here, and one can be valid.
Yes
};
/// Is this a context in which we are parsing defining-type-specifiers (and
/// so permit class and enum definitions in addition to non-defining class and
/// enum elaborated-type-specifiers)?
static AllowDefiningTypeSpec
isDefiningTypeSpecifierContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
case DeclSpecContext::DSC_alias_declaration:
case DeclSpecContext::DSC_objc_method_result:
return AllowDefiningTypeSpec::Yes;
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_template_param:
return AllowDefiningTypeSpec::YesButInvalid;
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
return AllowDefiningTypeSpec::NoButErrorRecovery;
case DeclSpecContext::DSC_trailing:
return AllowDefiningTypeSpec::No;
}
llvm_unreachable("Missing DeclSpecContext case");
}
/// Is this a context in which an opaque-enum-declaration can appear?
static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) {
switch (DSC) {
case DeclSpecContext::DSC_normal:
case DeclSpecContext::DSC_class:
case DeclSpecContext::DSC_top_level:
return true;
case DeclSpecContext::DSC_alias_declaration:
case DeclSpecContext::DSC_objc_method_result:
case DeclSpecContext::DSC_condition:
case DeclSpecContext::DSC_template_param:
case DeclSpecContext::DSC_template_type_arg:
case DeclSpecContext::DSC_type_specifier:
case DeclSpecContext::DSC_trailing:
return false;
}
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,
RecordDecl *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
};
/// Determine whether we could have an enum-base.
///
/// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise
/// only consider this to be an enum-base if the next token is a '{'.
///
/// \return \c false if this cannot possibly be an enum base; \c true
/// otherwise.
bool isEnumBase(bool AllowSemi);
/// 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();
/// Try to skip a possibly empty sequence of 'attribute-specifier's without
/// full validation of the syntactic structure of attributes.
bool TrySkipAttributes();
public:
TypeResult
ParseTypeName(SourceRange *Range = nullptr,
DeclaratorContext Context = DeclaratorContext::TypeName,
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);
}
}
bool MaybeParseCXX11Attributes(ParsedAttributes &attrs,
SourceLocation *endLoc = nullptr) {
if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) {
ParsedAttributesWithRange attrsWithRange(AttrFactory);
ParseCXX11Attributes(attrsWithRange, endLoc);
attrs.takeAllFrom(attrsWithRange);
return true;
}
return false;
}
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 ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName,
SourceLocation AttrNameLoc,
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);
ExprResult ParseExtIntegerArgument();
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,
ParsedType ObjectType,
bool ObjectHadErrors,
SourceLocation TemplateKWLoc,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool EnteringContext,
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 a property kind into \p TIProperty for the selector set \p Set and
/// selector \p Selector.
void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
llvm::omp::TraitSet Set,
llvm::omp::TraitSelector Selector,
llvm::StringMap<SourceLocation> &Seen);
/// Parse a selector kind into \p TISelector for the selector set \p Set.
void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &Seen);
/// Parse a selector set kind into \p TISet.
void parseOMPTraitSetKind(OMPTraitSet &TISet,
llvm::StringMap<SourceLocation> &Seen);
/// Parses an OpenMP context property.
void parseOMPContextProperty(OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &Seen);
/// Parses an OpenMP context selector.
void parseOMPContextSelector(OMPTraitSelector &TISelector,
llvm::omp::TraitSet Set,
llvm::StringMap<SourceLocation> &SeenSelectors);
/// Parses an OpenMP context selector set.
void parseOMPContextSelectorSet(OMPTraitSet &TISet,
llvm::StringMap<SourceLocation> &SeenSets);
/// Parses OpenMP context selectors.
bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI);
/// Parse a `match` clause for an '#pragma omp declare variant'. Return true
/// if there was an error.
bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI,
OMPTraitInfo *ParentTI);
/// Parse clauses for '#pragma omp declare variant'.
void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks,
SourceLocation Loc);
/// Parse 'omp [begin] assume[s]' directive.
void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Parse 'omp end assumes' directive.
void ParseOpenMPEndAssumesDirective(SourceLocation Loc);
/// Parse clauses for '#pragma omp declare target'.
DeclGroupPtrTy ParseOMPDeclareTargetClauses();
/// Parse '#pragma omp end declare target'.
void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind,
SourceLocation Loc);
/// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if
/// it is not the current token.
void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind);
/// Check the \p FoundKind against the \p ExpectedKind, if not issue an error
/// that the "end" matching the "begin" directive of kind \p BeginKind was not
/// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd
/// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`.
void parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
OpenMPDirectiveKind ExpectedKind,
OpenMPDirectiveKind FoundKind,
SourceLocation MatchingLoc,
SourceLocation FoundLoc,
bool SkipUntilOpenMPEnd);
/// 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);
/// Tries to parse cast part of OpenMP array shaping operation:
/// '[' expression ']' { '[' expression ']' } ')'.
bool tryParseOpenMPArrayShapingCastPart();
/// 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 DKind Directive kind.
/// \param Kind Kind of current clause.
/// \param ParseOnly true to skip the clause's semantic actions and return
/// nullptr.
///
OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
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);
/// Parses and creates OpenMP 5.0 iterators expression:
/// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier =
/// <range-specification> }+ ')'
ExprResult ParseOpenMPIteratorsExpr();
/// Parses allocators and traits in the context of the uses_allocator clause.
/// Expected format:
/// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')'
OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind);
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 *DepModOrTailExpr = nullptr;
SourceLocation ColonLoc;
SourceLocation RLoc;
CXXScopeSpec ReductionOrMapperIdScopeSpec;
DeclarationNameInfo ReductionOrMapperId;
int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or
///< lastprivate clause.
SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers>
MapTypeModifiers;
SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers>
MapTypeModifiersLoc;
SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers>
MotionModifiers;
SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc;
bool IsMapTypeImplicit = false;
SourceLocation ExtraModifierLoc;
};
/// Parses clauses with list.
bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind,
SmallVectorImpl<Expr *> &Vars,
OpenMPVarListDataTy &Data);
bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType,
bool ObjectHadErrors, bool EnteringContext,
bool AllowDestructorName, bool AllowConstructorName,
bool AllowDeductionGuide,
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(MultiParseScope &TemplateScopes, 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();
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 LAngleLoc,
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();
//===--------------------------------------------------------------------===//
// 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;
class GNUAsmQualifiers {
unsigned Qualifiers = AQ_unspecified;
public:
enum AQ {
AQ_unspecified = 0,
AQ_volatile = 1,
AQ_inline = 2,
AQ_goto = 4,
};
static const char *getQualifierName(AQ Qualifier);
bool setAsmQualifier(AQ Qualifier);
inline bool isVolatile() const { return Qualifiers & AQ_volatile; };
inline bool isInline() const { return Qualifiers & AQ_inline; };
inline bool isGoto() const { return Qualifiers & AQ_goto; }
};
bool isGCCAsmStatement(const Token &TokAfterAsm) const;
bool isGNUAsmQualifier(const Token &TokAfterAsm) const;
GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const;
bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ);
};
} // end namespace clang
#endif
|
SPHCalcDensityFunctor.h | /**
* @file SPHCalcDensityFunctor.h
* @author seckler
* @date 19.01.18
*/
#pragma once
#include "autopas/pairwiseFunctors/Functor.h"
#include "autopas/particles/OwnershipState.h"
#include "autopas/sph/SPHKernels.h"
namespace autopas::sph {
/**
* Class that defines the density functor.
* It is used to calculate the density based on the given SPH kernel.
* @tparam Particle
* @tparam ParticleCell
*/
template <class Particle>
class SPHCalcDensityFunctor : public Functor<Particle, SPHCalcDensityFunctor<Particle>> {
public:
/// soa arrays type
using SoAArraysType = typename Particle::SoAArraysType;
SPHCalcDensityFunctor() : autopas::Functor<Particle, SPHCalcDensityFunctor<Particle>>(0.){};
bool isRelevantForTuning() override { return true; }
bool allowsNewton3() override { return true; }
bool allowsNonNewton3() override { return true; }
/**
* Calculates the density contribution of the interaction of particle i and j.
* It is not symmetric, because the smoothing lenghts of the two particles can
* be different.
* @param i first particle of the interaction
* @param j second particle of the interaction
* @param newton3 defines whether or whether not to use newton 3
*/
inline void AoSFunctor(Particle &i, Particle &j, bool newton3 = true) override {
if (i.isDummy() or j.isDummy()) {
return;
}
const std::array<double, 3> dr = utils::ArrayMath::sub(j.getR(), i.getR()); // ep_j[j].pos - ep_i[i].pos;
const double density =
j.getMass() * SPHKernels::W(dr, i.getSmoothingLength()); // ep_j[j].mass * W(dr, ep_i[i].smth)
i.addDensity(density);
if (newton3) {
// Newton 3:
// W is symmetric in dr, so no -dr needed, i.e. we can reuse dr
const double density2 = i.getMass() * SPHKernels::W(dr, j.getSmoothingLength());
j.addDensity(density2);
}
}
/**
* Get the number of floating point operations used in one full kernel call
* @return the number of floating point operations
*/
static unsigned long getNumFlopsPerKernelCall() {
unsigned long flops = 0;
flops += 3; // calculating dr
flops += 2 * SPHKernels::getFlopsW(); // flops for calling W
flops += 2 * 1; // calculating density
flops += 2 * 1; // adding density
return flops;
}
/**
* @copydoc Functor::SoAFunctorSingle(SoAView<SoAArraysType>, bool)
* This functor ignores the newton3 value, as we do not expect any benefit from disabling newton3.
*/
void SoAFunctorSingle(SoAView<SoAArraysType> soa, bool newton3) override {
if (soa.getNumParticles() == 0) return;
double *const __restrict xptr = soa.template begin<Particle::AttributeNames::posX>();
double *const __restrict yptr = soa.template begin<Particle::AttributeNames::posY>();
double *const __restrict zptr = soa.template begin<Particle::AttributeNames::posZ>();
double *const __restrict densityptr = soa.template begin<Particle::AttributeNames::density>();
double *const __restrict smthptr = soa.template begin<Particle::AttributeNames::smth>();
double *const __restrict massptr = soa.template begin<Particle::AttributeNames::mass>();
const auto *const __restrict ownedStatePtr = soa.template begin<Particle::AttributeNames::ownershipState>();
size_t numParticles = soa.getNumParticles();
for (unsigned int i = 0; i < numParticles; ++i) {
// checks whether particle i is owned.
if (ownedStatePtr[i] == OwnershipState::dummy) {
continue;
}
double densacc = 0.;
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
#pragma omp simd reduction(+ : densacc)
for (unsigned int j = i + 1; j < numParticles; ++j) {
const double drx = xptr[i] - xptr[j];
const double dry = yptr[i] - yptr[j];
const double drz = zptr[i] - zptr[j];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
// if second particle is a dummy, we skip the interaction.
const bool mask = ownedStatePtr[j] != OwnershipState::dummy;
const double density = mask ? massptr[j] * SPHKernels::W(dr2, smthptr[i]) : 0.;
densacc += density;
// Newton 3:
// W is symmetric in dr, so no -dr needed, i.e. we can reuse dr
const double density2 = mask ? massptr[i] * SPHKernels::W(dr2, smthptr[j]) : 0.;
densityptr[j] += density2;
}
densityptr[i] += densacc;
}
}
/**
* @copydoc Functor::SoAFunctorPair(SoAView<SoAArraysType>, SoAView<SoAArraysType>, bool)
*/
void SoAFunctorPair(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, bool newton3) override {
if (soa1.getNumParticles() == 0 || soa2.getNumParticles() == 0) return;
double *const __restrict xptr1 = soa1.template begin<Particle::AttributeNames::posX>();
double *const __restrict yptr1 = soa1.template begin<Particle::AttributeNames::posY>();
double *const __restrict zptr1 = soa1.template begin<Particle::AttributeNames::posZ>();
double *const __restrict densityptr1 = soa1.template begin<Particle::AttributeNames::density>();
double *const __restrict smthptr1 = soa1.template begin<Particle::AttributeNames::smth>();
double *const __restrict massptr1 = soa1.template begin<Particle::AttributeNames::mass>();
double *const __restrict xptr2 = soa2.template begin<Particle::AttributeNames::posX>();
double *const __restrict yptr2 = soa2.template begin<Particle::AttributeNames::posY>();
double *const __restrict zptr2 = soa2.template begin<Particle::AttributeNames::posZ>();
double *const __restrict densityptr2 = soa2.template begin<Particle::AttributeNames::density>();
double *const __restrict smthptr2 = soa2.template begin<Particle::AttributeNames::smth>();
double *const __restrict massptr2 = soa2.template begin<Particle::AttributeNames::mass>();
const auto *const __restrict ownedStatePtr1 = soa1.template begin<Particle::AttributeNames::ownershipState>();
const auto *const __restrict ownedStatePtr2 = soa2.template begin<Particle::AttributeNames::ownershipState>();
size_t numParticlesi = soa1.getNumParticles();
for (unsigned int i = 0; i < numParticlesi; ++i) {
// checks whether particle i is in the domain box, unused if calculateGlobals is false!
if (ownedStatePtr1[i] == OwnershipState::dummy) {
continue;
}
double densacc = 0.;
size_t numParticlesj = soa2.getNumParticles();
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
#pragma omp simd reduction(+ : densacc)
for (unsigned int j = 0; j < numParticlesj; ++j) {
const double drx = xptr1[i] - xptr2[j];
const double dry = yptr1[i] - yptr2[j];
const double drz = zptr1[i] - zptr2[j];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
// if second particle is a dummy, we skip the interaction.
const bool mask = ownedStatePtr2[j] != OwnershipState::dummy;
const double density = mask ? massptr2[j] * SPHKernels::W(dr2, smthptr1[i]) : 0.;
densacc += density;
if (newton3) {
// Newton 3:
// W is symmetric in dr, so no -dr needed, i.e. we can reuse dr
const double density2 = mask ? massptr1[i] * SPHKernels::W(dr2, smthptr2[j]) : 0.;
densityptr2[j] += density2;
}
}
densityptr1[i] += densacc;
}
}
// clang-format off
/**
* @copydoc Functor::SoAFunctorVerlet(SoAView<SoAArraysType> soa, const size_t indexFirst, const std::vector<size_t, autopas::AlignedAllocator<size_t>> &neighborList, bool newton3)
*/
// clang-format on
void SoAFunctorVerlet(SoAView<SoAArraysType> soa, const size_t indexFirst,
const std::vector<size_t, autopas::AlignedAllocator<size_t>> &neighborList,
bool newton3) override {
if (soa.getNumParticles() == 0) return;
const auto *const __restrict ownedStatePtr = soa.template begin<Particle::AttributeNames::ownershipState>();
// checks whether particle i is owned.
if (ownedStatePtr[indexFirst] == OwnershipState::dummy) {
return;
}
double *const __restrict xptr = soa.template begin<Particle::AttributeNames::posX>();
double *const __restrict yptr = soa.template begin<Particle::AttributeNames::posY>();
double *const __restrict zptr = soa.template begin<Particle::AttributeNames::posZ>();
double *const __restrict densityptr = soa.template begin<Particle::AttributeNames::density>();
double *const __restrict smthptr = soa.template begin<Particle::AttributeNames::smth>();
double *const __restrict massptr = soa.template begin<Particle::AttributeNames::mass>();
double densacc = 0;
const auto ¤tList = neighborList;
size_t listSize = currentList.size();
// icpc vectorizes this.
// g++ only with -ffast-math or -funsafe-math-optimizations
#pragma omp simd reduction(+ : densacc)
for (unsigned int j = 0; j < listSize; ++j) {
const double drx = xptr[indexFirst] - xptr[currentList[j]];
const double dry = yptr[indexFirst] - yptr[currentList[j]];
const double drz = zptr[indexFirst] - zptr[currentList[j]];
const double drx2 = drx * drx;
const double dry2 = dry * dry;
const double drz2 = drz * drz;
const double dr2 = drx2 + dry2 + drz2;
// if second particle is a dummy, we skip the interaction.
const bool mask = ownedStatePtr[currentList[j]] != OwnershipState::dummy;
const double density = mask ? massptr[currentList[j]] * SPHKernels::W(dr2, smthptr[indexFirst]) : 0.;
densacc += density;
if (newton3) {
// Newton 3:
// W is symmetric in dr, so no -dr needed, i.e. we can reuse dr
const double density2 = mask ? massptr[indexFirst] * SPHKernels::W(dr2, smthptr[currentList[j]]) : 0.;
densityptr[currentList[j]] += density2;
}
}
densityptr[indexFirst] += densacc;
}
/**
* @copydoc Functor::getNeededAttr()
*/
constexpr static auto getNeededAttr() {
return std::array<typename Particle::AttributeNames, 7>{
Particle::AttributeNames::mass, Particle::AttributeNames::posX, Particle::AttributeNames::posY,
Particle::AttributeNames::posZ, Particle::AttributeNames::smth, Particle::AttributeNames::density,
Particle::AttributeNames::ownershipState};
}
/**
* @copydoc Functor::getNeededAttr(std::false_type)
*/
constexpr static auto getNeededAttr(std::false_type) {
return std::array<typename Particle::AttributeNames, 6>{
Particle::AttributeNames::mass, Particle::AttributeNames::posX, Particle::AttributeNames::posY,
Particle::AttributeNames::posZ, Particle::AttributeNames::smth, Particle::AttributeNames::ownershipState};
}
/**
* @copydoc Functor::getComputedAttr()
*/
constexpr static auto getComputedAttr() {
return std::array<typename Particle::AttributeNames, 1>{Particle::AttributeNames::density};
}
};
} // namespace autopas::sph
|
mish_kernel_arm.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: 942002795@qq.com
*/
#include "mish_kernel_arm.h"
#include "mish_math_func.h"
#include <math.h>
#include <arm_neon.h>
static void mish_kernel(int i, int id, void* data, const float* input, float* output)
{
int step = ((int*)data)[0];
const float* cur_input = input + id * step;
float* cur_output = output + id * step;
for (int i = 0; i < (step & -4); i += 4)
{
float32x4_t _input = vld1q_f32(cur_input);
float32x4_t out = vmulq_f32(_input, tanh_ps(log_ps(vaddq_f32(exp_ps(_input), vdupq_n_f32(1.f)))));
vst1q_f32(cur_output, out);
cur_input += 4;
cur_output += 4;
}
for (int i = step & ~3; i < step; i++)
{
float tmp = *input++;
*cur_output++ = tanh(log(exp(tmp) + 1.f));
}
}
int mish_run(struct tensor* output_tensor, struct tensor* input_tensor, int num_thread)
{
float* data = (float*)input_tensor->data;
float* out_data = (float*)output_tensor->data;
int chan_num = (input_tensor->dims[0]) * (input_tensor->dims[1]);
int chan_size = (input_tensor->dims[2]) * (input_tensor->dims[3]);
#pragma omp parallel for num_threads(num_thread)
for (int i = 0; i < chan_num; i++)
{
int offset = i * chan_size;
mish_kernel(0, 0, &chan_size, data + offset, out_data + offset);
}
return 0;
}
|
main-policy-vs-swap-mpi.c | /*****************************************************
* PROJECT : ummap-io-v2 *
* LICENSE : Apache 2.0 *
* COPYRIGHT: 2020-2021 Bull SAS All rights reserved *
*****************************************************/
//mpicc -O0 main-policy-vs-swap.c -I${HOME}/test-rdma/usr2/include -lummap-io -L${HOME}/test-rdma/usr2/lib -o main-policy-vs-swap -fopenmp
//OMP_NUM_THREADS=8 ./main-policy-vs-swap 15 172 4
#include <stdbool.h>
#include <ummap/ummap.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/mman.h>
#include <assert.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <omp.h>
#include <mpi.h>
//#define SEGMENT_SIZE (2048UL*1024UL)
#define SEGMENT_SIZE (256UL*1024UL)
#define POLICY "fifo://32MB"
#define OP(x) x += i
#define STEP 4096
static inline double timespec_diff(struct timespec *a, struct timespec *b) {
struct timespec result;
result.tv_sec = a->tv_sec - b->tv_sec;
result.tv_nsec = a->tv_nsec - b->tv_nsec;
if (result.tv_nsec < 0) {
--result.tv_sec;
result.tv_nsec += 1000000000L;
}
return (double)result.tv_sec + (double)result.tv_nsec / (double)1e9;
}
void test_malloc(size_t size, size_t repeat)
{
//get rank
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//start
if (rank ==0)
printf("Testing malloc...\n");
//alloc
char * ptr = malloc(size);
assert(ptr != NULL);
//wait wall
MPI_Barrier(MPI_COMM_WORLD);
//time
struct timespec start, stop;
clock_gettime(CLOCK_MONOTONIC, &start);
//loop
size_t i, r;
for (r = 0 ; r < repeat ; r++)
//#pragma omp parallel for
for (i = 0 ; i < size ; i+=STEP)
OP(ptr[i]);
//free
free(ptr);
//wait all
MPI_Barrier(MPI_COMM_WORLD);
//time
clock_gettime(CLOCK_MONOTONIC, &stop);
//print
if (rank == 0)
printf("Testing malloc: %0.03f seconds\n", timespec_diff(&stop, &start));
}
void test_mmap_file(size_t size, size_t repeat)
{
//get rank
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//displau
if (rank == 0)
printf("Testing file map...\n");
//open
char fname[256];
sprintf(fname, "/tmp/test-%d.raw", rank);
FILE * fp = fopen(fname, "w+");
ftruncate(fileno(fp), size);
//mmap
char * ptr = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fileno(fp), 0);
assert(ptr != MAP_FAILED);
//wait all
MPI_Barrier(MPI_COMM_WORLD);
//time
struct timespec start, stop;
clock_gettime(CLOCK_MONOTONIC, &start);
//process
size_t i, r;
for (r = 0 ; r < repeat ; r++)
//#pragma omp parallel for
for (i = 0 ; i < size ; i+=STEP)
OP(ptr[i]);
//sync
msync(ptr, size, MS_SYNC);
//unmap
munmap(ptr, size);
//close
fclose(fp);
//wait all
MPI_Barrier(MPI_COMM_WORLD);
//time
clock_gettime(CLOCK_MONOTONIC, &stop);
//print
if (rank == 0)
printf("Testing file map: %0.03f seconds\n", timespec_diff(&stop, &start));
}
void test_ummap(size_t size, size_t repeat)
{
//get rank
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//print
if (rank == 0)
printf("Testing ummap...\n");
//map
ummap_uri_set_variable_int("rank", rank);
ummap_driver_t * driver = ummap_driver_create_uri("ioc://10:2{rank}");
ummap_policy_t * policy = ummap_policy_create_uri(POLICY, true);
char * ptr = ummap(NULL, size, SEGMENT_SIZE, 0, PROT_READ | PROT_WRITE, 0, driver, policy, "none");
//wait all
MPI_Barrier(MPI_COMM_WORLD);
//start
struct timespec start, stop;
clock_gettime(CLOCK_MONOTONIC, &start);
//process
size_t i, r;
for (r = 0 ; r < repeat ; r++)
//#pragma omp parallel for
for (i = 0 ; i < size ; i+=STEP)
OP(ptr[i]);
//unmap
umunmap(ptr, true);
//wait all
MPI_Barrier(MPI_COMM_WORLD);
//time
clock_gettime(CLOCK_MONOTONIC, &stop);
//print
if (rank == 0)
printf("Testing ummap: %0.03f seconds\n", timespec_diff(&stop, &start));
}
int main(int argc, char ** argv)
{
//args
if (argc < 4) {
fprintf(stderr, "Usage: %s {seg_size} {baloon_size} {repeat}\n", argv[0]);
return EXIT_FAILURE;
}
//mpi
MPI_Init(&argc, &argv);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
//info
if (rank == 0) {
printf("============= Parameters ==============\n");
printf("Size : %0.02f GB\n", atof(argv[1]));
printf("Balloon : %0.02f GB\n", atof(argv[2]));
printf("Segment : %lu KB\n", SEGMENT_SIZE/1024UL);
printf("Policy : %s\n", POLICY);
printf("Repeat : %lu\n", atol(argv[3]));
printf("Ranks : %d\n", world_size);
}
//extract args
size_t size = atof(argv[1]) * 1024.0 * 1024.0 * 1024.0;
size_t balloon = atof(argv[2]) * 1024.0 * 1024.0 * 1024.0;
size_t repeat = atol(argv[3]);
//divide
size /= world_size;
size -= size % (SEGMENT_SIZE);
balloon /= world_size;
//init ummap
ummap_init();
ummap_config_ioc_init_options("10.1.3.85", "8556");
//test without ballon
if (rank == 0) printf("\n============= No balloon ==============\n");
test_ummap(size, repeat);
test_mmap_file(size, repeat);
test_malloc(size, repeat);
//ballon
if (rank == 0) printf("\n============ With balloon =============\n");
if (rank == 0) printf("Create balloon...\n");
MPI_Barrier(MPI_COMM_WORLD);
char * ptr = malloc(balloon);
size_t i;
for (i = 0 ; i < balloon ; i+= 4096)
ptr[i] = 1;
mlock(ptr, size);
MPI_Barrier(MPI_COMM_WORLD);
//test with balloon
test_ummap(size, repeat);
test_mmap_file(size, repeat);
test_malloc(size, repeat);
//free balloon
if (rank == 0) free(ptr);
//fini
ummap_finalize();
//mpi
MPI_Finalize();
//ok
return EXIT_SUCCESS;
}
|
prop3DAcoVTIDenQ_DEO2_FDTD.h | #ifndef PROP3DACOVTIDENQ_DEO2_FDTD_H
#define PROP3DACOVTIDENQ_DEO2_FDTD_H
#include <omp.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <fftw3.h>
#include <complex>
#include "propagatorStaticFunctions.h"
#define MIN(x,y) ((x)<(y)?(x):(y))
class Prop3DAcoVTIDenQ_DEO2_FDTD {
public:
const bool _freeSurface;
const long _nbx, _nby, _nbz, _nthread, _nx, _ny, _nz, _nsponge;
const float _dx, _dy, _dz, _dt;
const float _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz;
const float _fDefault = 0.85f;
float * __restrict__ _v = NULL;
float * __restrict__ _eps = NULL;
float * __restrict__ _eta = NULL;
float * __restrict__ _b = NULL;
float * __restrict__ _f = NULL;
float * __restrict__ _dtOmegaInvQ = NULL;
float * __restrict__ _pSpace = NULL;
float * __restrict__ _mSpace = NULL;
float * __restrict__ _tmpPx1 = NULL;
float * __restrict__ _tmpPy1 = NULL;
float * __restrict__ _tmpPz1 = NULL;
float * __restrict__ _tmpMx1 = NULL;
float * __restrict__ _tmpMy1 = NULL;
float * __restrict__ _tmpMz1 = NULL;
float * __restrict__ _tmpPx2 = NULL;
float * __restrict__ _tmpPy2 = NULL;
float * __restrict__ _tmpPz2 = NULL;
float * __restrict__ _tmpMx2 = NULL;
float * __restrict__ _tmpMy2 = NULL;
float * __restrict__ _tmpMz2 = NULL;
float * _pOld = NULL;
float * _pCur = NULL;
float * _mOld = NULL;
float * _mCur = NULL;
Prop3DAcoVTIDenQ_DEO2_FDTD(
bool freeSurface,
long nthread,
long nx,
long ny,
long nz,
long nsponge,
float dx,
float dy,
float dz,
float dt,
const long nbx,
const long nby,
const long nbz) :
_freeSurface(freeSurface),
_nthread(nthread),
_nx(nx),
_ny(ny),
_nz(nz),
_nsponge(nsponge),
_nbx(nbx),
_nby(nby),
_nbz(nbz),
_dx(dx),
_dy(dy),
_dz(dz),
_dt(dt),
_c8_1(+1225.0 / 1024.0),
_c8_2(-245.0 / 3072.0),
_c8_3(+49.0 / 5120.0),
_c8_4(-5.0 / 7168.0),
_invDx(1.0 / _dx),
_invDy(1.0 / _dy),
_invDz(1.0 / _dz) {
// Allocate arrays
_v = new float[_nx * _ny * _nz];
_eps = new float[_nx * _ny * _nz];
_eta = new float[_nx * _ny * _nz];
_b = new float[_nx * _ny * _nz];
_f = new float[_nx * _ny * _nz];
_dtOmegaInvQ = new float[_nx * _ny * _nz];
_pSpace = new float[_nx * _ny * _nz];
_mSpace = new float[_nx * _ny * _nz];
_tmpPx1 = new float[_nx * _ny * _nz];
_tmpPy1 = new float[_nx * _ny * _nz];
_tmpPz1 = new float[_nx * _ny * _nz];
_tmpMx1 = new float[_nx * _ny * _nz];
_tmpMy1 = new float[_nx * _ny * _nz];
_tmpMz1 = new float[_nx * _ny * _nz];
_tmpPx2 = new float[_nx * _ny * _nz];
_tmpPy2 = new float[_nx * _ny * _nz];
_tmpPz2 = new float[_nx * _ny * _nz];
_tmpMx2 = new float[_nx * _ny * _nz];
_tmpMy2 = new float[_nx * _ny * _nz];
_tmpMz2 = new float[_nx * _ny * _nz];
_pOld = new float[_nx * _ny * _nz];
_pCur = new float[_nx * _ny * _nz];
_mOld = new float[_nx * _ny * _nz];
_mCur = new float[_nx * _ny * _nz];
numaFirstTouch(_nx, _ny, _nz, _nthread, _v, _eps, _eta, _b,
_f, _dtOmegaInvQ, _pSpace, _mSpace,
_tmpPx1, _tmpPy1, _tmpPz1, _tmpMx1, _tmpMy1, _tmpMz1,
_tmpPx2, _tmpPy2, _tmpPz2, _tmpMx2, _tmpMy2, _tmpMz2,
_pOld, _pCur, _mOld, _mCur, _nbx, _nby, _nbz);
}
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void numaFirstTouch(
const long nx,
const long ny,
const long nz,
const long nthread,
float * __restrict__ v,
float * __restrict__ eps,
float * __restrict__ eta,
float * __restrict__ b,
float * __restrict__ f,
float * __restrict__ dtOmegaInvQ,
float * __restrict__ pSpace,
float * __restrict__ mSpace,
float * __restrict__ tmpPx1,
float * __restrict__ tmpPy1,
float * __restrict__ tmpPz1,
float * __restrict__ tmpMx1,
float * __restrict__ tmpMy1,
float * __restrict__ tmpMz1,
float * __restrict__ tmpPx2,
float * __restrict__ tmpPy2,
float * __restrict__ tmpPz2,
float * __restrict__ tmpMx2,
float * __restrict__ tmpMy2,
float * __restrict__ tmpMz2,
float * __restrict__ pOld,
float * __restrict__ pCur,
float * __restrict__ mOld,
float * __restrict__ mCur,
const long BX_3D,
const long BY_3D,
const long BZ_3D) {
const long nx4 = nx - 4;
const long ny4 = ny - 4;
const long nz4 = nz - 4;
#pragma omp parallel for collapse(3) num_threads(nthread) schedule(static)
for (long bx = 4; bx < nx4; bx += BX_3D) {
for (long by = 4; by < ny4; by += BY_3D) {
for (long bz = 4; bz < nz4; bz += BZ_3D) {
const long kxmax = MIN(bx + BX_3D, nx4);
const long kymax = MIN(by + BY_3D, ny4);
const long kzmax = MIN(bz + BZ_3D, nz4);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
v[k] = 0;
eps[k] = 0;
eta[k] = 0;
b[k] = 0;
f[k] = 0;
dtOmegaInvQ[k] = 0;
pSpace[k] = 0;
mSpace[k] = 0;
tmpPx1[k] = 0;
tmpPy1[k] = 0;
tmpPz1[k] = 0;
tmpMx1[k] = 0;
tmpMy1[k] = 0;
tmpMz1[k] = 0;
tmpPx2[k] = 0;
tmpPy2[k] = 0;
tmpPz2[k] = 0;
tmpMx2[k] = 0;
tmpMy2[k] = 0;
tmpMz2[k] = 0;
pOld[k] = 0;
pCur[k] = 0;
mOld[k] = 0;
mCur[k] = 0;
}
}
}
}
}
}
// annulus
for (long k = 0; k < 4; k++) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long ky = 0; ky < ny; ky++) {
const long kindex1 = kx * ny * nz + ky * nz + k;
const long kindex2 = kx * ny * nz + ky * nz + (nz - 1 - k);
v[kindex1] = eps[kindex1] = eta[kindex1] = b[kindex1] = f[kindex1] =
dtOmegaInvQ[kindex1] = pSpace[kindex1] = mSpace[kindex1] =
tmpPx1[kindex1] = tmpPy1[kindex1] = tmpPz1[kindex1] = tmpMx1[kindex1] =
tmpMy1[kindex1] = tmpMz1[kindex1] = tmpPx2[kindex1] = tmpPy2[kindex1] =
tmpPz2[kindex1] = tmpMx2[kindex1] = tmpMy2[kindex1] = tmpMz2[kindex1] =
pOld[kindex1] = pCur[kindex1] = mOld[kindex1] = mCur[kindex1] = 0;
v[kindex2] = eps[kindex2] = eta[kindex2] = b[kindex2] = f[kindex2] =
dtOmegaInvQ[kindex2] = pSpace[kindex2] = mSpace[kindex2] =
tmpPx1[kindex2] = tmpPy1[kindex2] = tmpPz1[kindex2] = tmpMx1[kindex2] =
tmpMy1[kindex2] = tmpMz1[kindex2] = tmpPx2[kindex2] = tmpPy2[kindex2] =
tmpPz2[kindex2] = tmpMx2[kindex2] = tmpMy2[kindex2] = tmpMz2[kindex2] =
pOld[kindex2] = pCur[kindex2] = mOld[kindex2] = mCur[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = kx * ny * nz + k * nz + kz;
const long kindex2 = kx * ny * nz + (ny - 1 - k) * nz + kz;
v[kindex1] = eps[kindex1] = eta[kindex1] = b[kindex1] = f[kindex1] =
dtOmegaInvQ[kindex1] = pSpace[kindex1] = mSpace[kindex1] =
tmpPx1[kindex1] = tmpPy1[kindex1] = tmpPz1[kindex1] = tmpMx1[kindex1] =
tmpMy1[kindex1] = tmpMz1[kindex1] = tmpPx2[kindex1] = tmpPy2[kindex1] =
tmpPz2[kindex1] = tmpMx2[kindex1] = tmpMy2[kindex1] = tmpMz2[kindex1] =
pOld[kindex1] = pCur[kindex1] = mOld[kindex1] = mCur[kindex1] = 0;
v[kindex2] = eps[kindex2] = eta[kindex2] = b[kindex2] = f[kindex2] =
dtOmegaInvQ[kindex2] = pSpace[kindex2] = mSpace[kindex2] =
tmpPx1[kindex2] = tmpPy1[kindex2] = tmpPz1[kindex2] = tmpMx1[kindex2] =
tmpMy1[kindex2] = tmpMz1[kindex2] = tmpPx2[kindex2] = tmpPy2[kindex2] =
tmpPz2[kindex2] = tmpMx2[kindex2] = tmpMy2[kindex2] = tmpMz2[kindex2] =
pOld[kindex2] = pCur[kindex2] = mOld[kindex2] = mCur[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long ky = 0; ky < ny; ky++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = k * ny * nz + ky * nz + kz;
const long kindex2 = (nx - 1 - k) * ny * nz + ky * nz + kz;
v[kindex1] = eps[kindex1] = eta[kindex1] = b[kindex1] = f[kindex1] =
dtOmegaInvQ[kindex1] = pSpace[kindex1] = mSpace[kindex1] =
tmpPx1[kindex1] = tmpPy1[kindex1] = tmpPz1[kindex1] = tmpMx1[kindex1] =
tmpMy1[kindex1] = tmpMz1[kindex1] = tmpPx2[kindex1] = tmpPy2[kindex1] =
tmpPz2[kindex1] = tmpMx2[kindex1] = tmpMy2[kindex1] = tmpMz2[kindex1] =
pOld[kindex1] = pCur[kindex1] = mOld[kindex1] = mCur[kindex1] = 0;
v[kindex2] = eps[kindex2] = eta[kindex2] = b[kindex2] = f[kindex2] =
dtOmegaInvQ[kindex2] = pSpace[kindex2] = mSpace[kindex2] =
tmpPx1[kindex2] = tmpPy1[kindex2] = tmpPz1[kindex2] = tmpMx1[kindex2] =
tmpMy1[kindex2] = tmpMz1[kindex2] = tmpPx2[kindex2] = tmpPy2[kindex2] =
tmpPz2[kindex2] = tmpMx2[kindex2] = tmpMy2[kindex2] = tmpMz2[kindex2] =
pOld[kindex2] = pCur[kindex2] = mOld[kindex2] = mCur[kindex2] = 0;
}
}
}
}
~Prop3DAcoVTIDenQ_DEO2_FDTD() {
if (_v != NULL) delete [] _v;
if (_eps != NULL) delete [] _eps;
if (_eta != NULL) delete [] _eta;
if (_b != NULL) delete [] _b;
if (_f != NULL) delete [] _f;
if (_dtOmegaInvQ != NULL) delete [] _dtOmegaInvQ;
if (_pSpace != NULL) delete [] _pSpace;
if (_mSpace != NULL) delete [] _mSpace;
if (_tmpPx1 != NULL) delete [] _tmpPx1;
if (_tmpPy1 != NULL) delete [] _tmpPy1;
if (_tmpPz1 != NULL) delete [] _tmpPz1;
if (_tmpMx1 != NULL) delete [] _tmpMx1;
if (_tmpMy1 != NULL) delete [] _tmpMy1;
if (_tmpMz1 != NULL) delete [] _tmpMz1;
if (_tmpPx2 != NULL) delete [] _tmpPx2;
if (_tmpPy2 != NULL) delete [] _tmpPy2;
if (_tmpPz2 != NULL) delete [] _tmpPz2;
if (_tmpMx2 != NULL) delete [] _tmpMx2;
if (_tmpMy2 != NULL) delete [] _tmpMy2;
if (_tmpMz2 != NULL) delete [] _tmpMz2;
if (_pOld != NULL) delete [] _pOld;
if (_pCur != NULL) delete [] _pCur;
if (_mOld != NULL) delete [] _mOld;
if (_mCur != NULL) delete [] _mCur;
}
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
void info() {
printf("\n");
printf("Prop3DAcoVTIDenQ_DEO2_FDTD\n");
printf(" nx,ny,nz; %5ld %5ld %5ld\n", _nx, _ny, _nz);
printf(" nthread,nsponge,fs; %5ld %5ld %5d\n", _nthread, _nsponge, _freeSurface);
printf(" X min,max,inc; %+16.8f %+16.8f %+16.8f\n", 0.0, _dx * (_nx - 1), _dx);
printf(" Y min,max,inc; %+16.8f %+16.8f %+16.8f\n", 0.0, _dy * (_ny - 1), _dy);
printf(" Z min,max,inc; %+16.8f %+16.8f %+16.8f\n", 0.0, _dz * (_nz - 1), _dz);
}
/**
* Notes
* - User must have called setupDtOmegaInvQ_2D to initialize the array _dtOmegaInvQ
* - wavefield arrays are switched in this call
* pCur -> pOld
* pOld -> pCur
* mCur -> mOld
* mOld -> mCur
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void timeStep() {
applyFirstDerivatives3D_PlusHalf_Sandwich(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_pCur, _pCur, _pCur, _mCur, _mCur, _mCur, _eps, _eta, _f, _b,
_tmpPx1, _tmpPy1, _tmpPz1, _tmpMx1, _tmpMy1, _tmpMz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_MinusHalf_TimeUpdate_Nonlinear(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz, _dt,
_tmpPx1, _tmpPy1, _tmpPz1, _tmpMx1, _tmpMy1, _tmpMz1, _v, _b, _dtOmegaInvQ,
_pCur, _mCur, _pSpace, _mSpace, _pOld, _mOld, _nbx, _nby, _nbz);
// swap pointers
float *pswap = _pOld;
_pOld = _pCur;
_pCur = pswap;
float *mswap = _mOld;
_mOld = _mCur;
_mCur = mswap;
}
/**
* Same as above, but does not collect the spatial derivatives
* Note this is only used in the PSD operators, where the first (transient) time steps do
* not need to save the P'' term
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void timeStepLinear() {
applyFirstDerivatives3D_PlusHalf_Sandwich(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_pCur, _pCur, _pCur, _mCur, _mCur, _mCur, _eps, _eta, _f, _b,
_tmpPx1, _tmpPy1, _tmpPz1, _tmpMx1, _tmpMy1, _tmpMz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_MinusHalf_TimeUpdate_Linear(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz, _dt,
_tmpPx1, _tmpPy1, _tmpPz1, _tmpMx1, _tmpMy1, _tmpMz1, _v, _b, _dtOmegaInvQ,
_pCur, _mCur, _pOld, _mOld, _nbx, _nby, _nbz);
// swap pointers
float *pswap = _pOld;
_pOld = _pCur;
_pCur = pswap;
float *mswap = _mOld;
_mOld = _mCur;
_mCur = mswap;
}
/**
* Scale spatial derivatives by v^2/b to make them temporal derivs
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void scaleSpatialDerivatives() {
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float v2OverB = _v[k] * _v[k] / _b[k];
_pSpace[k] *= v2OverB;
_mSpace[k] *= v2OverB;
}
}
}
}
}
}
}
/**
* Add the Born source at the current time
*
* User must have:
* - called the nonlinear forward
* - saved 2nd time derivative of pressure at corresponding time index in array dp2
* - Born source term will be injected into the _pCur array
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void forwardBornInjection_V(float *dVel, float *wavefieldDP, float *wavefieldDM) {
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float B = _b[k];
const float dV = dVel[k];
// V^2/b factor to "clear" the b/V^2 factor on L_tP and L_tM
// _dt^2 factor is from the finite difference approximation
// 2B_dV/V^3 factor is from the linearization
const float factor = 2 * _dt * _dt * dV / V;
_pCur[k] += factor * wavefieldDP[k];
_mCur[k] += factor * wavefieldDM[k];
}
}
}
}
}
}
}
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void forwardBornInjection_VEA(float *dVel, float *dEps, float *dEta,
float *wavefieldP, float *wavefieldM, float *wavefieldDP, float *wavefieldDM) {
// Right side spatial derivatives for the Born source
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
wavefieldP, wavefieldP, wavefieldP, _tmpPx1, _tmpPy1, _tmpPz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
wavefieldM, wavefieldM, wavefieldM, _tmpMx1, _tmpMy1, _tmpMz1, _nbx, _nby, _nbz);
// Sandwich terms for the Born source
// note flipped sign for Z derivative term between P and M
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float E = _eps[k];
const float A = _eta[k];
const float B = _b[k];
const float F = _f[k];
const float dV = dVel[k];
const float dE = dEps[k];
const float dA = dEta[k];
_tmpPx2[k] = (+2 * B * dE) *_tmpPx1[k];
_tmpPy2[k] = (+2 * B * dE) *_tmpPy1[k];
_tmpPz2[k] = (-2 * B * F * A * dA) *_tmpPz1[k] +
(dA * B * F * (1 - 2 * A * A) / sqrt(1 - A * A)) * _tmpMz1[k];
_tmpMx2[k] = 0;
_tmpMy2[k] = 0;
_tmpMz2[k] = (+2 * B * F * A * dA) *_tmpMz1[k] +
(dA * B * F * (1 - 2 * A * A) / sqrt(1 - A * A)) * _tmpPz1[k];
}
}
}
}
}
}
// Left side spatial derivatives for the Born source
applyFirstDerivatives3D_MinusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_tmpPx2, _tmpPy2, _tmpPz2, _tmpPx1, _tmpPy1, _tmpPz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_MinusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_tmpMx2, _tmpMy2, _tmpMz2, _tmpMx1, _tmpMy1, _tmpMz1, _nbx, _nby, _nbz);
// add the born source at the current time
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float B = _b[k];
const float dV = dVel[k];
const float dt2v2OverB = _dt * _dt * V * V / B;
const float factor = 2 * B * dV / (V * V * V);
_pCur[k] += dt2v2OverB * (factor * wavefieldDP[k] + _tmpPx1[k] + _tmpPy1[k] + _tmpPz1[k]);
_mCur[k] += dt2v2OverB * (factor * wavefieldDM[k] + _tmpMx1[k] + _tmpMy1[k] + _tmpMz1[k]);
}
}
}
}
}
}
}
/**
* Accumulate the Born image term at the current time
*
* User must have:
* - called the nonlinear forward
* - saved 2nd time derivative of pressure at corresponding time index in array dp2
* - Born image term will be accumulated iu the _dm array
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void adjointBornAccumulation_V(float *dVel,
float *wavefieldDP, float *wavefieldDM) {
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float B = _b[k];
const float factor = 2 * B / (V * V * V);
dVel[k] += factor * (wavefieldDP[k] * _pOld[k] + wavefieldDM[k] * _mOld[k]);
}
}
}
}
}
}
}
/**
* Apply Kz wavenumber filter for up/down wavefield seperation
* Faqi, 2011, Geophysics https://library.seg.org/doi/full/10.1190/1.3533914
*
* We handle the FWI and RTM imaging conditions with a condition inside the OMP loop
*
* Example Kz filtering with 8 samples
* frequency | +0 | +1 | +2 | +3 | N | -3 | -2 | -1 |
* original | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
* upgoing | 0 | X | X | X | 4 | 5 | 6 | 7 |
* dngoing | 0 | 1 | 2 | 3 | 4 | X | X | X |
*/
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void adjointBornAccumulation_wavefieldsep_V(float *dVel,
float *wavefieldDP, float *wavefieldDM, const long isFWI) {
const long nfft = 2 * _nz;
const float scale = 1.0f / (float)(nfft);
// FWI: adj wavefield is dngoing
// RTM: adj wavefield is upgoing
const long kfft_adj = (isFWI) ? 0 : nfft / 2;
std::complex<float> * __restrict__ tmp = new std::complex<float>[nfft];
fftwf_plan planForward = fftwf_plan_dft_1d(nfft,
reinterpret_cast<fftwf_complex*>(tmp),
reinterpret_cast<fftwf_complex*>(tmp), +1, FFTW_ESTIMATE);
fftwf_plan planInverse = fftwf_plan_dft_1d(nfft,
reinterpret_cast<fftwf_complex*>(tmp),
reinterpret_cast<fftwf_complex*>(tmp), -1, FFTW_ESTIMATE);
delete [] tmp;
#pragma omp parallel num_threads(_nthread)
{
std::complex<float> * __restrict__ tmp_nlf_p = new std::complex<float>[nfft];
std::complex<float> * __restrict__ tmp_adj_p = new std::complex<float>[nfft];
std::complex<float> * __restrict__ tmp_nlf_m = new std::complex<float>[nfft];
std::complex<float> * __restrict__ tmp_adj_m = new std::complex<float>[nfft];
#pragma omp for collapse(2) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kfft = 0; kfft < nfft; kfft++) {
tmp_nlf_p[kfft] = 0;
tmp_adj_p[kfft] = 0;
tmp_nlf_m[kfft] = 0;
tmp_adj_m[kfft] = 0;
}
#pragma omp simd
for (long kz = 0; kz < _nz; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
tmp_nlf_p[kz] = scale * wavefieldDP[k];
tmp_adj_p[kz] = scale * _pOld[k];
tmp_nlf_m[kz] = scale * wavefieldDM[k];
tmp_adj_m[kz] = scale * _mOld[k];
}
fftwf_execute_dft(planForward,
reinterpret_cast<fftwf_complex*>(tmp_nlf_p),
reinterpret_cast<fftwf_complex*>(tmp_nlf_p));
fftwf_execute_dft(planForward,
reinterpret_cast<fftwf_complex*>(tmp_adj_p),
reinterpret_cast<fftwf_complex*>(tmp_adj_p));
fftwf_execute_dft(planForward,
reinterpret_cast<fftwf_complex*>(tmp_nlf_m),
reinterpret_cast<fftwf_complex*>(tmp_nlf_m));
fftwf_execute_dft(planForward,
reinterpret_cast<fftwf_complex*>(tmp_adj_m),
reinterpret_cast<fftwf_complex*>(tmp_adj_m));
// upgoing: zero the positive frequencies, excluding Nyquist
// dngoing: zero the negative frequencies, excluding Nyquist
#pragma omp simd
for (long k = 1; k < nfft / 2; k++) {
tmp_nlf_p[nfft / 2 + k] = 0;
tmp_adj_p[kfft_adj + k] = 0;
tmp_nlf_m[nfft / 2 + k] = 0;
tmp_adj_m[kfft_adj + k] = 0;
}
fftwf_execute_dft(planInverse,
reinterpret_cast<fftwf_complex*>(tmp_nlf_p),
reinterpret_cast<fftwf_complex*>(tmp_nlf_p));
fftwf_execute_dft(planInverse,
reinterpret_cast<fftwf_complex*>(tmp_adj_p),
reinterpret_cast<fftwf_complex*>(tmp_adj_p));
fftwf_execute_dft(planInverse,
reinterpret_cast<fftwf_complex*>(tmp_nlf_m),
reinterpret_cast<fftwf_complex*>(tmp_nlf_m));
fftwf_execute_dft(planInverse,
reinterpret_cast<fftwf_complex*>(tmp_adj_m),
reinterpret_cast<fftwf_complex*>(tmp_adj_m));
// Faqi eq 10
// Applied to FWI: [Sup * Rdn]
// Applied to RTM: [Sup * Rup]
#pragma omp simd
for (long kz = 0; kz < _nz; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float B = _b[k];
const float factor = 2 * B / (V * V * V);
dVel[k] += factor * (real(tmp_nlf_p[kz] * tmp_adj_p[kz]) + real(tmp_nlf_m[kz] * tmp_adj_m[kz]));
}
} // end loop over ky
} // end loop over kx
} // end loop over by
} // end loop over bx
delete [] tmp_nlf_p;
delete [] tmp_adj_p;
delete [] tmp_nlf_m;
delete [] tmp_adj_m;
} // end parallel region
fftwf_destroy_plan(planForward);
fftwf_destroy_plan(planInverse);
}
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline void adjointBornAccumulation_VEA(float *dVel, float *dEps, float *dEta,
float *wavefieldP, float *wavefieldM, float *wavefieldDP, float *wavefieldDM) {
// Right side spatial derivatives for the adjoint accumulation
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
wavefieldP, wavefieldP, wavefieldP, _tmpPx1, _tmpPy1, _tmpPz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
wavefieldM, wavefieldM, wavefieldM, _tmpMx1, _tmpMy1, _tmpMz1, _nbx, _nby, _nbz);
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_pOld, _pOld, _pOld, _tmpPx2, _tmpPy2, _tmpPz2, _nbx, _nby, _nbz);
applyFirstDerivatives3D_PlusHalf(
_freeSurface, _nx, _ny, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDy, _invDz,
_mOld, _mOld, _mOld, _tmpMx2, _tmpMy2, _tmpMz2, _nbx, _nby, _nbz);
// Sandwich terms for the adjoint accumulation
#pragma omp parallel for collapse(3) num_threads(_nthread) schedule(static)
for (long bx = 0; bx < _nx; bx += _nbx) {
for (long by = 0; by < _ny; by += _nby) {
for (long bz = 0; bz < _nz; bz += _nbz) {
const long kxmax = MIN(bx + _nbx, _nx);
const long kymax = MIN(by + _nby, _ny);
const long kzmax = MIN(bz + _nbz, _nz);
for (long kx = bx; kx < kxmax; kx++) {
for (long ky = by; ky < kymax; ky++) {
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kx * _ny * _nz + ky * _nz + kz;
const float V = _v[k];
const float E = _eps[k];
const float A = _eta[k];
const float B = _b[k];
const float F = _f[k];
const float factor = 2 * B / (V * V * V);
dVel[k] += factor * (wavefieldDP[k] * _pOld[k] + wavefieldDM[k] * _mOld[k]);
dEps[k] += (-2 * B * _tmpPx1[k] * _tmpPx2[k] -2 * B * _tmpPy1[k] * _tmpPy2[k]);
const float partP = 2 * B * F * A * _tmpPz1[k] - (B * F * (1 - 2 * A * A) / sqrt(1 - A * A)) * _tmpMz1[k];
const float partM = 2 * B * F * A * _tmpMz1[k] + (B * F * (1 - 2 * A * A) / sqrt(1 - A * A)) * _tmpPz1[k];
dEta[k] += (partP * _tmpPz2[k] - partM * _tmpMz2[k]);
}
}
}
}
}
}
}
template<class Type>
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline static void applyFirstDerivatives3D_PlusHalf_Sandwich(
const long freeSurface,
const long nx,
const long ny,
const long nz,
const long nthread,
const Type c8_1,
const Type c8_2,
const Type c8_3,
const Type c8_4,
const Type invDx,
const Type invDy,
const Type invDz,
const Type * __restrict__ const inPX,
const Type * __restrict__ const inPY,
const Type * __restrict__ const inPZ,
const Type * __restrict__ const inMX,
const Type * __restrict__ const inMY,
const Type * __restrict__ const inMZ,
const Type * __restrict__ const fieldEps,
const Type * __restrict__ const fieldEta,
const Type * __restrict__ const fieldVsVp,
const Type * __restrict__ const fieldBuoy,
Type * __restrict__ tmpPX,
Type * __restrict__ tmpPY,
Type * __restrict__ tmpPZ,
Type * __restrict__ tmpMX,
Type * __restrict__ tmpMY,
Type * __restrict__ tmpMZ,
const long BX_3D,
const long BY_3D,
const long BZ_3D) {
const long nx4 = nx - 4;
const long ny4 = ny - 4;
const long nz4 = nz - 4;
const long nynz = ny * nz;
// zero output array: note only the annulus that is in the absorbing boundary needs to be zeroed
for (long k = 0; k < 4; k++) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long ky = 0; ky < ny; ky++) {
const long kindex1 = kx * ny * nz + ky * nz + k;
const long kindex2 = kx * ny * nz + ky * nz + (nz - 1 - k);
tmpPX[kindex1] = tmpPX[kindex2] = 0;
tmpPY[kindex1] = tmpPY[kindex2] = 0;
tmpPZ[kindex1] = tmpPZ[kindex2] = 0;
tmpMX[kindex1] = tmpMX[kindex2] = 0;
tmpMY[kindex1] = tmpMY[kindex2] = 0;
tmpMZ[kindex1] = tmpMZ[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = kx * ny * nz + k * nz + kz;
const long kindex2 = kx * ny * nz + (ny - 1 - k) * nz + kz;
tmpPX[kindex1] = tmpPX[kindex2] = 0;
tmpPY[kindex1] = tmpPY[kindex2] = 0;
tmpPZ[kindex1] = tmpPZ[kindex2] = 0;
tmpMX[kindex1] = tmpMX[kindex2] = 0;
tmpMY[kindex1] = tmpMY[kindex2] = 0;
tmpMZ[kindex1] = tmpMZ[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long ky = 0; ky < ny; ky++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = k * ny * nz + ky * nz + kz;
const long kindex2 = (nx - 1 - k) * ny * nz + ky * nz + kz;
tmpPX[kindex1] = tmpPX[kindex2] = 0;
tmpPY[kindex1] = tmpPY[kindex2] = 0;
tmpPZ[kindex1] = tmpPZ[kindex2] = 0;
tmpMX[kindex1] = tmpMX[kindex2] = 0;
tmpMY[kindex1] = tmpMY[kindex2] = 0;
tmpMZ[kindex1] = tmpMZ[kindex2] = 0;
}
}
}
// interior
#pragma omp parallel for collapse(3) num_threads(nthread) schedule(static)
for (long bx = 4; bx < nx4; bx += BX_3D) {
for (long by = 4; by < ny4; by += BY_3D) {
for (long bz = 4; bz < nz4; bz += BZ_3D) {
const long kxmax = MIN(bx + BX_3D, nx4);
const long kymax = MIN(by + BY_3D, ny4);
const long kzmax = MIN(bz + BZ_3D, nz4);
for (long kx = bx; kx < kxmax; kx++) {
const long kxnynz = kx * nynz;
for (long ky = by; ky < kymax; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kxnynz_kynz + kz;
const long kynz_kz = + kynz + kz;
const float stencilDPx =
c8_1 * (- inPX[(kx+0) * nynz + kynz_kz] + inPX[(kx+1) * nynz + kynz_kz]) +
c8_2 * (- inPX[(kx-1) * nynz + kynz_kz] + inPX[(kx+2) * nynz + kynz_kz]) +
c8_3 * (- inPX[(kx-2) * nynz + kynz_kz] + inPX[(kx+3) * nynz + kynz_kz]) +
c8_4 * (- inPX[(kx-3) * nynz + kynz_kz] + inPX[(kx+4) * nynz + kynz_kz]);
const float stencilDPy =
c8_1 * (- inPY[kxnynz + (ky+0) * nz + kz] + inPY[kxnynz + (ky+1) * nz + kz]) +
c8_2 * (- inPY[kxnynz + (ky-1) * nz + kz] + inPY[kxnynz + (ky+2) * nz + kz]) +
c8_3 * (- inPY[kxnynz + (ky-2) * nz + kz] + inPY[kxnynz + (ky+3) * nz + kz]) +
c8_4 * (- inPY[kxnynz + (ky-3) * nz + kz] + inPY[kxnynz + (ky+4) * nz + kz]);
const float stencilDPz =
c8_1 * (- inPZ[kxnynz_kynz + (kz+0)] + inPZ[kxnynz_kynz + (kz+1)]) +
c8_2 * (- inPZ[kxnynz_kynz + (kz-1)] + inPZ[kxnynz_kynz + (kz+2)]) +
c8_3 * (- inPZ[kxnynz_kynz + (kz-2)] + inPZ[kxnynz_kynz + (kz+3)]) +
c8_4 * (- inPZ[kxnynz_kynz + (kz-3)] + inPZ[kxnynz_kynz + (kz+4)]);
const float stencilDMx =
c8_1 * (- inMX[(kx+0) * nynz + kynz_kz] + inMX[(kx+1) * nynz + kynz_kz]) +
c8_2 * (- inMX[(kx-1) * nynz + kynz_kz] + inMX[(kx+2) * nynz + kynz_kz]) +
c8_3 * (- inMX[(kx-2) * nynz + kynz_kz] + inMX[(kx+3) * nynz + kynz_kz]) +
c8_4 * (- inMX[(kx-3) * nynz + kynz_kz] + inMX[(kx+4) * nynz + kynz_kz]);
const float stencilDMy =
c8_1 * (- inMY[kxnynz + (ky+0) * nz + kz] + inMY[kxnynz + (ky+1) * nz + kz]) +
c8_2 * (- inMY[kxnynz + (ky-1) * nz + kz] + inMY[kxnynz + (ky+2) * nz + kz]) +
c8_3 * (- inMY[kxnynz + (ky-2) * nz + kz] + inMY[kxnynz + (ky+3) * nz + kz]) +
c8_4 * (- inMY[kxnynz + (ky-3) * nz + kz] + inMY[kxnynz + (ky+4) * nz + kz]);
const float stencilDMz =
c8_1 * (- inMZ[kxnynz_kynz + (kz+0)] + inMZ[kxnynz_kynz + (kz+1)]) +
c8_2 * (- inMZ[kxnynz_kynz + (kz-1)] + inMZ[kxnynz_kynz + (kz+2)]) +
c8_3 * (- inMZ[kxnynz_kynz + (kz-2)] + inMZ[kxnynz_kynz + (kz+3)]) +
c8_4 * (- inMZ[kxnynz_kynz + (kz-3)] + inMZ[kxnynz_kynz + (kz+4)]);
const float dPx = invDx * stencilDPx;
const float dPy = invDy * stencilDPy;
const float dPz = invDz * stencilDPz;
const float dMx = invDx * stencilDMx;
const float dMy = invDy * stencilDMy;
const float dMz = invDz * stencilDMz;
const float E = 1 + 2 * fieldEps[k];
const float A = fieldEta[k];
const float F = fieldVsVp[k];
const float B = fieldBuoy[k];
const float SA2 = sqrt(1 - A * A);
tmpPX[k] = B * E * dPx;
tmpPY[k] = B * E * dPy;
tmpPZ[k] = B * (1 - F * A * A) * dPz + B * (F * A * SA2) * dMz;
tmpMX[k] = B * (1 - F) * dMx;
tmpMY[k] = B * (1 - F) * dMy;
tmpMZ[k] = B * F * A * SA2 * dPz + B * (1 - F + F * A * A) * dMz;
}
}
}
}
}
}
// roll on free surface
if (freeSurface) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 4; kx < nx4; kx++) {
const long kxnynz = kx * nynz;
#pragma omp simd
for (long ky = 4; ky < ny4; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
// kz = 0 -- 1/2 cells below free surface for Z derivative, at free surface for X/Y derivative
// X and Y derivatives are identically zero
// [kxnynz_kynz + 0]
{
const Type stencilDPz0 =
c8_1 * (- inPZ[kxnynz_kynz + 0] + inPZ[kxnynz_kynz + 1]) +
c8_2 * (+ inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 2]) +
c8_3 * (+ inPZ[kxnynz_kynz + 2] + inPZ[kxnynz_kynz + 3]) +
c8_4 * (+ inPZ[kxnynz_kynz + 3] + inPZ[kxnynz_kynz + 4]);
const Type dPX = 0;
const Type dPY = 0;
const Type dPZ = invDz * stencilDPz0;
const Type stencilDMz0 =
c8_1 * (- inMZ[kxnynz_kynz + 0] + inMZ[kxnynz_kynz + 1]) +
c8_2 * (+ inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 2]) +
c8_3 * (+ inMZ[kxnynz_kynz + 2] + inMZ[kxnynz_kynz + 3]) +
c8_4 * (+ inMZ[kxnynz_kynz + 3] + inMZ[kxnynz_kynz + 4]);
const Type dMX = 0;
const Type dMY = 0;
const Type dMZ = invDz * stencilDMz0;
const long k = kxnynz_kynz + 0;
const Type E = 1 + 2 * fieldEps[k];
const Type A = fieldEta[k];
const Type F = fieldVsVp[k];
const Type B = fieldBuoy[k];
const Type SA2 = sqrt(1 - A * A);
tmpPX[k] = B * E * dPX;
tmpPY[k] = B * E * dPY;
tmpPZ[k] = B * (1 - F * A * A) * dPZ + B * (F * A * SA2) * dMZ;
tmpMX[k] = B * (1 - F) * dMX;
tmpMY[k] = B * (1 - F) * dMY;
tmpMZ[k] = B * F * A * SA2 * dPZ + B * (1 - F + F * A * A) * dMZ;
}
// kz = 1 -- 1 1/2 cells below free surface for Z derivative, 1 cells below for X/Y derivative
// [kxnynz_kynz + 1]
{
const Type stencilDPx1 =
c8_1 * (- inPX[(kx+0) * nynz + kynz + 1] + inPX[(kx+1) * nynz + kynz + 1]) +
c8_2 * (- inPX[(kx-1) * nynz + kynz + 1] + inPX[(kx+2) * nynz + kynz + 1]) +
c8_3 * (- inPX[(kx-2) * nynz + kynz + 1] + inPX[(kx+3) * nynz + kynz + 1]) +
c8_4 * (- inPX[(kx-3) * nynz + kynz + 1] + inPX[(kx+4) * nynz + kynz + 1]);
const Type stencilDPy1 =
c8_1 * (- inPY[kxnynz + (ky+0) * nz + 1] + inPY[kxnynz + (ky+1) * nz + 1]) +
c8_2 * (- inPY[kxnynz + (ky-1) * nz + 1] + inPY[kxnynz + (ky+2) * nz + 1]) +
c8_3 * (- inPY[kxnynz + (ky-2) * nz + 1] + inPY[kxnynz + (ky+3) * nz + 1]) +
c8_4 * (- inPY[kxnynz + (ky-3) * nz + 1] + inPY[kxnynz + (ky+4) * nz + 1]);
const Type stencilDPz1 =
c8_1 * (- inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 2]) +
c8_2 * (- inPZ[kxnynz_kynz + 0] + inPZ[kxnynz_kynz + 3]) +
c8_3 * (+ inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 4]) +
c8_4 * (+ inPZ[kxnynz_kynz + 2] + inPZ[kxnynz_kynz + 5]);
const Type dPX = invDx * stencilDPx1;
const Type dPY = invDy * stencilDPy1;
const Type dPZ = invDz * stencilDPz1;
const Type stencilDMx1 =
c8_1 * (- inMX[(kx+0) * nynz + kynz + 1] + inMX[(kx+1) * nynz + kynz + 1]) +
c8_2 * (- inMX[(kx-1) * nynz + kynz + 1] + inMX[(kx+2) * nynz + kynz + 1]) +
c8_3 * (- inMX[(kx-2) * nynz + kynz + 1] + inMX[(kx+3) * nynz + kynz + 1]) +
c8_4 * (- inMX[(kx-3) * nynz + kynz + 1] + inMX[(kx+4) * nynz + kynz + 1]);
const Type stencilDMy1 =
c8_1 * (- inMY[kxnynz + (ky+0) * nz + 1] + inMY[kxnynz + (ky+1) * nz + 1]) +
c8_2 * (- inMY[kxnynz + (ky-1) * nz + 1] + inMY[kxnynz + (ky+2) * nz + 1]) +
c8_3 * (- inMY[kxnynz + (ky-2) * nz + 1] + inMY[kxnynz + (ky+3) * nz + 1]) +
c8_4 * (- inMY[kxnynz + (ky-3) * nz + 1] + inMY[kxnynz + (ky+4) * nz + 1]);
const Type stencilDMz1 =
c8_1 * (- inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 2]) +
c8_2 * (- inMZ[kxnynz_kynz + 0] + inMZ[kxnynz_kynz + 3]) +
c8_3 * (+ inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 4]) +
c8_4 * (+ inMZ[kxnynz_kynz + 2] + inMZ[kxnynz_kynz + 5]);
const Type dMX = invDx * stencilDMx1;
const Type dMY = invDy * stencilDMy1;
const Type dMZ = invDz * stencilDMz1;
const long k = kxnynz_kynz + 1;
const Type E = 1 + 2 * fieldEps[k];
const Type A = fieldEta[k];
const Type F = fieldVsVp[k];
const Type B = fieldBuoy[k];
const Type SA2 = sqrt(1 - A * A);
tmpPX[k] = B * E * dPX;
tmpPY[k] = B * E * dPY;
tmpPZ[k] = B * (1 - F * A * A) * dPZ + B * (F * A * SA2) * dMZ;
tmpMX[k] = B * (1 - F) * dMX;
tmpMY[k] = B * (1 - F) * dMY;
tmpMZ[k] = B * F * A * SA2 * dPZ + B * (1 - F + F * A * A) * dMZ;
}
// kz = 2 -- 2 1/2 cells below free surface for Z derivative, 2 cells below for X/Y derivative
// [kxnynz_kynz + 2]
{
const Type stencilDPx2 =
c8_1 * (- inPX[(kx+0) * nynz + kynz + 2] + inPX[(kx+1) * nynz + kynz + 2]) +
c8_2 * (- inPX[(kx-1) * nynz + kynz + 2] + inPX[(kx+2) * nynz + kynz + 2]) +
c8_3 * (- inPX[(kx-2) * nynz + kynz + 2] + inPX[(kx+3) * nynz + kynz + 2]) +
c8_4 * (- inPX[(kx-3) * nynz + kynz + 2] + inPX[(kx+4) * nynz + kynz + 2]);
const Type stencilDPy2 =
c8_1 * (- inPY[kxnynz + (ky+0) * nz + 2] + inPY[kxnynz + (ky+1) * nz + 2]) +
c8_2 * (- inPY[kxnynz + (ky-1) * nz + 2] + inPY[kxnynz + (ky+2) * nz + 2]) +
c8_3 * (- inPY[kxnynz + (ky-2) * nz + 2] + inPY[kxnynz + (ky+3) * nz + 2]) +
c8_4 * (- inPY[kxnynz + (ky-3) * nz + 2] + inPY[kxnynz + (ky+4) * nz + 2]);
const Type stencilDPz2 =
c8_1 * (- inPZ[kxnynz_kynz + 2] + inPZ[kxnynz_kynz + 3]) +
c8_2 * (- inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 4]) +
c8_3 * (- inPZ[kxnynz_kynz + 0] + inPZ[kxnynz_kynz + 5]) +
c8_4 * (+ inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 6]);
const Type dPX = invDx * stencilDPx2;
const Type dPY = invDy * stencilDPy2;
const Type dPZ = invDz * stencilDPz2;
const Type stencilDMx2 =
c8_1 * (- inMX[(kx+0) * nynz + kynz + 2] + inMX[(kx+1) * nynz + kynz + 2]) +
c8_2 * (- inMX[(kx-1) * nynz + kynz + 2] + inMX[(kx+2) * nynz + kynz + 2]) +
c8_3 * (- inMX[(kx-2) * nynz + kynz + 2] + inMX[(kx+3) * nynz + kynz + 2]) +
c8_4 * (- inMX[(kx-3) * nynz + kynz + 2] + inMX[(kx+4) * nynz + kynz + 2]);
const Type stencilDMy2 =
c8_1 * (- inMY[kxnynz + (ky+0) * nz + 2] + inMY[kxnynz + (ky+1) * nz + 2]) +
c8_2 * (- inMY[kxnynz + (ky-1) * nz + 2] + inMY[kxnynz + (ky+2) * nz + 2]) +
c8_3 * (- inMY[kxnynz + (ky-2) * nz + 2] + inMY[kxnynz + (ky+3) * nz + 2]) +
c8_4 * (- inMY[kxnynz + (ky-3) * nz + 2] + inMY[kxnynz + (ky+4) * nz + 2]);
const Type stencilDMz2 =
c8_1 * (- inMZ[kxnynz_kynz + 2] + inMZ[kxnynz_kynz + 3]) +
c8_2 * (- inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 4]) +
c8_3 * (- inMZ[kxnynz_kynz + 0] + inMZ[kxnynz_kynz + 5]) +
c8_4 * (+ inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 6]);
const Type dMX = invDx * stencilDMx2;
const Type dMY = invDy * stencilDMy2;
const Type dMZ = invDz * stencilDMz2;
const long k = kxnynz_kynz + 2;
const Type E = 1 + 2 * fieldEps[k];
const Type A = fieldEta[k];
const Type F = fieldVsVp[k];
const Type B = fieldBuoy[k];
const Type SA2 = sqrt(1 - A * A);
tmpPX[k] = B * E * dPX;
tmpPY[k] = B * E * dPY;
tmpPZ[k] = B * (1 - F * A * A) * dPZ + B * (F * A * SA2) * dMZ;
tmpMX[k] = B * (1 - F) * dMX;
tmpMY[k] = B * (1 - F) * dMY;
tmpMZ[k] = B * F * A * SA2 * dPZ + B * (1 - F + F * A * A) * dMZ;
}
// kz = 3 -- 3 1/2 cells below free surface for Z derivative, 3 cells below for X/Y derivative
// [kxnynz_kynz + 3]
{
const Type stencilDPx3 =
c8_1 * (- inPX[(kx+0) * nynz + kynz + 3] + inPX[(kx+1) * nynz + kynz + 3]) +
c8_2 * (- inPX[(kx-1) * nynz + kynz + 3] + inPX[(kx+2) * nynz + kynz + 3]) +
c8_3 * (- inPX[(kx-2) * nynz + kynz + 3] + inPX[(kx+3) * nynz + kynz + 3]) +
c8_4 * (- inPX[(kx-3) * nynz + kynz + 3] + inPX[(kx+4) * nynz + kynz + 3]);
const Type stencilDPy3 =
c8_1 * (- inPY[kxnynz + (ky+0) * nz + 3] + inPY[kxnynz + (ky+1) * nz + 3]) +
c8_2 * (- inPY[kxnynz + (ky-1) * nz + 3] + inPY[kxnynz + (ky+2) * nz + 3]) +
c8_3 * (- inPY[kxnynz + (ky-2) * nz + 3] + inPY[kxnynz + (ky+3) * nz + 3]) +
c8_4 * (- inPY[kxnynz + (ky-3) * nz + 3] + inPY[kxnynz + (ky+4) * nz + 3]);
const Type stencilDPz3 =
c8_1 * (- inPZ[kxnynz_kynz + 3] + inPZ[kxnynz_kynz + 4]) +
c8_2 * (- inPZ[kxnynz_kynz + 2] + inPZ[kxnynz_kynz + 5]) +
c8_3 * (- inPZ[kxnynz_kynz + 1] + inPZ[kxnynz_kynz + 6]) +
c8_4 * (- inPZ[kxnynz_kynz + 0] + inPZ[kxnynz_kynz + 7]);
const Type dPX = invDx * stencilDPx3;
const Type dPY = invDy * stencilDPy3;
const Type dPZ = invDz * stencilDPz3;
const Type stencilDMx3 =
c8_1 * (- inMX[(kx+0) * nynz + kynz + 3] + inMX[(kx+1) * nynz + kynz + 3]) +
c8_2 * (- inMX[(kx-1) * nynz + kynz + 3] + inMX[(kx+2) * nynz + kynz + 3]) +
c8_3 * (- inMX[(kx-2) * nynz + kynz + 3] + inMX[(kx+3) * nynz + kynz + 3]) +
c8_4 * (- inMX[(kx-3) * nynz + kynz + 3] + inMX[(kx+4) * nynz + kynz + 3]);
const Type stencilDMy3 =
c8_1 * (- inMY[kxnynz + (ky+0) * nz + 3] + inMY[kxnynz + (ky+1) * nz + 3]) +
c8_2 * (- inMY[kxnynz + (ky-1) * nz + 3] + inMY[kxnynz + (ky+2) * nz + 3]) +
c8_3 * (- inMY[kxnynz + (ky-2) * nz + 3] + inMY[kxnynz + (ky+3) * nz + 3]) +
c8_4 * (- inMY[kxnynz + (ky-3) * nz + 3] + inMY[kxnynz + (ky+4) * nz + 3]);
const Type stencilDMz3 =
c8_1 * (- inMZ[kxnynz_kynz + 3] + inMZ[kxnynz_kynz + 4]) +
c8_2 * (- inMZ[kxnynz_kynz + 2] + inMZ[kxnynz_kynz + 5]) +
c8_3 * (- inMZ[kxnynz_kynz + 1] + inMZ[kxnynz_kynz + 6]) +
c8_4 * (- inMZ[kxnynz_kynz + 0] + inMZ[kxnynz_kynz + 7]);
const Type dMX = invDx * stencilDMx3;
const Type dMY = invDy * stencilDMy3;
const Type dMZ = invDz * stencilDMz3;
const long k = kxnynz_kynz + 3;
const Type E = 1 + 2 * fieldEps[k];
const Type A = fieldEta[k];
const Type F = fieldVsVp[k];
const Type B = fieldBuoy[k];
const Type SA2 = sqrt(1 - A * A);
tmpPX[k] = B * E * dPX;
tmpPY[k] = B * E * dPY;
tmpPZ[k] = B * (1 - F * A * A) * dPZ + B * (F * A * SA2) * dMZ;
tmpMX[k] = B * (1 - F) * dMX;
tmpMY[k] = B * (1 - F) * dMY;
tmpMZ[k] = B * F * A * SA2 * dPZ + B * (1 - F + F * A * A) * dMZ;
}
}
}
}
}
/**
* Combines
* applyFirstDerivatives_MinusHalf(P)
* secondOrderTimeUpdate_BubeConservation(P)
* applyFirstDerivatives_MinusHalf(M)
* secondOrderTimeUpdate_BubeConservation(M)
*
* Updates pOld and mOld with second order time update
* see notes in method secondOrderTimeUpdate_BubeConservation()
*
* Nonlinear method: outputs the spatial derivatives for serialization
* Linear method: does not output the spatial derivatives
*/
template<class Type>
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline static void applyFirstDerivatives3D_MinusHalf_TimeUpdate_Nonlinear(
const long freeSurface,
const long nx,
const long ny,
const long nz,
const long nthread,
const Type c8_1,
const Type c8_2,
const Type c8_3,
const Type c8_4,
const Type invDx,
const Type invDy,
const Type invDz,
const Type dtMod,
const Type * __restrict__ const tmpPX,
const Type * __restrict__ const tmpPY,
const Type * __restrict__ const tmpPZ,
const Type * __restrict__ const tmpMX,
const Type * __restrict__ const tmpMY,
const Type * __restrict__ const tmpMZ,
const Type * __restrict__ const fieldVel,
const Type * __restrict__ const fieldBuoy,
const Type * __restrict__ const dtOmegaInvQ,
const Type * __restrict__ const pCur,
const Type * __restrict__ const mCur,
Type * __restrict__ pSpace,
Type * __restrict__ mSpace,
Type * __restrict__ pOld,
Type * __restrict__ mOld,
const long BX_3D,
const long BY_3D,
const long BZ_3D) {
const long nx4 = nx - 4;
const long ny4 = ny - 4;
const long nz4 = nz - 4;
const long nynz = ny * nz;
const Type dt2 = dtMod * dtMod;
// zero output array: note only the annulus that is in the absorbing boundary needs to be zeroed
for (long k = 0; k < 4; k++) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long ky = 0; ky < ny; ky++) {
const long kindex1 = kx * ny * nz + ky * nz + k;
const long kindex2 = kx * ny * nz + ky * nz + (nz - 1 - k);
pSpace[kindex1] = pSpace[kindex2] = 0;
mSpace[kindex1] = mSpace[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 0; kx < nx; kx++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = kx * ny * nz + k * nz + kz;
const long kindex2 = kx * ny * nz + (ny - 1 - k) * nz + kz;
pSpace[kindex1] = pSpace[kindex2] = 0;
mSpace[kindex1] = mSpace[kindex2] = 0;
}
}
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long ky = 0; ky < ny; ky++) {
#pragma omp simd
for (long kz = 0; kz < nz; kz++) {
const long kindex1 = k * ny * nz + ky * nz + kz;
const long kindex2 = (nx - 1 - k) * ny * nz + ky * nz + kz;
pSpace[kindex1] = pSpace[kindex2] = 0;
mSpace[kindex1] = mSpace[kindex2] = 0;
}
}
}
// interior
#pragma omp parallel for collapse(3) num_threads(nthread) schedule(static)
for (long bx = 4; bx < nx4; bx += BX_3D) {
for (long by = 4; by < ny4; by += BY_3D) {
for (long bz = 4; bz < nz4; bz += BZ_3D) {
const long kxmax = MIN(bx + BX_3D, nx4);
const long kymax = MIN(by + BY_3D, ny4);
const long kzmax = MIN(bz + BZ_3D, nz4);
for (long kx = bx; kx < kxmax; kx++) {
const long kxnynz = kx * nynz;
for (long ky = by; ky < kymax; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kxnynz_kynz + kz;
const long kynz_kz = + kynz + kz;
const Type stencilDPx =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz_kz] + tmpPX[(kx+0) * nynz + kynz_kz]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz_kz] + tmpPX[(kx+1) * nynz + kynz_kz]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz_kz] + tmpPX[(kx+2) * nynz + kynz_kz]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz_kz] + tmpPX[(kx+3) * nynz + kynz_kz]);
const Type stencilDPy =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + kz] + tmpPY[kxnynz + (ky+0) * nz + kz]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + kz] + tmpPY[kxnynz + (ky+1) * nz + kz]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + kz] + tmpPY[kxnynz + (ky+2) * nz + kz]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + kz] + tmpPY[kxnynz + (ky+3) * nz + kz]);
const Type stencilDPz =
c8_1 * (- tmpPZ[kxnynz_kynz + (kz-1)] + tmpPZ[kxnynz_kynz + (kz+0)]) +
c8_2 * (- tmpPZ[kxnynz_kynz + (kz-2)] + tmpPZ[kxnynz_kynz + (kz+1)]) +
c8_3 * (- tmpPZ[kxnynz_kynz + (kz-3)] + tmpPZ[kxnynz_kynz + (kz+2)]) +
c8_4 * (- tmpPZ[kxnynz_kynz + (kz-4)] + tmpPZ[kxnynz_kynz + (kz+3)]);
const Type stencilDMx =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz_kz] + tmpMX[(kx+0) * nynz + kynz_kz]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz_kz] + tmpMX[(kx+1) * nynz + kynz_kz]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz_kz] + tmpMX[(kx+2) * nynz + kynz_kz]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz_kz] + tmpMX[(kx+3) * nynz + kynz_kz]);
const Type stencilDMy =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + kz] + tmpMY[kxnynz + (ky+0) * nz + kz]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + kz] + tmpMY[kxnynz + (ky+1) * nz + kz]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + kz] + tmpMY[kxnynz + (ky+2) * nz + kz]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + kz] + tmpMY[kxnynz + (ky+3) * nz + kz]);
const Type stencilDMz =
c8_1 * (- tmpMZ[kxnynz_kynz + (kz-1)] + tmpMZ[kxnynz_kynz + (kz+0)]) +
c8_2 * (- tmpMZ[kxnynz_kynz + (kz-2)] + tmpMZ[kxnynz_kynz + (kz+1)]) +
c8_3 * (- tmpMZ[kxnynz_kynz + (kz-3)] + tmpMZ[kxnynz_kynz + (kz+2)]) +
c8_4 * (- tmpMZ[kxnynz_kynz + (kz-4)] + tmpMZ[kxnynz_kynz + (kz+3)]);
const Type dPx = invDx * stencilDPx;
const Type dPy = invDy * stencilDPy;
const Type dPz = invDz * stencilDPz;
const Type dMx = invDx * stencilDMx;
const Type dMy = invDy * stencilDMy;
const Type dMz = invDz * stencilDMz;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pSpace[k] = dPx + dPy + dPz;
mSpace[k] = dMx + dMy + dMz;
pOld[k] = dt2V2_B * pSpace[k] - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * mSpace[k] - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
}
}
}
}
}
// roll on free surface
if (freeSurface) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 4; kx < nx4; kx++) {
const long kxnynz = kx * nynz;
#pragma omp simd
for (long ky = 4; ky < ny4; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
// kz = 0 -- at the free surface -- p = 0
// [kxnynz_kynz + 0]
{
const Type dPx = 0;
const Type dPy = 0;
const Type dPz = 0;
const Type dMx = 0;
const Type dMy = 0;
const Type dMz = 0;
const long k = kxnynz_kynz + 0;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
pSpace[k] = dPx + dPy + dPz;
mSpace[k] = dMx + dMy + dMz;
}
// kz = 1 -- one cell below the free surface
// [kxnynz_kynz + 1]
{
const Type stencilDPx1 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 1] + tmpPX[(kx+0) * nynz + kynz + 1]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 1] + tmpPX[(kx+1) * nynz + kynz + 1]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 1] + tmpPX[(kx+2) * nynz + kynz + 1]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 1] + tmpPX[(kx+3) * nynz + kynz + 1]);
const Type stencilDPy1 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 1] + tmpPY[kxnynz + (ky+0) * nz + 1]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 1] + tmpPY[kxnynz + (ky+1) * nz + 1]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 1] + tmpPY[kxnynz + (ky+2) * nz + 1]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 1] + tmpPY[kxnynz + (ky+3) * nz + 1]);
const Type stencilDPz1 =
c8_1 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 1]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 2]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 3]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 2] + tmpPZ[kxnynz_kynz + 4]);
const Type stencilDMx1 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 1] + tmpMX[(kx+0) * nynz + kynz + 1]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 1] + tmpMX[(kx+1) * nynz + kynz + 1]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 1] + tmpMX[(kx+2) * nynz + kynz + 1]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 1] + tmpMX[(kx+3) * nynz + kynz + 1]);
const Type stencilDMy1 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 1] + tmpMY[kxnynz + (ky+0) * nz + 1]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 1] + tmpMY[kxnynz + (ky+1) * nz + 1]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 1] + tmpMY[kxnynz + (ky+2) * nz + 1]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 1] + tmpMY[kxnynz + (ky+3) * nz + 1]);
const Type stencilDMz1 =
c8_1 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 1]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 2]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 3]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 2] + tmpMZ[kxnynz_kynz + 4]);
const Type dPx = invDx * stencilDPx1;
const Type dPy = invDy * stencilDPy1;
const Type dPz = invDz * stencilDPz1;
const Type dMx = invDx * stencilDMx1;
const Type dMy = invDy * stencilDMy1;
const Type dMz = invDz * stencilDMz1;
const long k = kxnynz_kynz + 1;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pSpace[k] = dPx + dPy + dPz;
mSpace[k] = dMx + dMy + dMz;
pOld[k] = dt2V2_B * pSpace[k] - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * mSpace[k] - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
// kz = 2 -- two cells below the free surface
// [kxnynz_kynz + 2]
{
const Type stencilDPx2 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 2] + tmpPX[(kx+0) * nynz + kynz + 2]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 2] + tmpPX[(kx+1) * nynz + kynz + 2]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 2] + tmpPX[(kx+2) * nynz + kynz + 2]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 2] + tmpPX[(kx+3) * nynz + kynz + 2]);
const Type stencilDPy2 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 2] + tmpPY[kxnynz + (ky+0) * nz + 2]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 2] + tmpPY[kxnynz + (ky+1) * nz + 2]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 2] + tmpPY[kxnynz + (ky+2) * nz + 2]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 2] + tmpPY[kxnynz + (ky+3) * nz + 2]);
const Type stencilDPz2 =
c8_1 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 2]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 3]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 4]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 5]);
const Type stencilDMx2 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 2] + tmpMX[(kx+0) * nynz + kynz + 2]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 2] + tmpMX[(kx+1) * nynz + kynz + 2]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 2] + tmpMX[(kx+2) * nynz + kynz + 2]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 2] + tmpMX[(kx+3) * nynz + kynz + 2]);
const Type stencilDMy2 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 2] + tmpMY[kxnynz + (ky+0) * nz + 2]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 2] + tmpMY[kxnynz + (ky+1) * nz + 2]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 2] + tmpMY[kxnynz + (ky+2) * nz + 2]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 2] + tmpMY[kxnynz + (ky+3) * nz + 2]);
const Type stencilDMz2 =
c8_1 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 2]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 3]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 4]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 5]);
const Type dPx = invDx * stencilDPx2;
const Type dPy = invDy * stencilDPy2;
const Type dPz = invDz * stencilDPz2;
const Type dMx = invDx * stencilDMx2;
const Type dMy = invDy * stencilDMy2;
const Type dMz = invDz * stencilDMz2;
const long k = kxnynz_kynz + 2;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pSpace[k] = dPx + dPy + dPz;
mSpace[k] = dMx + dMy + dMz;
pOld[k] = dt2V2_B * pSpace[k] - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * mSpace[k] - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
// kz = 3 -- three cells below the free surface
// [kxnynz_kynz + 3]
{
const Type stencilDPx3 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 3] + tmpPX[(kx+0) * nynz + kynz + 3]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 3] + tmpPX[(kx+1) * nynz + kynz + 3]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 3] + tmpPX[(kx+2) * nynz + kynz + 3]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 3] + tmpPX[(kx+3) * nynz + kynz + 3]);
const Type stencilDPy3 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 3] + tmpPY[kxnynz + (ky+0) * nz + 3]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 3] + tmpPY[kxnynz + (ky+1) * nz + 3]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 3] + tmpPY[kxnynz + (ky+2) * nz + 3]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 3] + tmpPY[kxnynz + (ky+3) * nz + 3]);
const Type stencilDPz3 =
c8_1 * (- tmpPZ[kxnynz_kynz + 2] + tmpPZ[kxnynz_kynz + 3]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 4]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 5]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 6]);
const Type stencilDMx3 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 3] + tmpMX[(kx+0) * nynz + kynz + 3]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 3] + tmpMX[(kx+1) * nynz + kynz + 3]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 3] + tmpMX[(kx+2) * nynz + kynz + 3]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 3] + tmpMX[(kx+3) * nynz + kynz + 3]);
const Type stencilDMy3 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 3] + tmpMY[kxnynz + (ky+0) * nz + 3]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 3] + tmpMY[kxnynz + (ky+1) * nz + 3]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 3] + tmpMY[kxnynz + (ky+2) * nz + 3]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 3] + tmpMY[kxnynz + (ky+3) * nz + 3]);
const Type stencilDMz3 =
c8_1 * (- tmpMZ[kxnynz_kynz + 2] + tmpMZ[kxnynz_kynz + 3]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 4]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 5]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 6]);
const Type dPx = invDx * stencilDPx3;
const Type dPy = invDy * stencilDPy3;
const Type dPz = invDz * stencilDPz3;
const Type dMx = invDx * stencilDMx3;
const Type dMy = invDy * stencilDMy3;
const Type dMz = invDz * stencilDMz3;
const long k = kxnynz_kynz + 3;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pSpace[k] = dPx + dPy + dPz;
mSpace[k] = dMx + dMy + dMz;
pOld[k] = dt2V2_B * pSpace[k] - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * mSpace[k] - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
}
}
}
}
template<class Type>
#if defined(__FUNCTION_CLONES__)
__attribute__((target_clones("avx","avx2","avx512f","default")))
#endif
inline static void applyFirstDerivatives3D_MinusHalf_TimeUpdate_Linear(
const long freeSurface,
const long nx,
const long ny,
const long nz,
const long nthread,
const Type c8_1,
const Type c8_2,
const Type c8_3,
const Type c8_4,
const Type invDx,
const Type invDy,
const Type invDz,
const Type dtMod,
const Type * __restrict__ const tmpPX,
const Type * __restrict__ const tmpPY,
const Type * __restrict__ const tmpPZ,
const Type * __restrict__ const tmpMX,
const Type * __restrict__ const tmpMY,
const Type * __restrict__ const tmpMZ,
const Type * __restrict__ const fieldVel,
const Type * __restrict__ const fieldBuoy,
const Type * __restrict__ const dtOmegaInvQ,
const Type * __restrict__ const pCur,
const Type * __restrict__ const mCur,
Type * __restrict__ pOld,
Type * __restrict__ mOld,
const long BX_3D,
const long BY_3D,
const long BZ_3D) {
const long nx4 = nx - 4;
const long ny4 = ny - 4;
const long nz4 = nz - 4;
const long nynz = ny * nz;
const Type dt2 = dtMod * dtMod;
// interior
#pragma omp parallel for collapse(3) num_threads(nthread) schedule(static)
for (long bx = 4; bx < nx4; bx += BX_3D) {
for (long by = 4; by < ny4; by += BY_3D) {
for (long bz = 4; bz < nz4; bz += BZ_3D) {
const long kxmax = MIN(bx + BX_3D, nx4);
const long kymax = MIN(by + BY_3D, ny4);
const long kzmax = MIN(bz + BZ_3D, nz4);
for (long kx = bx; kx < kxmax; kx++) {
const long kxnynz = kx * nynz;
for (long ky = by; ky < kymax; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
#pragma omp simd
for (long kz = bz; kz < kzmax; kz++) {
const long k = kxnynz_kynz + kz;
const long kynz_kz = + kynz + kz;
const Type stencilDPx =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz_kz] + tmpPX[(kx+0) * nynz + kynz_kz]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz_kz] + tmpPX[(kx+1) * nynz + kynz_kz]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz_kz] + tmpPX[(kx+2) * nynz + kynz_kz]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz_kz] + tmpPX[(kx+3) * nynz + kynz_kz]);
const Type stencilDPy =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + kz] + tmpPY[kxnynz + (ky+0) * nz + kz]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + kz] + tmpPY[kxnynz + (ky+1) * nz + kz]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + kz] + tmpPY[kxnynz + (ky+2) * nz + kz]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + kz] + tmpPY[kxnynz + (ky+3) * nz + kz]);
const Type stencilDPz =
c8_1 * (- tmpPZ[kxnynz_kynz + (kz-1)] + tmpPZ[kxnynz_kynz + (kz+0)]) +
c8_2 * (- tmpPZ[kxnynz_kynz + (kz-2)] + tmpPZ[kxnynz_kynz + (kz+1)]) +
c8_3 * (- tmpPZ[kxnynz_kynz + (kz-3)] + tmpPZ[kxnynz_kynz + (kz+2)]) +
c8_4 * (- tmpPZ[kxnynz_kynz + (kz-4)] + tmpPZ[kxnynz_kynz + (kz+3)]);
const Type stencilDMx =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz_kz] + tmpMX[(kx+0) * nynz + kynz_kz]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz_kz] + tmpMX[(kx+1) * nynz + kynz_kz]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz_kz] + tmpMX[(kx+2) * nynz + kynz_kz]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz_kz] + tmpMX[(kx+3) * nynz + kynz_kz]);
const Type stencilDMy =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + kz] + tmpMY[kxnynz + (ky+0) * nz + kz]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + kz] + tmpMY[kxnynz + (ky+1) * nz + kz]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + kz] + tmpMY[kxnynz + (ky+2) * nz + kz]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + kz] + tmpMY[kxnynz + (ky+3) * nz + kz]);
const Type stencilDMz =
c8_1 * (- tmpMZ[kxnynz_kynz + (kz-1)] + tmpMZ[kxnynz_kynz + (kz+0)]) +
c8_2 * (- tmpMZ[kxnynz_kynz + (kz-2)] + tmpMZ[kxnynz_kynz + (kz+1)]) +
c8_3 * (- tmpMZ[kxnynz_kynz + (kz-3)] + tmpMZ[kxnynz_kynz + (kz+2)]) +
c8_4 * (- tmpMZ[kxnynz_kynz + (kz-4)] + tmpMZ[kxnynz_kynz + (kz+3)]);
const Type dPx = invDx * stencilDPx;
const Type dPy = invDy * stencilDPy;
const Type dPz = invDz * stencilDPz;
const Type dMx = invDx * stencilDMx;
const Type dMy = invDy * stencilDMy;
const Type dMz = invDz * stencilDMz;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
}
}
}
}
}
// roll on free surface
if (freeSurface) {
#pragma omp parallel for num_threads(nthread) schedule(static)
for (long kx = 4; kx < nx4; kx++) {
const long kxnynz = kx * nynz;
#pragma omp simd
for (long ky = 4; ky < ny4; ky++) {
const long kynz = ky * nz;
const long kxnynz_kynz = kxnynz + kynz;
// kz = 0 -- at the free surface -- p = 0
// [kxnynz_kynz + 0]
{
const Type dPx = 0;
const Type dPy = 0;
const Type dPz = 0;
const Type dMx = 0;
const Type dMy = 0;
const Type dMz = 0;
const long k = kxnynz_kynz + 0;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
// kz = 1 -- one cell below the free surface
// [kxnynz_kynz + 1]
{
const Type stencilDPx1 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 1] + tmpPX[(kx+0) * nynz + kynz + 1]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 1] + tmpPX[(kx+1) * nynz + kynz + 1]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 1] + tmpPX[(kx+2) * nynz + kynz + 1]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 1] + tmpPX[(kx+3) * nynz + kynz + 1]);
const Type stencilDPy1 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 1] + tmpPY[kxnynz + (ky+0) * nz + 1]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 1] + tmpPY[kxnynz + (ky+1) * nz + 1]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 1] + tmpPY[kxnynz + (ky+2) * nz + 1]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 1] + tmpPY[kxnynz + (ky+3) * nz + 1]);
const Type stencilDPz1 =
c8_1 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 1]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 2]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 3]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 2] + tmpPZ[kxnynz_kynz + 4]);
const Type stencilDMx1 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 1] + tmpMX[(kx+0) * nynz + kynz + 1]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 1] + tmpMX[(kx+1) * nynz + kynz + 1]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 1] + tmpMX[(kx+2) * nynz + kynz + 1]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 1] + tmpMX[(kx+3) * nynz + kynz + 1]);
const Type stencilDMy1 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 1] + tmpMY[kxnynz + (ky+0) * nz + 1]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 1] + tmpMY[kxnynz + (ky+1) * nz + 1]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 1] + tmpMY[kxnynz + (ky+2) * nz + 1]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 1] + tmpMY[kxnynz + (ky+3) * nz + 1]);
const Type stencilDMz1 =
c8_1 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 1]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 2]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 3]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 2] + tmpMZ[kxnynz_kynz + 4]);
const Type dPx = invDx * stencilDPx1;
const Type dPy = invDy * stencilDPy1;
const Type dPz = invDz * stencilDPz1;
const Type dMx = invDx * stencilDMx1;
const Type dMy = invDy * stencilDMy1;
const Type dMz = invDz * stencilDMz1;
const long k = kxnynz_kynz + 1;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
// kz = 2 -- two cells below the free surface
// [kxnynz_kynz + 2]
{
const Type stencilDPx2 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 2] + tmpPX[(kx+0) * nynz + kynz + 2]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 2] + tmpPX[(kx+1) * nynz + kynz + 2]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 2] + tmpPX[(kx+2) * nynz + kynz + 2]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 2] + tmpPX[(kx+3) * nynz + kynz + 2]);
const Type stencilDPy2 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 2] + tmpPY[kxnynz + (ky+0) * nz + 2]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 2] + tmpPY[kxnynz + (ky+1) * nz + 2]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 2] + tmpPY[kxnynz + (ky+2) * nz + 2]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 2] + tmpPY[kxnynz + (ky+3) * nz + 2]);
const Type stencilDPz2 =
c8_1 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 2]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 3]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 4]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 5]);
const Type stencilDMx2 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 2] + tmpMX[(kx+0) * nynz + kynz + 2]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 2] + tmpMX[(kx+1) * nynz + kynz + 2]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 2] + tmpMX[(kx+2) * nynz + kynz + 2]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 2] + tmpMX[(kx+3) * nynz + kynz + 2]);
const Type stencilDMy2 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 2] + tmpMY[kxnynz + (ky+0) * nz + 2]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 2] + tmpMY[kxnynz + (ky+1) * nz + 2]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 2] + tmpMY[kxnynz + (ky+2) * nz + 2]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 2] + tmpMY[kxnynz + (ky+3) * nz + 2]);
const Type stencilDMz2 =
c8_1 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 2]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 3]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 4]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 5]);
const Type dPx = invDx * stencilDPx2;
const Type dPy = invDy * stencilDPy2;
const Type dPz = invDz * stencilDPz2;
const Type dMx = invDx * stencilDMx2;
const Type dMy = invDy * stencilDMy2;
const Type dMz = invDz * stencilDMz2;
const long k = kxnynz_kynz + 2;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
// kz = 3 -- three cells below the free surface
// [kxnynz_kynz + 3]
{
const Type stencilDPx3 =
c8_1 * (- tmpPX[(kx-1) * nynz + kynz + 3] + tmpPX[(kx+0) * nynz + kynz + 3]) +
c8_2 * (- tmpPX[(kx-2) * nynz + kynz + 3] + tmpPX[(kx+1) * nynz + kynz + 3]) +
c8_3 * (- tmpPX[(kx-3) * nynz + kynz + 3] + tmpPX[(kx+2) * nynz + kynz + 3]) +
c8_4 * (- tmpPX[(kx-4) * nynz + kynz + 3] + tmpPX[(kx+3) * nynz + kynz + 3]);
const Type stencilDPy3 =
c8_1 * (- tmpPY[kxnynz + (ky-1) * nz + 3] + tmpPY[kxnynz + (ky+0) * nz + 3]) +
c8_2 * (- tmpPY[kxnynz + (ky-2) * nz + 3] + tmpPY[kxnynz + (ky+1) * nz + 3]) +
c8_3 * (- tmpPY[kxnynz + (ky-3) * nz + 3] + tmpPY[kxnynz + (ky+2) * nz + 3]) +
c8_4 * (- tmpPY[kxnynz + (ky-4) * nz + 3] + tmpPY[kxnynz + (ky+3) * nz + 3]);
const Type stencilDPz3 =
c8_1 * (- tmpPZ[kxnynz_kynz + 2] + tmpPZ[kxnynz_kynz + 3]) +
c8_2 * (- tmpPZ[kxnynz_kynz + 1] + tmpPZ[kxnynz_kynz + 4]) +
c8_3 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 5]) +
c8_4 * (- tmpPZ[kxnynz_kynz + 0] + tmpPZ[kxnynz_kynz + 6]);
const Type stencilDMx3 =
c8_1 * (- tmpMX[(kx-1) * nynz + kynz + 3] + tmpMX[(kx+0) * nynz + kynz + 3]) +
c8_2 * (- tmpMX[(kx-2) * nynz + kynz + 3] + tmpMX[(kx+1) * nynz + kynz + 3]) +
c8_3 * (- tmpMX[(kx-3) * nynz + kynz + 3] + tmpMX[(kx+2) * nynz + kynz + 3]) +
c8_4 * (- tmpMX[(kx-4) * nynz + kynz + 3] + tmpMX[(kx+3) * nynz + kynz + 3]);
const Type stencilDMy3 =
c8_1 * (- tmpMY[kxnynz + (ky-1) * nz + 3] + tmpMY[kxnynz + (ky+0) * nz + 3]) +
c8_2 * (- tmpMY[kxnynz + (ky-2) * nz + 3] + tmpMY[kxnynz + (ky+1) * nz + 3]) +
c8_3 * (- tmpMY[kxnynz + (ky-3) * nz + 3] + tmpMY[kxnynz + (ky+2) * nz + 3]) +
c8_4 * (- tmpMY[kxnynz + (ky-4) * nz + 3] + tmpMY[kxnynz + (ky+3) * nz + 3]);
const Type stencilDMz3 =
c8_1 * (- tmpMZ[kxnynz_kynz + 2] + tmpMZ[kxnynz_kynz + 3]) +
c8_2 * (- tmpMZ[kxnynz_kynz + 1] + tmpMZ[kxnynz_kynz + 4]) +
c8_3 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 5]) +
c8_4 * (- tmpMZ[kxnynz_kynz + 0] + tmpMZ[kxnynz_kynz + 6]);
const Type dPx = invDx * stencilDPx3;
const Type dPy = invDy * stencilDPy3;
const Type dPz = invDz * stencilDPz3;
const Type dMx = invDx * stencilDMx3;
const Type dMy = invDy * stencilDMy3;
const Type dMz = invDz * stencilDMz3;
const long k = kxnynz_kynz + 3;
const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k];
pOld[k] = dt2V2_B * (dPx + dPy + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k];
mOld[k] = dt2V2_B * (dMx + dMy + dMz) - dtOmegaInvQ[k] * (mCur[k] - mOld[k]) - mOld[k] + 2 * mCur[k];
}
}
}
}
}
};
#endif
|
GB_binop__pair_fc64.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_emult.h"
#include "GB_control.h"
#include "GB_ek_slice.h"
#include "GB_dense.h"
#include "GB_atomics.h"
#include "GB_bitmap_assign_methods.h"
#include "GB_binop__include.h"
// C=binop(A,B) is defined by the following types and operators:
// A+B function (eWiseAdd): GB (_AaddB__pair_fc64)
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A.*B function (eWiseMult): GB ((none))
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__pair_fc64)
// C+=b function (dense accum): GB (_Cdense_accumb__pair_fc64)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_fc64)
// C=scalar+B GB ((none))
// C=scalar+B' GB ((none))
// C=A+scalar GB ((none))
// C=A'+scalar GB ((none))
// C type: GxB_FC64_t
// A type: GxB_FC64_t
// A pattern? 1
// B type: GxB_FC64_t
// B pattern? 1
// BinaryOp: cij = GxB_CMPLX(1,0)
#define GB_ATYPE \
GxB_FC64_t
#define GB_BTYPE \
GxB_FC64_t
#define GB_CTYPE \
GxB_FC64_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
;
// true if values of A are not used
#define GB_A_IS_PATTERN \
1 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
;
// true if values of B are not used
#define GB_B_IS_PATTERN \
1 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
GxB_FC64_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GxB_CMPLX(1,0) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
0
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_PAIR || GxB_NO_FC64 || GxB_NO_PAIR_FC64)
//------------------------------------------------------------------------------
// 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__pair_fc64)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__pair_fc64)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__pair_fc64)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type GxB_FC64_t
GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *restrict Cx = (GxB_FC64_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *restrict Cx = (GxB_FC64_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__pair_fc64)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
GxB_FC64_t alpha_scalar ;
GxB_FC64_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((GxB_FC64_t *) alpha_scalar_in)) ;
beta_scalar = (*((GxB_FC64_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
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
}
#endif
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ;
GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
; ;
Cx [p] = GxB_CMPLX(1,0) ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ;
GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ;
GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
; ;
Cx [p] = GxB_CMPLX(1,0) ;
}
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = GxB_CMPLX(1,0) ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC64_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
GxB_FC64_t
}
#endif
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
#if 0
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
; ; \
Cx [pC] = GxB_CMPLX(1,0) ; \
}
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
#endif
|
OpenMPIHAEA.h | //
// Created by jefferson on 14/11/16.
//
#ifndef DC_GA_OPENMPIHAEA_H
#define DC_GA_OPENMPIHAEA_H
#include "AbstractHAEA.h"
#include <cmath>
#include <iostream>
#include <boost/serialization/vector.hpp>
#include <boost/mpi.hpp>
#include <cstdlib>
namespace mpi = boost::mpi;
template <class T>
class OpenMPIHAEA : public AbstractHAEA<T> {
public:
OpenMPIHAEA(Selection<T> &selection, std::vector< std::shared_ptr<Operator<T> > > operators, size_t populationSize, size_t maxIters);
std::vector<T> solve(Space<T> *space, OptimizationFunction<T> *goal);
void setThreads(size_t threads);
void setArgc(int argc);
void setArgv(char **argv);
private:
size_t threads;
int argc;
char **argv;
};
template <class T>
OpenMPIHAEA<T>::OpenMPIHAEA(Selection<T> &selection, std::vector<std::shared_ptr<Operator<T> > > operators,
size_t populationSize, size_t maxIters) : AbstractHAEA<T>(selection, operators, populationSize,
maxIters) {
}
template <class T>
std::vector<T> OpenMPIHAEA<T>::solve(Space<T> *space, OptimizationFunction<T> *goal) {
this->space = space;
this->optimizationFunction = goal;
size_t tasks, iam, from, to, processSize, popSize = this->populationSize;
this->initPopulation();
mpi::environment env(this->argc, this->argv);
mpi::communicator world;
tasks = static_cast<size_t>(world.size());
iam = static_cast<size_t>(world.rank());
processSize = popSize / tasks;
from = iam * processSize;
to = iam + 1 == tasks ? popSize : from + processSize;
for(size_t i = 0; i < this->maxIters; ++i) {
//printf("%li %li\n", from, to);
#pragma omp parallel for num_threads(this->threads)
for(size_t j = from; j < to; ++j) {
T parent = this->population[j];
double delta = this->ur.generate();
std::vector<double> rates = this->operatorRates[j];
size_t operatorIndex = this->operatorSelect(rates);
std::shared_ptr< Operator<T> > op = this->operators[operatorIndex];
int arguments = op->getArguments();
double parentFitness = this->optimizationFunction->apply(parent);
std::vector<T> selectedIndividuals;
selectedIndividuals.push_back(parent);
for(int k = 1; k < arguments; ++k) {
// TODO: selection of the other individuals
// TODO: for now we select it randomly
size_t index = 0;
index = static_cast<size_t>(this->selection->chooseOne(this->population));
//printf("index : %i\n", static_cast<int>(index));
selectedIndividuals.push_back(this->population[index]);
}
std::vector<T> offspring = op->apply(selectedIndividuals);
// repair offspring
for(size_t k = 0; k < offspring.size(); ++k) {
offspring[k] = this->space->repair(offspring[k]);
}
double childFitness = std::numeric_limits<double>::max();
T child;
if(offspring.size() > 1) {
for(auto ind = offspring.begin(); ind != offspring.end(); ++ind){
double currentFitness = this->optimizationFunction->apply(*ind);
if(currentFitness < childFitness) {
childFitness = currentFitness;
child = *ind;
}
}
} else {
child = offspring[0];
childFitness = this->optimizationFunction->apply(child);
}
if(childFitness < parentFitness) {
rates[operatorIndex] *= (1.0 + delta);
} else {
rates[operatorIndex] *= (1.0 - delta);
}
this->ratesNormalize(rates);
this->new_population[j] = child;
}
//std::cout << "I am: " << iam << std::endl;
if(iam == 0) {
for(size_t j = to; j < this->populationSize; ++j) {
//std::cout << "receiving: " << j << std::endl;
world.recv(mpi::any_source, static_cast<int>(j), this->new_population[j]);
}
} else {
for(size_t j = from; j < to; ++j) {
//std::cout << "sending: " << j << std::endl;
world.send(0, static_cast<int>(j), this->new_population[j]);
}
}
world.barrier();
this->population = this->new_population;
broadcast(world, this->population, 0);
//printf("unlock \n");
}
MPI_Finalize();
if(iam != 0) {
exit(EXIT_SUCCESS);
}
return this->population;
}
template <class T>
void OpenMPIHAEA<T>::setThreads(size_t threads) {
this->threads = threads;
}
template <class T>
void OpenMPIHAEA<T>::setArgc(int argc) {
this->argc = argc;
}
template <class T>
void OpenMPIHAEA<T>::setArgv(char **argv) {
this->argv = argv;
}
#endif //DC_GA_OPENMPIHAEA_H
|
CBasedTraversal.h | /**
* @file CBasedTraversal.h
* @author C. Menges
* @date 26.04.2019
*/
#pragma once
#include "autopas/containers/cellPairTraversals/CellPairTraversal.h"
#include "autopas/utils/ArrayMath.h"
#include "autopas/utils/DataLayoutConverter.h"
#include "autopas/utils/ThreeDimensionalMapping.h"
namespace autopas {
/**
* This class provides the base for traversals using base steps based on cell coloring.
*
* @tparam ParticleCell the type of cells
* @tparam PairwiseFunctor The functor that defines the interaction of two particles.
* @tparam dataLayout
* @tparam useNewton3
* @tparam collapseDepth Set the depth of loop collapsion for OpenMP. Loop variables from outer to inner loop: z,y,x
*/
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption dataLayout, bool useNewton3,
int collapseDepth = 3>
class CBasedTraversal : public CellPairTraversal<ParticleCell> {
protected:
/**
* Constructor of the CBasedTraversal.
* @param dims The dimensions of the cellblock, i.e. the number of cells in x,
* y and z direction.
* @param pairwiseFunctor The functor that defines the interaction of two particles.
* @param interactionLength Interaction length (cutoff + skin).
* @param cellLength cell length.
*/
explicit CBasedTraversal(const std::array<unsigned long, 3> &dims, PairwiseFunctor *pairwiseFunctor,
const double interactionLength, const std::array<double, 3> &cellLength)
: CellPairTraversal<ParticleCell>(dims),
_interactionLength(interactionLength),
_cellLength(cellLength),
_dataLayoutConverter(pairwiseFunctor) {
for (unsigned int d = 0; d < 3; d++) {
_overlap[d] = std::ceil(_interactionLength / _cellLength[d]);
}
}
/**
* Destructor of CBasedTraversal.
*/
~CBasedTraversal() override = default;
public:
/**
* load Data Layouts required for this Traversal if cells have been set through setCellsToTraverse().
*/
void initTraversal() override {
if (this->_cells) {
auto &cells = *(this->_cells);
#ifdef AUTOPAS_OPENMP
// @todo find a condition on when to use omp or when it is just overhead
#pragma omp parallel for
#endif
for (size_t i = 0; i < cells.size(); ++i) {
_dataLayoutConverter.loadDataLayout(cells[i]);
}
}
}
/**
* write Data to AoS if cells have been set through setCellsToTraverse().
*/
void endTraversal() override {
if (this->_cells) {
auto &cells = *(this->_cells);
#ifdef AUTOPAS_OPENMP
// @todo find a condition on when to use omp or when it is just overhead
#pragma omp parallel for
#endif
for (size_t i = 0; i < cells.size(); ++i) {
_dataLayoutConverter.storeDataLayout(cells[i]);
}
}
}
protected:
/**
* The main traversal of the CTraversal.
* @tparam LoopBody type of the loop body
* @param loopBody The body of the loop as a function. Normally a lambda function, that takes as as parameters
* (x,y,z). If you need additional input from outside, please use captures (by reference).
* @param end 3D index until interactions are processed (exclusive)
* @param stride dimension of stride (depends on coloring)
* @param offset initial offset
*/
template <typename LoopBody>
inline void cTraversal(LoopBody &&loopBody, const std::array<unsigned long, 3> &end,
const std::array<unsigned long, 3> &stride,
const std::array<unsigned long, 3> &offset = {0ul, 0ul, 0ul});
/**
* This method is called when the color during the traversal has changed.
*
* @param newColor The new current color.
*/
virtual void notifyColorChange(unsigned long newColor){};
/**
* Interaction length (cutoff + skin).
*/
const double _interactionLength;
/**
* cell length in CellBlock3D.
*/
const std::array<double, 3> _cellLength;
/**
* overlap of interacting cells. Array allows asymmetric cell sizes.
*/
std::array<unsigned long, 3> _overlap;
private:
/**
* Data Layout Converter to be used with this traversal
*/
utils::DataLayoutConverter<PairwiseFunctor, dataLayout> _dataLayoutConverter;
};
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption dataLayout, bool useNewton3, int collapseDepth>
template <typename LoopBody>
inline void CBasedTraversal<ParticleCell, PairwiseFunctor, dataLayout, useNewton3, collapseDepth>::cTraversal(
LoopBody &&loopBody, const std::array<unsigned long, 3> &end, const std::array<unsigned long, 3> &stride,
const std::array<unsigned long, 3> &offset) {
#if defined(AUTOPAS_OPENMP)
#pragma omp parallel
#endif
{
const unsigned long numColors = stride[0] * stride[1] * stride[2];
for (unsigned long col = 0; col < numColors; ++col) {
notifyColorChange(col);
std::array<unsigned long, 3> startWithoutOffset(utils::ThreeDimensionalMapping::oneToThreeD(col, stride));
std::array<unsigned long, 3> start(ArrayMath::add(startWithoutOffset, offset));
// intel compiler demands following:
const unsigned long start_x = start[0], start_y = start[1], start_z = start[2];
const unsigned long end_x = end[0], end_y = end[1], end_z = end[2];
const unsigned long stride_x = stride[0], stride_y = stride[1], stride_z = stride[2];
if (collapseDepth == 2) {
#if defined(AUTOPAS_OPENMP)
#pragma omp for schedule(dynamic, 1) collapse(2)
#endif
for (unsigned long z = start_z; z < end_z; z += stride_z) {
for (unsigned long y = start_y; y < end_y; y += stride_y) {
for (unsigned long x = start_x; x < end_x; x += stride_x) {
// Don't exchange order of execution (x must be last!), it would break other code
loopBody(x, y, z);
}
}
}
} else {
#if defined(AUTOPAS_OPENMP)
#pragma omp for schedule(dynamic, 1) collapse(3)
#endif
for (unsigned long z = start_z; z < end_z; z += stride_z) {
for (unsigned long y = start_y; y < end_y; y += stride_y) {
for (unsigned long x = start_x; x < end_x; x += stride_x) {
// Don't exchange order of execution (x must be last!), it would break other code
loopBody(x, y, z);
}
}
}
}
}
}
}
} // namespace autopas
|
TraversalVerlet.h | /**
* @file TraversalVerlet.h
*
* @date 7.4.2019
* @author jspahl
*/
#pragma once
#include "VerletTraversalInterface.h"
#include "autopas/containers/cellPairTraversals/CellPairTraversal.h"
#include "autopas/containers/verletListsCellBased/verletLists/VerletListHelpers.h"
#include "autopas/options/DataLayoutOption.h"
namespace autopas {
/**
* This class provides a Traversal for the verlet lists container.
*
* @tparam ParticleCell the type of cells
* @tparam PairwiseFunctor The functor that defines the interaction of two particles.
* @tparam dataLayout
* @tparam useNewton3
*/
template <class ParticleCell, class PairwiseFunctor, DataLayoutOption dataLayout, bool useNewton3>
class TraversalVerlet
: public TraversalInterface,
public VerletTraversalInterface<
typename VerletListHelpers<typename ParticleCell::ParticleType>::VerletListParticleCellType> {
using Particle = typename ParticleCell::ParticleType;
typedef
typename VerletListHelpers<typename ParticleCell::ParticleType>::VerletListParticleCellType LinkedParticleCell;
public:
/**
* Constructor for Verlet Traversal
* @param pairwiseFunctor Functor to be used with this Traversal
*/
explicit TraversalVerlet(PairwiseFunctor *pairwiseFunctor) : _functor(pairwiseFunctor) {}
TraversalOption getTraversalType() const override { return TraversalOption::verletTraversal; }
DataLayoutOption getDataLayout() const override { return dataLayout; }
bool getUseNewton3() const override { return useNewton3; }
bool isApplicable() const override {
return dataLayout == DataLayoutOption::aos || dataLayout == DataLayoutOption::soa;
}
void initTraversal() override {
auto &cells = *(this->_cells);
if (dataLayout == DataLayoutOption::soa) {
size_t offset = 0;
for (auto &cell : cells) {
_functor->SoALoader(cell, _soa, offset);
offset += cell.numParticles();
}
}
}
void endTraversal() override {
auto &cells = *(this->_cells);
if (dataLayout == DataLayoutOption::soa) {
size_t offset = 0;
for (auto &cell : cells) {
_functor->SoAExtractor(cell, _soa, offset);
offset += cell.numParticles();
}
}
}
void traverseParticlePairs() override {
auto &aosNeighborLists = *(this->_aosNeighborLists);
auto &soaNeighborLists = *(this->_soaNeighborLists);
switch (dataLayout) {
case DataLayoutOption::aos: {
#if defined(AUTOPAS_OPENMP)
if (not useNewton3) {
size_t buckets = aosNeighborLists.bucket_count();
// @todo find a sensible chunk size
#pragma omp parallel for schedule(dynamic)
for (size_t b = 0; b < buckets; b++) {
auto endIter = aosNeighborLists.end(b);
for (auto it = aosNeighborLists.begin(b); it != endIter; ++it) {
Particle &i = *(it->first);
for (auto j_ptr : it->second) {
Particle &j = *j_ptr;
_functor->AoSFunctor(i, j, false);
}
}
}
} else
#endif
{
for (auto &list : aosNeighborLists) {
Particle &i = *list.first;
for (auto j_ptr : list.second) {
Particle &j = *j_ptr;
_functor->AoSFunctor(i, j, useNewton3);
}
}
}
return;
}
case DataLayoutOption::soa: {
const size_t iFrom = 0;
const size_t iTo = soaNeighborLists.size();
#if defined(AUTOPAS_OPENMP)
if (not useNewton3) {
// @todo find a sensible chunk size
const size_t chunkSize = std::max((iTo - iFrom) / (omp_get_max_threads() * 10), 1ul);
#pragma omp parallel for schedule(dynamic, chunkSize)
for (size_t i = iFrom; i < iTo; i++) {
_functor->SoAFunctor(_soa, soaNeighborLists, i, i + 1, useNewton3);
}
} else
#endif
{
// iterate over SoA
_functor->SoAFunctor(_soa, soaNeighborLists, iFrom, iTo, useNewton3);
}
return;
}
default: { utils::ExceptionHandler::exception("VerletList dataLayout {} not available", dataLayout); }
}
}
private:
/**
* Functor for Traversal
*/
PairwiseFunctor *_functor;
/**
*global SoA of verlet lists
*/
SoA<typename Particle::SoAArraysType> _soa;
};
} // namespace autopas |
ba_sparse_matrix.h | /*
* Copyright (C) 2015, Simon Fuhrmann, Fabian Langguth
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#ifndef SFM_SPARSE_MATRIX_HEADER
#define SFM_SPARSE_MATRIX_HEADER
#include <thread>
#include <stdexcept>
#include <vector>
#include <algorithm>
#include "sfm/ba_dense_vector.h"
#include "sfm/defines.h"
SFM_NAMESPACE_BEGIN
SFM_BA_NAMESPACE_BEGIN
/**
* Sparse matrix class in Yale format for column-major matrices.
*/
template <typename T>
class SparseMatrix
{
public:
/** Triplet with row/col index, and the actual value. */
struct Triplet
{
Triplet (void) = default;
Triplet (std::size_t row, std::size_t col, T const& value);
std::size_t row;
std::size_t col;
T value;
};
/** List of triplets. */
typedef std::vector<Triplet> Triplets;
public:
SparseMatrix (void);
SparseMatrix (std::size_t rows, std::size_t cols);
void allocate (std::size_t rows, std::size_t cols);
void reserve (std::size_t num_elements);
void set_from_triplets (Triplets const& triplets);
void mult_diagonal (T const& factor);
void cwise_invert (void);
void column_nonzeros (std::size_t col, DenseVector<T>* vector) const;
SparseMatrix transpose (void) const;
SparseMatrix subtract (SparseMatrix const& rhs) const;
SparseMatrix multiply (SparseMatrix const& rhs) const;
SparseMatrix sequential_multiply (SparseMatrix const& rhs) const;
SparseMatrix parallel_multiply (SparseMatrix const& rhs) const;
DenseVector<T> multiply (DenseVector<T> const& rhs) const;
SparseMatrix diagonal_matrix (void) const;
std::size_t num_non_zero (void) const;
std::size_t num_rows (void) const;
std::size_t num_cols (void) const;
T* begin (void);
T* end (void);
void debug (void) const;
private:
std::size_t rows;
std::size_t cols;
std::vector<T> values;
std::vector<std::size_t> outer;
std::vector<std::size_t> inner;
};
SFM_BA_NAMESPACE_END
SFM_NAMESPACE_END
/* ------------------------ Implementation ------------------------ */
#include <iostream>
SFM_NAMESPACE_BEGIN
SFM_BA_NAMESPACE_BEGIN
template <typename T>
SparseMatrix<T>::Triplet::Triplet (std::size_t row,
std::size_t col, T const& value)
: row(row), col(col), value(value)
{
}
/* --------------------------------------------------------------- */
template <typename T>
SparseMatrix<T>::SparseMatrix (void)
: rows(0)
, cols(0)
{
}
template <typename T>
SparseMatrix<T>::SparseMatrix (std::size_t rows, std::size_t cols)
{
this->allocate(rows, cols);
}
template <typename T>
void
SparseMatrix<T>::allocate (std::size_t rows, std::size_t cols)
{
this->rows = rows;
this->cols = cols;
this->values.clear();
this->outer.clear();
this->inner.clear();
this->outer.resize(cols + 1, 0);
}
template <typename T>
void
SparseMatrix<T>::reserve (std::size_t num_elements)
{
this->inner.reserve(num_elements);
this->values.reserve(num_elements);
}
template <typename T>
void
SparseMatrix<T>::set_from_triplets (Triplets const& triplets)
{
/* Create a temporary transposed matrix */
SparseMatrix<T> transposed(this->cols, this->rows);
transposed.values.resize(triplets.size());
transposed.inner.resize(triplets.size());
/* Initialize outer indices with amount of inner values. */
for (std::size_t i = 0; i < triplets.size(); ++i)
transposed.outer[triplets[i].row]++;
/* Convert amounts to indices with prefix sum. */
std::size_t sum = 0;
std::vector<std::size_t> scratch(transposed.outer.size());
for (std::size_t i = 0; i < transposed.outer.size(); ++i)
{
std::size_t const temp = transposed.outer[i];
transposed.outer[i] = sum;
scratch[i] = sum;
sum += temp;
}
/* Add triplets, inner indices are unsorted. */
for (std::size_t i = 0; i < triplets.size(); ++i)
{
Triplet const& t = triplets[i];
std::size_t pos = scratch[t.row]++;
transposed.values[pos] = t.value;
transposed.inner[pos] = t.col;
}
/* Transpose matrix, implicit sorting of inner indices. */
*this = transposed.transpose();
}
template <typename T>
SparseMatrix<T>
SparseMatrix<T>::transpose (void) const
{
SparseMatrix ret(this->cols, this->rows);
ret.values.resize(this->num_non_zero());
ret.inner.resize(this->num_non_zero());
/* Compute inner sizes of transposed matrix. */
for(std::size_t i = 0; i < this->inner.size(); ++i)
ret.outer[this->inner[i]] += 1;
/* Compute outer sizes of transposed matrix with prefix sum. */
std::size_t sum = 0;
std::vector<std::size_t> scratch(ret.outer.size());
for (std::size_t i = 0; i < ret.outer.size(); ++i)
{
std::size_t const temp = ret.outer[i];
ret.outer[i] = sum;
scratch[i] = sum;
sum += temp;
}
/* Write inner indices and values of transposed matrix. */
for (std::size_t i = 0; i < this->outer.size() - 1; ++i)
for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j)
{
std::size_t pos = scratch[this->inner[j]]++;
ret.inner[pos] = i;
ret.values[pos] = this->values[j];
}
return ret;
}
template <typename T>
SparseMatrix<T>
SparseMatrix<T>::subtract (SparseMatrix const& rhs) const
{
if (this->rows != rhs.rows || this->cols != rhs.cols)
throw std::invalid_argument("Incompatible matrix dimensions");
SparseMatrix ret(this->rows, this->cols);
ret.reserve(this->num_non_zero() + rhs.num_non_zero());
std::size_t num_outer = this->outer.size() - 1;
for (std::size_t outer = 0; outer < num_outer; ++outer)
{
ret.outer[outer] = ret.values.size();
std::size_t i1 = this->outer[outer];
std::size_t i2 = rhs.outer[outer];
std::size_t const i1_end = this->outer[outer + 1];
std::size_t const i2_end = rhs.outer[outer + 1];
while (i1 < i1_end || i2 < i2_end)
{
if (i1 >= i1_end)
{
ret.values.push_back(-rhs.values[i2]);
ret.inner.push_back(rhs.inner[i2]);
i2 += 1;
continue;
}
if (i2 >= i2_end)
{
ret.values.push_back(this->values[i1]);
ret.inner.push_back(this->inner[i1]);
i1 += 1;
continue;
}
std::size_t id1 = this->inner[i1];
std::size_t id2 = rhs.inner[i2];
if (id1 < id2)
ret.values.push_back(this->values[i1]);
else if (id2 < id1)
ret.values.push_back(-rhs.values[i2]);
else
ret.values.push_back(this->values[i1] - rhs.values[i2]);
i1 += static_cast<std::size_t>(id1 <= id2);
i2 += static_cast<std::size_t>(id2 <= id1);
ret.inner.push_back(std::min(id1, id2));
}
}
ret.outer.back() = ret.values.size();
return ret;
}
template <typename T>
SparseMatrix<T>
SparseMatrix<T>::multiply (SparseMatrix const& rhs) const
{
#ifdef _OPENMP
return this->parallel_multiply(rhs);
#else
return this->sequential_multiply(rhs);
#endif
}
template <typename T>
SparseMatrix<T>
SparseMatrix<T>::sequential_multiply (SparseMatrix const& rhs) const
{
if (this->cols != rhs.rows)
throw std::invalid_argument("Incompatible matrix dimensions");
SparseMatrix ret(this->rows, rhs.cols);
ret.reserve(this->num_non_zero() + rhs.num_non_zero());
/* Matrix-matrix multiplication. */
std::vector<T> ret_col(ret.rows, T(0));
std::vector<bool> ret_nonzero(ret.rows, false);
for (std::size_t col = 0; col < ret.cols; ++col)
{
ret.outer[col] = ret.values.size();
std::fill(ret_col.begin(), ret_col.end(), T(0));
std::fill(ret_nonzero.begin(), ret_nonzero.end(), false);
std::size_t rhs_col_begin = rhs.outer[col];
std::size_t rhs_col_end = rhs.outer[col + 1];
for (std::size_t i = rhs_col_begin; i < rhs_col_end; ++i)
{
T const& rhs_col_value = rhs.values[i];
std::size_t const lhs_col = rhs.inner[i];
std::size_t const lhs_col_begin = this->outer[lhs_col];
std::size_t const lhs_col_end = this->outer[lhs_col + 1];
for (std::size_t j = lhs_col_begin; j < lhs_col_end; ++j)
{
std::size_t const id = this->inner[j];
ret_col[id] += this->values[j] * rhs_col_value;
ret_nonzero[id] = true;
}
}
for (std::size_t i = 0; i < ret.rows; ++i)
if (ret_nonzero[i])
{
ret.inner.push_back(i);
ret.values.push_back(ret_col[i]);
}
}
ret.outer[ret.cols] = ret.values.size();
return ret;
}
template <typename T>
SparseMatrix<T>
SparseMatrix<T>::parallel_multiply (SparseMatrix const& rhs) const
{
if (this->cols != rhs.rows)
throw std::invalid_argument("Incompatible matrix dimensions");
std::size_t nnz = this->num_non_zero() + rhs.num_non_zero();
SparseMatrix ret(this->rows, rhs.cols);
ret.reserve(nnz);
std::fill(ret.outer.begin(), ret.outer.end(), 0);
std::size_t const chunk_size = 64;
std::size_t const num_chunks = ret.cols / chunk_size
+ (ret.cols % chunk_size != 0);
std::size_t const max_threads = std::max(1u,
std::thread::hardware_concurrency());
std::size_t const num_threads = std::min(num_chunks, max_threads);
#pragma omp parallel num_threads(num_threads)
{
/* Matrix-matrix multiplication. */
std::vector<T> ret_col(ret.rows, T(0));
std::vector<bool> ret_nonzero(ret.rows, false);
std::vector<T> thread_values;
thread_values.reserve(nnz / num_chunks);
std::vector<std::size_t> thread_inner;
thread_inner.reserve(nnz / num_chunks);
#pragma omp for ordered schedule(static, 1)
for (std::size_t chunk = 0; chunk < num_chunks; ++chunk)
{
thread_inner.clear();
thread_values.clear();
std::size_t const begin = chunk * chunk_size;
std::size_t const end = std::min(begin + chunk_size, ret.cols);
for (std::size_t col = begin; col < end; ++col)
{
std::fill(ret_col.begin(), ret_col.end(), T(0));
std::fill(ret_nonzero.begin(), ret_nonzero.end(), false);
std::size_t const rhs_col_begin = rhs.outer[col];
std::size_t const rhs_col_end = rhs.outer[col + 1];
for (std::size_t i = rhs_col_begin; i < rhs_col_end; ++i)
{
T const& rhs_col_value = rhs.values[i];
std::size_t const lhs_col = rhs.inner[i];
std::size_t const lhs_col_begin = this->outer[lhs_col];
std::size_t const lhs_col_end = this->outer[lhs_col + 1];
for (std::size_t j = lhs_col_begin; j < lhs_col_end; ++j)
{
std::size_t const id = this->inner[j];
ret_col[id] += this->values[j] * rhs_col_value;
ret_nonzero[id] = true;
}
}
for (std::size_t i = 0; i < ret.rows; ++i)
if (ret_nonzero[i])
{
ret.outer[col + 1] += 1;
thread_inner.push_back(i);
thread_values.push_back(ret_col[i]);
}
}
#pragma omp ordered
{
ret.inner.insert(ret.inner.end(),
thread_inner.begin(), thread_inner.end());
ret.values.insert(ret.values.end(),
thread_values.begin(), thread_values.end());
}
}
}
for (std::size_t col = 0; col < ret.cols; ++col)
ret.outer[col + 1] += ret.outer[col];
return ret;
}
template<typename T>
DenseVector<T>
SparseMatrix<T>::multiply (DenseVector<T> const& rhs) const
{
if (rhs.size() != this->cols)
throw std::invalid_argument("Incompatible dimensions");
DenseVector<T> ret(this->rows, T(0));
for (std::size_t i = 0; i < this->cols; ++i)
for (std::size_t id = this->outer[i]; id < this->outer[i + 1]; ++id)
ret[this->inner[id]] += this->values[id] * rhs[i];
return ret;
}
template<typename T>
SparseMatrix<T>
SparseMatrix<T>::diagonal_matrix (void) const
{
std::size_t const diag_size = std::min(this->rows, this->cols);
SparseMatrix ret(diag_size, diag_size);
ret.reserve(diag_size);
for (std::size_t i = 0; i < diag_size; ++i)
{
ret.outer[i] = ret.values.size();
for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j)
if (this->inner[j] == i)
{
ret.inner.push_back(i);
ret.values.push_back(this->values[j]);
}
else if (this->inner[j] > i)
break;
}
ret.outer[diag_size] = ret.values.size();
return ret;
}
template<typename T>
void
SparseMatrix<T>::mult_diagonal (T const& factor)
{
for (std::size_t i = 0; i < this->outer.size() - 1; ++i)
for (std::size_t j = this->outer[i]; j < this->outer[i + 1]; ++j)
{
if (this->inner[j] == i)
this->values[j] *= factor;
if (this->inner[j] >= i)
break;
}
}
template<typename T>
void
SparseMatrix<T>::cwise_invert (void)
{
for (std::size_t i = 0; i < this->values.size(); ++i)
this->values[i] = T(1) / this->values[i];
}
template<typename T>
void
SparseMatrix<T>::column_nonzeros (std::size_t col, DenseVector<T>* vector) const
{
std::size_t const start = this->outer[col];
std::size_t const end = this->outer[col + 1];
vector->resize(end - start);
for (std::size_t row = start, i = 0; row < end; ++row, ++i)
vector->at(i) = this->values[row];
}
template<typename T>
inline std::size_t
SparseMatrix<T>::num_non_zero (void) const
{
return this->values.size();
}
template<typename T>
inline std::size_t
SparseMatrix<T>::num_rows (void) const
{
return this->rows;
}
template<typename T>
inline std::size_t
SparseMatrix<T>::num_cols (void) const
{
return this->cols;
}
template<typename T>
inline T*
SparseMatrix<T>::begin (void)
{
return this->values.data();
}
template<typename T>
inline T*
SparseMatrix<T>::end (void)
{
return this->values.data() + this->values.size();
}
template<typename T>
void
SparseMatrix<T>::debug (void) const
{
std::cout << "SparseMatrix ("
<< this->rows << " rows, " << this->cols << " cols, "
<< this->num_non_zero() << " values)" << std::endl;
std::cout << " Values:";
for (std::size_t i = 0; i < this->values.size(); ++i)
std::cout << " " << this->values[i];
std::cout << std::endl << " Inner:";
for (std::size_t i = 0; i < this->inner.size(); ++i)
std::cout << " " << this->inner[i];
std::cout << std::endl << " Outer:";
for (std::size_t i = 0; i < this->outer.size(); ++i)
std::cout << " " << this->outer[i];
std::cout << std::endl;
}
SFM_BA_NAMESPACE_END
SFM_NAMESPACE_END
#endif // SFM_SPARSE_MATRIX_HEADER
|
pragmaScope.c | // This example exposes the problem of have a pragma and a following statement in the same scope without brackets.
int main(){
int i,j;
int n=10, m=10;
int a[n][m];
for(i=0;i<n; i++)
for(j=0;j<n; j++)
a[i][j]= 0;
for (i=0;i<n-1;i++)
#pragma omp parallel for
for (j=0;j<m-1;j++)
a[i][j]=a[i+1][j+1];
}
|
Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
//
// The LLVM37 Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM37_CLANG_SEMA_SEMA_H
#define LLVM37_CLANG_SEMA_SEMA_H
#include "clang/AST/Attr.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/LocInfoType.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm37/ADT/ArrayRef.h"
#include "llvm37/ADT/Optional.h"
#include "llvm37/ADT/SetVector.h"
#include "llvm37/ADT/SmallPtrSet.h"
#include "llvm37/ADT/SmallVector.h"
#include "llvm37/ADT/TinyPtrVector.h"
#include <deque>
#include <memory>
#include <string>
#include <vector>
// HLSL Change Starts
#include "llvm37/Support/OacrIgnoreCond.h" // HLSL Change - all sema use is heavily language-dependant
namespace hlsl {
struct UnusualAnnotation;
}
// HLSL Change Ends
namespace llvm37 {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
class InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class AttributeList;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class ExternalSemaSource;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPClause;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm37::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm37::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///\brief Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///\brief Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
// We are about to link these. It is now safe to compute the linkage of
// the new decl. If the new decl has external linkage, we will
// link it with the hidden decl (which also has external linkage) and
// it will keep having external linkage. If it has internal linkage, we
// will not link it. Since it has no previous decls, it will remain
// with internal linkage.
if (getLangOpts().ModulesHideInternalLinkage)
return isVisible(Old) || New->isExternallyVisible();
return true;
}
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
/// \brief Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// \brief Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// \brief Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
/// PackContext - Manages the stack for \#pragma pack. An alignment
/// of 0 indicates default alignment.
void *PackContext; // Really a "PragmaPackStack*"
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// \brief Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
// HLSL Change Begin
// The HLSL rewriter doesn't define a default matrix pack,
// so we must preserve the lack of annotations to avoid changing semantics.
bool HasDefaultMatrixPack = false;
// Uses of #pragma pack_matrix change the default pack.
bool DefaultMatrixPackRowMajor = false;
// HLSL Change End.
enum PragmaVtorDispKind {
PVDK_Push, ///< #pragma vtordisp(push, mode)
PVDK_Set, ///< #pragma vtordisp(mode)
PVDK_Pop, ///< #pragma vtordisp(pop)
PVDK_Reset ///< #pragma vtordisp()
};
enum PragmaMsStackAction {
PSK_Reset, // #pragma ()
PSK_Set, // #pragma ("name")
PSK_Push, // #pragma (push[, id])
PSK_Push_Set, // #pragma (push[, id], "name")
PSK_Pop, // #pragma (pop[, id])
PSK_Pop_Set, // #pragma (pop[, id], "name")
};
/// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
///
/// The stack always has at least one element in it.
SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// \brief Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm37::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
Slot(llvm37::StringRef StackSlotLabel,
ValueType Value,
SourceLocation PragmaLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm37::StringRef StackSlotLabel,
ValueType Value);
explicit PragmaStack(const ValueType &Value)
: CurrentValue(Value) {}
SmallVector<Slot, 2> Stack;
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// \brief This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// \brief Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// ExprNeedsCleanups - True if the current evaluation context
/// requires cleanups to be run at its conclusion.
bool ExprNeedsCleanups;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// \brief Store a list of either DeclRefExprs or MemberExprs
/// that contain a reference to a variable (constant) that may or may not
/// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
/// and discarded value conversions have been applied to all subexpressions
/// of the enclosing full expression. This is cleared at the end of each
/// full expression.
llvm37::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
/// \brief Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
///
/// This array is never empty. Clients should ignore the first
/// element, which is used to cache a single FunctionScopeInfo
/// that's used to parse every top-level function.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm37::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
/// \brief Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// \brief Set containing all typedefs that are likely unused.
llvm37::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// \brief Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm37::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm37::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm37::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm37::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// \brief Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// \brief All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// \brief The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// \brief All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// \brief All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedExceptionSpecChecks;
/// \brief All the members seen during a class definition which were both
/// explicitly defaulted and had explicitly-specified exception
/// specifications, along with the function type containing their
/// user-specified exception specification. Those exception specifications
/// were overridden with the default specifications, but we still need to
/// check whether they are compatible with the default specification, and
/// we can't do that until the nesting set of class definitions is complete.
SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
DelayedDefaultedMemberExceptionSpecs;
typedef llvm37::MapVector<const FunctionDecl *, LateParsedTemplate *>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// \brief Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// \brief The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// \brief RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC)
{
S.PushFunctionScope();
S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
}
~SynthesizedFunctionScope() {
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm37::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm37::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// \brief Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// \brief The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// \brief The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// \brief The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// \brief Caches identifiers/selectors for NSFoundation APIs.
// std::unique_ptr<NSAPI> NSAPIObj; // HLSL Change
/// \brief The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// \brief The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// \brief Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// \brief Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// \brief The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// \brief The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// \brief Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// \brief The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// \brief The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// \brief The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// \brief The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// \brief The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// \brief id<NSCopying> type.
QualType QIDNSCopying;
/// \brief will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// \brief counter for internal MS Asm label names.
unsigned MSAsmLabelNameCounter;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// \brief Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum ExpressionEvaluationContext {
/// \brief The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// \brief The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// \brief The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// \brief The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// \brief The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// \brief Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// \brief The expression evaluation context.
ExpressionEvaluationContext Context;
/// \brief Whether the enclosing context needed a cleanup.
bool ParentNeedsCleanups;
/// \brief Whether we are in a decltype expression.
bool IsDecltype;
/// \brief The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// \brief The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
llvm37::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
/// \brief The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// \brief The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// \brief The context information used to mangle lambda expressions
/// and block literals within this context.
///
/// This mangling information is allocated lazily, since most contexts
/// do not have lambda expressions or block literals.
IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
/// \brief If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// \brief If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
bool ParentNeedsCleanups,
Decl *ManglingContextDecl,
bool IsDecltype)
: Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
NumTypos(0),
ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
/// \brief Retrieve the mangling numbering context, used to consistently
/// number constructs like lambdas for mangling.
MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
bool isUnevaluated() const {
return Context == Unevaluated || Context == UnevaluatedAbstract;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// \brief Compute the mangling number context for a lambda expression or
/// block literal.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
/// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
/// associated with the context, if relevant.
MangleNumberingContext *getCurrentMangleNumberContext(
const DeclContext *DC,
Decl *&ManglingContextDecl);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult : public llvm37::FastFoldingSetNode {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm37::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult(const llvm37::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
/// \brief A cache of special member function overload resolution results
/// for C++ records.
llvm37::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
/// \brief The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm37::BumpPtrAllocator BumpAlloc;
/// \brief The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm37::DenseMap<ParmVarDecl *, llvm37::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// \brief A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm37::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm37::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm37::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm37::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm37::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm37::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
void ReadMethodPool(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// \brief Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema& S)
: S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
~FPContractStateRAII() {
S.FPFeatures.fp_contract = OldFPContractState;
}
private:
Sema& S;
bool OldFPContractState : 1;
};
void addImplicitTypedef(StringRef Name, QualType T);
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// \brief Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///\brief Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// \brief Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// \brief Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// \brief Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// \brief Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// \brief Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// \brief Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// \brief Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
void ActOnEndOfTranslationUnit();
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// \brief This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD,
CapturedRegionKind K);
void
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
const BlockExpr *blkExpr = nullptr);
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const {
if (FunctionScopes.empty())
return nullptr;
for (int e = FunctionScopes.size()-1; e >= 0; --e) {
if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
continue;
return FunctionScopes[e];
}
return nullptr;
}
template <typename ExprT>
void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
if (!isUnevaluatedContext())
getCurFunction()->recordUseOfWeak(E, IsRead);
}
void PushCompoundScope();
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// \brief Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// \brief Retrieve the current lambda scope info, if any.
sema::LambdaScopeInfo *getCurLambda();
/// \brief Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// \brief Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
unsigned deduceWeakPropertyFromType(QualType T) {
if ((getLangOpts().getGC() != LangOptions::NonGC &&
T.isObjCGCWeak()) ||
(getLangOpts().ObjCAutoRefCount &&
T.getObjCLifetime() == Qualifiers::OCL_Weak))
return ObjCDeclSpec::DQ_PR_weak;
return 0;
}
/// \brief Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
QualType BuildFunctionType(QualType T,
MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI);
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
TypeSourceInfo *ReturnTypeInfo);
/// \brief Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Expr *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc,
bool *MissingExceptionSpecification = nullptr,
bool *MissingEmptyExceptionSpecification = nullptr,
bool AllowNoexceptAllMatchWithNoSpec = false,
bool IsOperatorNew = false);
bool CheckExceptionSpecSubset(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
const FunctionProtoType *Target, SourceLocation TargetLoc,
const FunctionProtoType *Source, SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// \brief The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// \brief Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
bool Suppressed;
TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
llvm37::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
if (Suppressed)
return;
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, llvm37::index_sequence_for<Ts...>());
DB << T;
}
};
private:
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
VisibleModuleSet VisibleModules;
llvm37::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
Module *CachedFakeTopLevelModule;
public:
/// \brief Get the module owning an entity.
Module *getOwningModule(Decl *Entity);
/// \brief Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
bool hasVisibleMergedDefinition(NamedDecl *Def);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm37::SmallVectorImpl<Module *> *Modules = nullptr);
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
/// List of decls defined in a function prototype. This contains EnumConstants
/// that incorrectly end up in translation unit scope because there is no
/// function to pin them on. ActOnFunctionDeclarator reads this list and patches
/// them into the FunctionDecl.
std::vector<NamedDecl*> DeclsInPrototypeScope;
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false,
bool HasTrailingDot = false,
ParsedType ObjectType = ParsedType(),
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool AllowClassTemplates = false);
/// \brief For compatibility with MSVC, we delay parsing of some default
/// template type arguments until instantiation time. Emits a warning and
/// returns a synthesized DependentNameType that isn't really dependent on any
/// other template arguments.
ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
SourceLocation NameLoc);
/// \brief Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
NC_Unknown,
NC_Error,
NC_Keyword,
NC_Type,
NC_Expression,
NC_NestedNameSpecifier,
NC_TypeTemplate,
NC_VarTemplate,
NC_FunctionTemplate
};
class NameClassification {
NameClassificationKind Kind;
ExprResult Expr;
TemplateName Template;
ParsedType Type;
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *)
: Kind(NC_Keyword) {
}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification NestedNameSpecifier() {
return NameClassification(NC_NestedNameSpecifier);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
ExprResult getExpression() const {
assert(Kind == NC_Expression);
return Expr;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
default:
llvm37_unreachable("unsupported name classification.");
}
}
};
/// \brief Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param IsAddressOfOperand True if this name is the operand of a unary
/// address of ('&') expression, assuming it is classified as an
/// expression.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification
ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
SourceLocation NameLoc, const Token &NextToken,
bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name,
SourceLocation Loc);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
void CheckShadow(Scope *S, VarDecl *D);
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
// HLSL Change Starts
// This enumeration is used to determine whether a variable declaration
// should shadow a prior declaration rather than merging.
enum ShadowMergeState {
ShadowMergeState_Disallowed, // shadowing is not allowed
ShadowMergeState_Possible, // shadowing is possible (but may not occur)
ShadowMergeState_Effective // the declaration should shadow a prior one
};
// HLSL Change Ends
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ShadowMergeState MergeState = ShadowMergeState_Disallowed); // HLSL Change - add merge state
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, ShadowMergeState MergeState = ShadowMergeState_Disallowed); // HLSL Change - add merge state
void CheckVariableDeclarationType(VarDecl *NewVD);
void CheckCompleteVariableDeclaration(VarDecl *var);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsExplicitSpecialization);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SCm, hlsl::ParameterModifier ParamMod); // HLSL Change
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
bool TypeMayContainAuto);
void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
bool TypeMayContainAuto = true);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(FunctionDecl *FD,
const FunctionDecl *EffectiveDefinition =
nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// \brief Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// \brief Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// \brief Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
ParmVarDecl * const *End);
/// \brief Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
ParmVarDecl * const *End,
QualType ReturnTy,
NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// \brief Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S,
AttributeList *AttrList,
SourceLocation SemiLoc);
/// \brief The parser has processed a module import declaration.
///
/// \param AtLoc The location of the '@' symbol, if any.
///
/// \param ImportLoc The location of the 'import' keyword.
///
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
ModuleIdPath Path);
/// \brief The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// \brief Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument
};
/// \brief Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
bool NeedDefinition, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
/// \brief Retrieve a suitable printing policy.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// \brief Retrieve a suitable printing policy.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation = false);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
struct SkipBodyInfo {
SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
bool ShouldSkip;
NamedDecl *Previous;
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr, AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists,
bool &OwnedDecl, bool &IsDependent,
SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
AttributeList *MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields,
SourceLocation LBrac, SourceLocation RBrac,
AttributeList *AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
typedef void *SkippedDefinitionContext;
/// \brief Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceLocation RBraceLoc);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// \brief Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
AttributeList *Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
SourceLocation RBraceLoc, Decl *EnumDecl,
ArrayRef<Decl *> Elements,
Scope *S, AttributeList *Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// \brief Make the given externally-produced declaration visible at the
/// top level scope.
///
/// \param D The externally-produced declaration to push.
///
/// \param Name The name of the externally-produced declaration.
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
IdentifierInfo *Platform,
VersionTuple Introduced,
VersionTuple Deprecated,
VersionTuple Obsoleted,
bool IsUnavailable,
StringRef Message,
bool Override,
unsigned AttrSpellingListIndex);
TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
TypeVisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
VisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
unsigned AttrSpellingListIndex,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
IdentifierInfo *Format, int FormatIdx,
int FirstArg, unsigned AttrSpellingListIndex);
SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
/// \brief Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// \brief Don't merge availability attributes at all.
AMK_None,
/// \brief Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// \brief Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override
};
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous, ShadowMergeState& MergeState); // HLSL Change - add merge state
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld, ShadowMergeState& MergeState); // HLSL Change - add merge state
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
/// \brief Checks availability of the function depending on the current
/// function context.Inside an unavailable function,unavailability is ignored.
///
/// \returns true if \p FD is unavailable and current context is inside
/// an available function, false otherwise.
bool isFunctionConsideredUnavailable(FunctionDecl *FD);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsNoReturnConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm37::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// \brief Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// \brief Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// \brief Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm37::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm37::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
void AddOverloadCandidate(FunctionDecl *Function,
DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = false);
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false);
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddConversionCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet& CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
// Emit as a series of 'note's all template and non-templates
// identified by the expression Expr
void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
const SourceRange& OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
// An enum to represent whether something is dealing with a call to begin()
// or a call to end() in a range-based for loop.
enum BeginEndFunction {
BEF_begin,
BEF_end
};
ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
SourceLocation RangeLoc,
VarDecl *Decl,
BeginEndFunction BEF,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *input);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
ParmVarDecl *const *ParamEnd,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// @brief Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// \brief Look up any declaration with any name.
LookupAnyName
};
/// \brief Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// \brief The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// \brief The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists.
ForRedeclaration
};
/// \brief The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// \brief The lookup resulted in an error.
LOLR_Error,
/// \brief The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// \brief The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState&& other) LLVM37_NOEXCEPT;
TypoExprState& operator=(TypoExprState&& other) LLVM37_NOEXCEPT;
};
/// \brief The set of unhandled TypoExprs and their associated state.
llvm37::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// \brief Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm37::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// \brief Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// \brief Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// \brief Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
DeclAccessPair Operator,
QualType T1, QualType T2);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate);
bool isKnownName(StringRef name);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// \brief Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm37::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm37::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm37::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm37::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const AttributeList *AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckNoReturnAttr(const AttributeList &attr);
bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType &T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type.
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param nullabilityLoc The location of the nullability specifier.
///
/// \param isContextSensitive Whether this nullability specifier was
/// written as a context-sensitive keyword (in an Objective-C
/// method) or an Objective-C property attribute, rather than as an
/// underscored type specifier.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
SourceLocation nullabilityLoc,
bool isContextSensitive);
/// \brief Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm37::SmallPtrSet<Selector, 8> SelectorSet;
typedef llvm37::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl *IDecl);
void DefaultSynthesizeProperties(Scope *S, Decl *D);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
bool *isOverridingProperty,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// \brief Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// \brief - Returns instance or factory methods in global method pool for
/// given selector. If no such method or only one method found, function returns
/// false; otherwise, it returns true
bool CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool instance);
bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R,
bool receiverIdOrClass);
void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// \brief - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance);
/// \brief Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg);
StmtResult ActOnExprStmtError();
StmtResult ActOnHlslDiscardStmt(SourceLocation Loc); // HLSL Change
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// \brief A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S): S(S) {
S.ActOnStartOfCompoundStmt();
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
SourceLocation DotDotDotLoc, Expr *RHSVal,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
StmtResult ActOnIfStmt(SourceLocation IfLoc,
FullExprArg CondVal, Decl *CondVar,
Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Expr *Cond,
Decl *CondVar);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
FullExprArg Cond,
Decl *CondVar, Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc,
SourceLocation CondLParen, Expr *Cond,
SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First, FullExprArg Second,
Decl *SecondVar,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *BeginEndDecl,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
bool AllowFunctionParameters);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
bool AllowFunctionParameters);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
SourceLocation RParenLoc);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
llvm37::InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// \brief If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
NamedDecl *D, StringRef Message,
SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
const ObjCPropertyDecl *ObjCProperty,
bool ObjCPropertyAccess);
bool makeUnavailableInSystemHeader(SourceLocation loc,
StringRef message);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D);
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
bool ObjCPropertyAccess=false);
void NoteDeletedFunction(FunctionDecl *FD);
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
ReuseLambdaContextDecl_t,
bool IsDecltype = false);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool OdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E);
void MarkMemberReferenced(MemberExpr *E);
void UpdateMarkingForLValueToRValue(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// \brief Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// \brief Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// \brief Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// \brief Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// \brief Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// \brief Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
ExprResult
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult BuildQualifiedDeclarationNameExpr(
CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentType IT);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
const SourceRange &ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
// HLSL Change Begins
bool CheckHLSLUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation Loc,
UnaryExprOrTypeTrait ExprKind);
// HLSL Change Ends
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
SourceLocation LParenLoc,
ArrayRef<Expr *> Arg,
SourceLocation RParenLoc,
Expr *Config = nullptr,
bool IsExecConfig = false);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// \brief Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// \brief Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// \brief The symbol exists.
IER_Exists,
/// \brief The symbol does not exist.
IER_DoesNotExist,
/// \brief The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// \brief An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
// HLSL Change Starts
//===---------------------------- HLSL Features -------------------------===//
/// cbuffer/tbuffer
llvm37::SmallVector<Decl*, 1> HLSLBuffers;
Decl* ActOnStartHLSLBuffer(Scope* bufferScope, bool cbuffer, SourceLocation KwLoc,
IdentifierInfo *Ident, SourceLocation IdentLoc,
std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
SourceLocation LBrace);
void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace);
Decl* getActiveHLSLBuffer() const;
void ActOnStartHLSLBufferView();
bool IsOnHLSLBufferView();
Decl *ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
DeclGroupPtrTy &dcl, bool iscbuf);
// HLSL Change Ends
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc,
IdentifierInfo *Ident,
SourceLocation LBrace,
AttributeList *AttrList);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
CXXRecordDecl *getStdBadAlloc() const;
/// \brief Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// \brief Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// \brief Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const CXXConstructorDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope,
SourceLocation UsingLoc,
SourceLocation NamespcLoc,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
AttributeList *AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
DeclarationNameInfo NameInfo,
AttributeList *AttrList,
bool IsInstantiation,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
Decl *ActOnUsingDeclaration(Scope *CurScope,
AccessSpecifier AS,
bool HasUsingKeyword,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
UnqualifiedId &Name,
AttributeList *AttrList,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
Decl *ActOnAliasDeclaration(Scope *CurScope,
AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc,
UnqualifiedId &Name,
AttributeList *AttrList,
TypeResult Type,
Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// \brief Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm37::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// \brief Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(ComputedEST != EST_ComputedNoexcept &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// \brief The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// \brief The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// \brief Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// \brief Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// \brief Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_ComputedNoexcept;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// \brief Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defautled
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
/// \brief Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// \brief Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// \brief Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// \brief Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
/// \brief Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
/// \brief Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// \brief Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
CXXDestructorDecl *Destructor);
/// \brief Declare all inheriting constructors for the given class.
///
/// \param ClassDecl The class declaration into which the inheriting
/// constructors will be added.
void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
/// \brief Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// \brief Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// \brief Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// \brief Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// \brief Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// \brief Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// \brief When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// \brief RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// \brief Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// \brief Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr);
/// \brief Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Expr *ArraySize,
SourceRange DirectInitRange,
Expr *Initializer,
bool TypeMayContainAuto = true);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
bool UseGlobal, QualType AllocType, bool IsArray,
MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete);
bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
DeclarationName Name, MultiExprArg Args,
DeclContext *Ctx,
bool AllowMissing, FunctionDecl *&Operator,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
QualType Param1,
QualType Param2 = QualType(),
bool addRestrictAttr = false);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
DeclarationName Name);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
bool ConvertToBoolean);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// \brief Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
ExprResult ActOnFinishFullExpr(Expr *Expr) {
return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
: SourceLocation());
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue = false,
bool IsConstexpr = false,
bool IsLambdaInitCaptureInitializer = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// \brief The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// \brief The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
SourceLocation IdLoc,
IdentifierInfo &II,
ParsedType ObjectType);
bool BuildCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
QualType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr);
/// \brief The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param Identifier The identifier preceding the '::'.
///
/// \param IdentifierLoc The location of the identifier.
///
/// \param CCLoc The location of the '::'.
///
/// \param ObjectType The type of the object, if we're parsing
/// nested-name-specifier in a member access expression.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
ParsedType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation ColonLoc,
ParsedType ObjectType,
bool EnteringContext);
/// \brief The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// \brief Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// \brief Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// \brief Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// \brief Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params);
/// \brief Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// \brief Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
bool ByRef, IdentifierInfo *Id, Expr *&Init);
/// \brief Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
/// \brief Build the implicit field for an init-capture.
FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// \brief Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief Introduce the lambda parameters into scope.
void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
/// \brief Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// \brief Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// \brief Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// \brief Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
Expr **Strings,
unsigned NumStrings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
ObjCDictionaryElement *Elements,
unsigned NumElements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access,
SourceLocation ASLoc,
SourceLocation ColonLoc,
AttributeList *Attrs = nullptr);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// \brief The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// \brief The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// \brief The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm37::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// \brief Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// \brief Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// \brief Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc,
const CXXRecordDecl *RD);
/// \brief Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
void CheckCompletedCXXClass(CXXRecordDecl *Record);
void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Decl *TagDecl,
SourceLocation LBrac,
SourceLocation RBrac,
AttributeList *AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXMemberDefaultArgs(Decl *D);
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
const FunctionProtoType *T);
void CheckDelayedMemberExceptionSpecs();
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
unsigned NumBases);
void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
unsigned NumBases);
bool IsDerivedFrom(QualType Derived, QualType Base);
bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
AccessSpecifier access,
QualType objectType);
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// \brief When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
AbstractDiagSelID SelID = AbstractNone);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
Decl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
Decl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
Decl **Params, unsigned NumParams,
SourceLocation RAngleLoc);
/// \brief The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
TemplateParameterList *TemplateParams,
AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc,
unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false);
/// \brief Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template);
DeclResult
ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc,
SourceLocation ModulePrivateLoc,
TemplateIdAnnotation &TemplateId,
AttributeList *Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
const CXXScopeSpec &SS,
TemplateTy Template,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
AttributeList *Attr);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
AttributeList *Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// \brief Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// \brief The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// \brief The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// \brief The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// \brief Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
TemplateArgumentLoc &Arg,
unsigned ArgumentPackIndex);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// \brief Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// \brief We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// \brief We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// \brief We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// \brief Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// \brief Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// \brief The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// \brief An arbitrary expression.
UPPC_Expression = 0,
/// \brief The base type of a class type.
UPPC_BaseType,
/// \brief The type of an arbitrary declaration.
UPPC_DeclarationType,
/// \brief The type of a data member.
UPPC_DataMemberType,
/// \brief The size of a bit-field.
UPPC_BitFieldWidth,
/// \brief The expression in a static assertion.
UPPC_StaticAssertExpression,
/// \brief The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// \brief The enumerator value.
UPPC_EnumeratorValue,
/// \brief A using declaration.
UPPC_UsingDeclaration,
/// \brief A friend declaration.
UPPC_FriendDeclaration,
/// \brief A declaration qualifier.
UPPC_DeclarationQualifier,
/// \brief An initializer.
UPPC_Initializer,
/// \brief A default argument.
UPPC_DefaultArgument,
/// \brief The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// \brief The type of an exception.
UPPC_ExceptionType,
/// \brief Partial specialization.
UPPC_PartialSpecialization,
/// \brief Microsoft __if_exists.
UPPC_IfExists,
/// \brief Microsoft __if_not_exists.
UPPC_IfNotExists,
/// \brief Lambda expression.
UPPC_Lambda,
/// \brief Block expression,
UPPC_Block
};
/// \brief Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// \brief If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// \brief If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// \brief If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// \brief If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param SS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// \brief Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// \brief Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// \brief Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
/// \brief Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// \brief Template argument deduction was successful.
TDK_Success = 0,
/// \brief The declaration was invalid; do nothing.
TDK_Invalid,
/// \brief Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// \brief Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// \brief Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// \brief Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// \brief Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// \brief A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// \brief When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// \brief When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// \brief The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// \brief The arguments included an overloaded function name that could
/// not be resolved to a suitable function.
TDK_FailedOverloadResolution,
/// \brief Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType,
unsigned ArgIdx,
QualType OriginalArgType)
: OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) { }
QualType OriginalParamType;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult
FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
/// \brief Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// \brief Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// \brief Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
QualType &Result);
DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
QualType &Result);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm37::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm37::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm37::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// \brief A template instantiation that is currently in progress.
struct ActiveTemplateInstantiation {
/// \brief The kind of template instantiation we are performing
enum InstantiationKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template, and
/// TemplateArgs/NumTemplateArguments provides the template
/// arguments as specified.
/// FIXME: Use a TemplateArgumentList
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a ClassTemplatePartialSpecializationDecl or
/// a FunctionTemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation
} Kind;
/// \brief The point of instantiation within the source code.
SourceLocation PointOfInstantiation;
/// \brief The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// \brief The entity that is being instantiated.
Decl *Entity;
/// \brief The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
/// \brief The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// \brief The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// \brief The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
ActiveTemplateInstantiation()
: Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
/// \brief Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
friend bool operator==(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
if (X.Kind != Y.Kind)
return false;
if (X.Entity != Y.Entity)
return false;
switch (X.Kind) {
case TemplateInstantiation:
case ExceptionSpecInstantiation:
return true;
case PriorTemplateArgumentSubstitution:
case DefaultTemplateArgumentChecking:
return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
case DefaultTemplateArgumentInstantiation:
case ExplicitTemplateArgumentSubstitution:
case DeducedTemplateArgumentSubstitution:
case DefaultFunctionArgumentInstantiation:
return X.TemplateArgs == Y.TemplateArgs;
}
llvm37_unreachable("Invalid InstantiationKind!");
}
friend bool operator!=(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
return !(X == Y);
}
};
/// \brief List of active template instantiations.
///
/// This vector is treated as a stack. As one template instantiation
/// requires another template instantiation, additional
/// instantiations are pushed onto the stack up to a
/// user-configurable limit LangOptions::InstantiationDepth.
SmallVector<ActiveTemplateInstantiation, 16>
ActiveTemplateInstantiations;
/// \brief Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
/// \brief Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm37::DenseSet<Module*> LookupModulesCache;
/// \brief Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm37::DenseSet<Module*> &getLookupModules();
/// \brief Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// \brief The number of ActiveTemplateInstantiation entries in
/// \c ActiveTemplateInstantiations that are not actual instantiations and,
/// therefore, should not be counted as part of the instantiation depth.
unsigned NonInstantiationEntries;
/// \brief The last template from which a template instantiation
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant template
/// instantiation backtraces when there are multiple errors in the
/// same instantiation. FIXME: Does this belong in Sema? It's tough
/// to implement it anywhere else.
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
/// \brief The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// \brief RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// \brief The stack of calls expression undergoing template instantiation.
///
/// The top of this stack is used by a fixit instantiating unresolved
/// function calls to fix the AST to match the textual change it prints.
SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
/// \brief For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm37::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// \brief A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// \brief Note that we are instantiating a class template,
/// function template, or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// \brief Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
ActiveTemplateInstantiation::InstantiationKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// \brief Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
private:
Sema &SemaRef;
bool Invalid;
bool SavedInNonInstantiationSFINAEContext;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void PrintInstantiationStack();
/// \brief Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// \brief Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// \brief RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
}
/// \brief Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// \brief RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// \brief The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// \brief Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// \brief The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm37::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm37::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// \brief A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// \brief Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// \brief An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// \brief The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
class SavePendingInstantiationsAndVTableUsesRAII {
public:
SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
~SavePendingInstantiationsAndVTableUsesRAII() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// \brief The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class SavePendingLocalImplicitInstantiationsRAII {
public:
SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
~SavePendingLocalImplicitInstantiationsRAII() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
unsigned ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc,
ParmVarDecl **Params, unsigned NumParams,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param NumExprs The number of expressions in \p Exprs.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateStaticDataMemberDefinition(
SourceLocation PointOfInstantiation,
VarDecl *Var,
bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc,
IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
Decl * const *ProtoRefNames, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName,
SourceLocation CategoryLoc,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc);
Decl *ActOnStartClassImplementation(
SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
const IdentifierLocPair *IdentList,
unsigned NumElts,
AttributeList *attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
const IdentifierLocPair *ProtocolId,
unsigned NumProtocols,
SmallVectorImpl<Decl *> &Protocols);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Check the application of the Objective-C '__kindof' qualifier to
/// the given type.
bool checkObjCKindOfType(QualType &type, SourceLocation loc);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
/// \param CD The semantic container for the property
/// \param redeclaredProperty Declaration for property if redeclared
/// in class extension.
/// \param lexicalDC Container for redeclaredProperty.
void ProcessPropertyDecl(ObjCPropertyDecl *property,
ObjCContainerDecl *CD,
ObjCPropertyDecl *redeclaredProperty = nullptr,
ObjCContainerDecl *lexicalDC = nullptr);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
bool *OverridingProperty,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
AttributeList *ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType,
ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo,
DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// \brief Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// \brief The message is sent to 'super'.
ObjCSuperMessage,
/// \brief The message is an instance message.
ObjCInstanceMessage,
/// \brief The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// \brief Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// \brief Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
enum PragmaPackKind {
PPK_Default, // #pragma pack([n])
PPK_Show, // #pragma pack(show), only supported by MSVC.
PPK_Push, // #pragma pack(push, [identifier], [n])
PPK_Pop // #pragma pack(pop, [identifier], [n])
};
enum PragmaMSStructKind {
PMSST_OFF, // #pragms ms_struct off
PMSST_ON // #pragms ms_struct on
};
enum PragmaMSCommentKind {
PCK_Unknown,
PCK_Linker, // #pragma comment(linker, ...)
PCK_Lib, // #pragma comment(lib, ...)
PCK_Compiler, // #pragma comment(compiler, ...)
PCK_ExeStr, // #pragma comment(exestr, ...)
PCK_User // #pragma comment(user, ...)
};
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(PragmaPackKind Kind,
IdentifierInfo *Name,
Expr *Alignment,
SourceLocation PragmaLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
/// ActOnPragmaPackMatrix - Called on well formed \#pragma pack_matrix(...).
void ActOnPragmaPackMatrix(bool bRowMajor, SourceLocation PragmaLoc);
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// \brief Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm37::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm37::StringRef PragmaName);
/// \brief Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// \brief Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT
void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
/// \brief Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// \brief Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// \brief Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// \brief Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex, bool IsPackExpansion);
void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
unsigned SpellingListIndex, bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
unsigned SpellingListIndex);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
Expr *MinBlocks, unsigned SpellingListIndex);
// OpenMP directives and clauses.
private:
void *VarDataSharingAttributesStack;
/// \brief Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
OpenMPClauseKind CKind);
public:
/// \brief Check if the specified variable is used in a private clause in
/// Checks if the specified variable is used in one of the private
/// clauses in OpenMP constructs.
bool IsOpenMPCapturedVar(VarDecl *VD);
/// OpenMP constructs.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// \brief Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// \brief Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// \brief End analysis of clauses.
void EndOpenMPClause();
/// \brief Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// \brief Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// \brief Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id);
/// \brief Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// \brief End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm37::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm37::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm37::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm37::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm37::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// \brief Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
unsigned Argument, Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ArgumentLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation KindLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'ordered' clause.
OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
SourceLocation DepLoc);
/// \brief Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'reduction' clause.
OMPClause *
ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc,
SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId);
/// \brief Called on well-formed 'linear' clause.
OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
Expr *Step,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief The kind of conversion being performed.
enum CheckedConversionKind {
/// \brief An implicit conversion.
CCK_ImplicitConversion,
/// \brief A C-style cast.
CCK_CStyleCast,
/// \brief A functional-style cast.
CCK_FunctionalCast,
/// \brief A cast other than a C-style cast.
CCK_OtherCast
};
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
bool IsCompAssign = false);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointer - The assignment is between two pointers types which
/// point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm37::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and prepare for a conversion of the
/// RHS to the LHS type.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind);
// CheckSingleAssignmentConstraints - Currently used by
// CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
// this routine performs the default function/array converions.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
bool Diagnose = true,
bool DiagnoseCFAudited = false);
// \brief If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
bool IsCompAssign = false);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
bool isRelational);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool *NonStandardCompositeType = nullptr);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool *NonStandardCompositeType = nullptr) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
NonStandardCompositeType);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool isRelational);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible_With_Added_Qualification - The two types are
/// reference-compatible with added qualification, meaning that
/// they are reference-compatible and the qualifiers on T1 (cv1)
/// are greater than the qualifiers on T2 (cv2).
Ref_Compatible_With_Added_Qualification,
/// Ref_Compatible - The two types are reference-compatible and
/// have equivalent qualifiers (cv1 == cv2).
Ref_Compatible
};
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
QualType T1, QualType T2,
bool &DerivedToBase,
bool &ObjCConversion,
bool &ObjCLifetimeConversion);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// \brief Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// \brief Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged };
/// \brief Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds.
ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage,
SourceLocation lbrac, SourceLocation rbrac,
SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// \brief Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage, bool isSuperMessage);
/// \brief If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// \brief Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// \brief Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm37::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// \brief Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm37::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm37::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm37::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \name Code completion
//@{
/// \brief Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// \brief Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// \brief Code completion occurs within a class, struct, or union.
PCC_Class,
/// \brief Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// \brief Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// \brief Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// \brief Code completion occurs following one or more template
/// headers.
PCC_Template,
/// \brief Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// \brief Code completion occurs within an expression.
PCC_Expression,
/// \brief Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// \brief Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// \brief Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// \brief Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// \brief Code completion occurs where only a type is permitted.
PCC_Type,
/// \brief Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// \brief Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool IsArrow);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteCase(Scope *S);
void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
ArrayRef<Expr *> Args);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteReturn(Scope *S);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
unsigned NumProtocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S,
bool IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteNaturalLanguage();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
// HLSL Change Starts - checking array subscript access to vector or matrix member
void CheckHLSLArrayAccess(const Expr *expr);
// HLSL Change ends
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
ArrayRef<const Expr *> Args, bool IsMemberFunction,
SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(CallExpr *TheCall);
bool SemaBuiltinVAStartARM(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm37::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinCpuSupports(CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
ArrayRef<const Expr *> Args, bool HasVAListArg,
unsigned format_idx, unsigned firstDataArg,
FormatStringType Type, bool inFunctionCall,
VariadicCallType CallType,
llvm37::SmallBitVector &CheckedVarArgs);
bool FormatStringHasSArg(const StringLiteral *FExpr);
bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm37::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm37::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl,
IdentifierInfo *FnInfo);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// \brief Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// \brief Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// \brief Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// \brief Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// \brief A map from magic value to type information.
std::unique_ptr<llvm37::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// \brief Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const Expr * const *ExprArgs);
/// \brief The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
// HLSL Change Starts
bool DiagnoseHLSLDecl(Declarator& D, DeclContext* DC, Expr *BitWidth, TypeSourceInfo* TInfo, bool isParameter);
bool DiagnoseHLSLLookup(const LookupResult &R);
void TransferUnusualAttributes(Declarator& D, NamedDecl* NewDecl);
// HLSL Change Ends
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// \brief Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
AvailabilityResult getCurContextAvailability() const;
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// \brief To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
};
/// \brief RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
public:
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
IsDecltype);
}
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext,
Sema::ReuseLambdaContextDecl,
IsDecltype);
}
~EnterExpressionEvaluationContext() {
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// \brief Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// \brief The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
#endif
|
nested_thread_num.c | // RUN: %libomp-compile-and-run | FileCheck %s
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck --check-prefix=THREADS %s
// REQUIRES: ompt
// UNSUPPORTE: gcc-4, gcc-5, gcc-6, gcc-7
#define TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN
#include "callback.h"
#include <omp.h>
#include <unistd.h>
int main() {
int condition = 0;
omp_set_nested(1);
print_frame(0);
#pragma omp parallel num_threads(2)
{
print_frame_from_outlined_fn(1);
print_ids(0);
print_ids(1);
print_frame(0);
// get all implicit task events before starting nested:
#pragma omp barrier
#pragma omp parallel num_threads(2)
{
print_frame_from_outlined_fn(1);
print_ids(0);
print_ids(1);
print_ids(2);
print_frame(0);
OMPT_SIGNAL(condition);
OMPT_WAIT(condition, 4);
#pragma omp barrier
print_fuzzy_address(1);
print_ids(0);
}
print_fuzzy_address(2);
print_ids(0);
}
print_fuzzy_address(3);
return 0;
}
// Check if libomp supports the callbacks for this test.
// CHECK-NOT: {{^}}0: Could not register callback
// CHECK: 0: NULL_POINTER=[[NULL:.*$]]
// make sure initial data pointers are null
// CHECK-NOT: 0: parallel_data initially not null
// CHECK-NOT: 0: task_data initially not null
// CHECK-NOT: 0: thread_data initially not null
// CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin:
// CHECK-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]],
// CHECK-SAME: parent_task_frame.exit=[[NULL]],
// CHECK-SAME: parent_task_frame.reenter={{0x[0-f]+}},
// CHECK-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]],
// CHECK-SAME: requested_team_size=2,
// CHECK-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}},
// CHECK-SAME: invoker=[[PARALLEL_INVOKER:[0-9]+]]
// CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin:
// CHECK-DAG: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end:
// Note that we cannot ensure that the worker threads have already called
// barrier_end and implicit_task_end before parallel_end!
// CHECK-DAG: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin:
// CHECK-DAG: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin:
// CHECK: ompt_event_parallel_end: parallel_id=[[PARALLEL_ID]],
// CHECK-SAME: task_id=[[PARENT_TASK_ID]], invoker=[[PARALLEL_INVOKER]]
// CHECK: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]]
// THREADS: {{^}}0: NULL_POINTER=[[NULL:.*$]]
// THREADS: __builtin_frame_address(0)=[[MAIN_REENTER:0x[0-f]+]]
// THREADS: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin:
// THREADS-SAME: parent_task_id=[[PARENT_TASK_ID:[0-9]+]],
// THREADS-SAME: parent_task_frame.exit=[[NULL]],
// THREADS-SAME: parent_task_frame.reenter=[[MAIN_REENTER]],
// THREADS-SAME: parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=2,
// THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}},
// THREADS-SAME: invoker=[[PARALLEL_INVOKER:[0-9]+]]
// nested parallel masters
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]],
// THREADS-SAME: team_size=2, thread_num=0
// THREADS: __builtin_frame_address({{.}})=[[EXIT:0x[0-f]+]]
// THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]],
// THREADS-SAME: reenter_frame=[[NULL]],
// THREADS-SAME: thread_num=0
// THREADS: {{^}}[[MASTER_ID]]: task level 1:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID:[0-9]+]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]],
// THREADS-SAME: reenter_frame=[[MAIN_REENTER]]
// THREADS: __builtin_frame_address(0)=[[REENTER:0x[0-f]+]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_begin:
// THREADS-SAME: parent_task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: parent_task_frame.exit=[[EXIT]],
// THREADS-SAME: parent_task_frame.reenter=[[REENTER]],
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]],
// THREADS-SAME: requested_team_size=2,
// THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}},
// THREADS-SAME: invoker=[[PARALLEL_INVOKER]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID:[0-9]+]], team_size=2,
// THREADS-SAME: thread_num=0
// THREADS: __builtin_frame_address({{.}})=[[NESTED_EXIT:0x[0-f]+]]
// THREADS: {{^}}[[MASTER_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=[[NULL]],
// THREADS-SAME: thread_num=0
// THREADS: {{^}}[[MASTER_ID]]: task level 1: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]],
// THREADS-SAME: reenter_frame=[[REENTER]]
// THREADS: {{^}}[[MASTER_ID]]: task level 2:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]], exit_frame=[[NULL]],
// THREADS-SAME: reenter_frame=[[MAIN_REENTER]]
// THREADS: __builtin_frame_address(0)=[[NESTED_REENTER:0x[0-f]+]]
// THREADS-NOT: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end
// explicit barrier
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: codeptr_ra=[[BARRIER_RETURN_ADDRESS:0x[0-f]+]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=[[NESTED_REENTER]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[BARRIER_RETURN_ADDRESS]]
// THREADS: {{^}}[[MASTER_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: exit_frame=[[NESTED_EXIT]], reenter_frame=[[NULL]]
// implicit barrier
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: exit_frame=[[NULL]], reenter_frame=[[NULL]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_end:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: invoker=[[PARALLEL_INVOKER]],
// THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[NESTED_RETURN_ADDRESS]]
// THREADS-NOT: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end
// THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[EXIT]],
// THREADS-SAME: reenter_frame=[[NULL]]
// implicit barrier
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], exit_frame=[[NULL]],
// THREADS-SAME: reenter_frame=[[NULL]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[MASTER_ID]]: ompt_event_parallel_end:
// THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]],
// THREADS-SAME: invoker=[[PARALLEL_INVOKER]],
// THREADS-SAME: codeptr_ra=[[RETURN_ADDRESS]]{{[0-f][0-f]}}
// THREADS: {{^}}[[MASTER_ID]]: fuzzy_address={{.*}}[[RETURN_ADDRESS]]
// Worker of first nesting level
// THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]], team_size=2,
// THREADS-SAME: thread_num=[[OUTER_THREADNUM:[0-9]+]]
// THREADS: {{^}}[[THREAD_ID]]: task level 0: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: thread_num=[[OUTER_THREADNUM]]
// THREADS: {{^}}[[THREAD_ID]]: task level 1:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_parallel_begin:
// THREADS-SAME: parent_task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: parent_task_frame.exit={{0x[0-f]+}},
// THREADS-SAME: parent_task_frame.reenter={{0x[0-f]+}},
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]], requested_team_size=2,
// THREADS-SAME: codeptr_ra=[[NESTED_RETURN_ADDRESS]]{{[0-f][0-f]}},
// THREADS-SAME: invoker=[[PARALLEL_INVOKER]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID:[0-9]+]], team_size=2,
// THREADS-SAME: thread_num=[[INNER_THREADNUM:[0-9]+]]
// THREADS: {{^}}[[THREAD_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]],
// THREADS-SAME: thread_num=[[INNER_THREADNUM]]
// THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id=[[PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]],
// THREADS-SAME: thread_num=[[OUTER_THREADNUM]]
// THREADS: {{^}}[[THREAD_ID]]: task level 2:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]]
// THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[NESTED_IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[NESTED_IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_parallel_end:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]], invoker=[[PARALLEL_INVOKER]]
// THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// nested parallel worker threads
// THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// THREADS-SAME: thread_num=[[THREADNUM:[0-9]+]]
// THREADS: {{^}}[[THREAD_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]]
// THREADS-SAME: thread_num=[[THREADNUM]]
// can't reliably tell which parallel region is the parent...
// THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id={{[0-9]+}},
// THREADS-SAME: task_id={{[0-9]+}}
// THREADS-SAME: thread_num={{[01]}}
// THREADS: {{^}}[[THREAD_ID]]: task level 2:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]]
// THREADS-SAME: thread_num=0
// THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// other nested parallel worker threads
// THREADS: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_implicit_task_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID:[0-9]+]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID:[0-9]+]]
// THREADS-SAME: thread_num=[[THREADNUM:[0-9]+]]
// THREADS: {{^}}[[THREAD_ID]]: task level 0:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]]
// THREADS-SAME: thread_num=[[THREADNUM]]
// can't reliably tell which parallel region is the parent...
// THREADS: {{^}}[[THREAD_ID]]: task level 1: parallel_id={{[0-9]+}},
// THREADS-SAME: task_id={{[0-9]+}}
// THREADS-SAME: thread_num={{[01]}}
// THREADS: {{^}}[[THREAD_ID]]: task level 2:
// THREADS-SAME: parallel_id=[[IMPLICIT_PARALLEL_ID]],
// THREADS-SAME: task_id=[[PARENT_TASK_ID]]
// THREADS-SAME: thread_num=0
// THREADS-NOT: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_begin:
// THREADS-SAME: parallel_id=[[NESTED_PARALLEL_ID]],
// THREADS-SAME: task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_barrier_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
// THREADS: {{^}}[[THREAD_ID]]: ompt_event_implicit_task_end:
// THREADS-SAME: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]]
|
ccl_cls.c | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <gsl/gsl_errno.h>
#include <gsl/gsl_integration.h>
#include "ccl.h"
typedef struct{
double l;
ccl_cosmology *cosmo;
ccl_cl_tracer_collection_t *trc1;
ccl_cl_tracer_collection_t *trc2;
ccl_f2d_t *psp;
int *status;
} integ_cl_par;
typedef struct{
int chipow;
double l1;
double l2;
ccl_cosmology *cosmo;
ccl_cl_tracer_collection_t *trc1;
ccl_cl_tracer_collection_t *trc2;
ccl_cl_tracer_collection_t *trc3;
ccl_cl_tracer_collection_t *trc4;
ccl_f3d_t *tsp;
ccl_f1d_t *ker_extra;
ccl_a_finder *finda;
int *status;
} integ_cov_par;
static void update_chi_limits(ccl_cl_tracer_collection_t *trc,
double *chimin, double *chimax,
int is_union)
{
int itr;
double chimin_h=1E15;
double chimax_h=-1E15;
for(itr=0; itr < trc->n_tracers; itr++) {
if (trc->ts[itr]->chi_min < chimin_h)
chimin_h = trc->ts[itr]->chi_min;
if (trc->ts[itr]->chi_max > chimax_h)
chimax_h = trc->ts[itr]->chi_max;
}
if(is_union) {
if(chimin_h < *chimin)
*chimin = chimin_h;
if(chimax_h > *chimax)
*chimax = chimax_h;
}
else {
if(chimin_h > *chimin)
*chimin = chimin_h;
if(chimax_h < *chimax)
*chimax = chimax_h;
}
}
static void get_k_interval(ccl_cosmology *cosmo,
ccl_cl_tracer_collection_t *trc1,
ccl_cl_tracer_collection_t *trc2,
double l, double *lkmin, double *lkmax) {
int itr;
// Loop through all tracers and find distance bounds
double chi_min1 = 1E15;
double chi_max1 = -1E15;
for (itr=0; itr < trc1->n_tracers; itr++) {
if (trc1->ts[itr]->chi_min < chi_min1)
chi_min1 = trc1->ts[itr]->chi_min;
if (trc1->ts[itr]->chi_max > chi_max1)
chi_max1 = trc1->ts[itr]->chi_max;
}
double chi_min2 = 1E15;
double chi_max2 = -1E15;
for (itr=0; itr < trc2->n_tracers; itr++) {
if (trc2->ts[itr]->chi_min < chi_min2)
chi_min2 = trc2->ts[itr]->chi_min;
if (trc2->ts[itr]->chi_max > chi_max2)
chi_max2 = trc2->ts[itr]->chi_max;
}
// Find maximum of minima and minimum of maxima
// (i.e. edges where the product of both kernels will have support).
double chi_min = fmax(chi_min1, chi_min2);
double chi_max = fmin(chi_max1, chi_max2);
if (chi_min <= 0)
chi_min = 0.5*(l+0.5)/cosmo->spline_params.K_MAX;
// Don't go beyond kmax
*lkmax = log(fmin(cosmo->spline_params.K_MAX, 2*(l+0.5)/chi_min));
*lkmin = log(fmax(cosmo->spline_params.K_MIN, (l+0.5)/chi_max));
}
static double transfer_limber_single(ccl_cl_tracer_t *tr, double l, double lk,
double k, double chi_l, double a_l,
ccl_cosmology *cosmo, ccl_f2d_t *psp,
int ignore_jbes_deriv,
int *status) {
double dd = 0;
// Kernel and transfer evaluated at chi_l
double w = ccl_cl_tracer_t_get_kernel(tr, chi_l, status);
double t = ccl_cl_tracer_t_get_transfer(tr, lk,a_l, status);
double fl = ccl_cl_tracer_t_get_f_ell(tr, l, status);
if (tr->der_bessel < 1) { //We don't need l+1
dd = w*t;
if (tr->der_bessel == -1) { //If we divide by (chi*k)^2
double lp1h = l+0.5;
dd /= (lp1h*lp1h);
}
}
else { // We will need l+1
if(ignore_jbes_deriv)
dd = 0;
else {
// Compute chi_{l+1} and a_{l+1}
double lp1h = l+0.5;
double lp3h = l+1.5;
double chi_lp = lp3h/k;
double a_lp = ccl_scale_factor_of_chi(cosmo, chi_lp, status);
// Compute power spectrum ratio there
double pk_ratio = fabs(ccl_f2d_t_eval(psp, lk, a_lp, cosmo, status) /
ccl_f2d_t_eval(psp, lk, a_l, cosmo, status));
// Compute kernel and trasfer at chi_{l+1}
double w_p = ccl_cl_tracer_t_get_kernel(tr, chi_lp, status);
double t_p = ccl_cl_tracer_t_get_transfer(tr, lk,a_lp, status);
// sqrt(2l+1/2l+3)
double sqell = sqrt(lp1h*pk_ratio/lp3h);
if (tr->der_bessel == 1)
dd = l*w*t/lp1h-sqell*w_p*t_p;
else //we assume der_bessel=2 here to avoid extra if clause
dd = sqell*2*w_p*t_p/lp3h - (0.25+2*l)*w*t/(lp1h*lp1h);
}
}
return dd*fl;
}
static double transfer_limber_wrap(double l,double lk, double k, double chi,
double a, ccl_cl_tracer_collection_t *trc,
ccl_cosmology *cosmo,ccl_f2d_t *psp,
int ignore_jbes_deriv, int *status) {
int itr;
double transfer = 0;
for (itr=0; itr < trc->n_tracers; itr++) {
transfer += transfer_limber_single(
trc->ts[itr], l, lk, k, chi, a, cosmo, psp, ignore_jbes_deriv, status);
if (*status != 0)
return -1;
}
return transfer;
}
static double cl_integrand(double lk, void *params) {
double d1, d2;
integ_cl_par *p = (integ_cl_par *)params;
double k = exp(lk);
double chi = (p->l+0.5)/k;
double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status);
d1 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc1,
p->cosmo, p->psp, 0, p->status);
if (d1 == 0)
return 0;
d2 = transfer_limber_wrap(p->l, lk, k, chi, a, p->trc2,
p->cosmo, p->psp, 0, p->status);
if (d2 == 0)
return 0;
double pk = ccl_f2d_t_eval(p->psp, lk, a, p->cosmo, p->status);
return k*pk*d1*d2;
}
static void integ_cls_limber_spline(ccl_cosmology *cosmo,
integ_cl_par *ipar,
double lkmin, double lkmax,
double *result, int *status) {
int ik;
int nk = (int)(fmax((lkmax - lkmin) / cosmo->spline_params.DLOGK_INTEGRATION + 0.5,
1))+1;
double *fk_arr = NULL;
double *lk_arr = NULL;
lk_arr = ccl_linear_spacing(lkmin, lkmax, nk);
if(lk_arr == NULL)
*status = CCL_ERROR_LOGSPACE;
if(*status == 0) {
fk_arr = malloc(nk * sizeof(double));
if(fk_arr == NULL)
*status = CCL_ERROR_MEMORY;
}
if(*status == 0) {
for(ik=0; ik<nk; ik++) {
fk_arr[ik] = cl_integrand(lk_arr[ik], ipar);
if(*(ipar->status)) {
*status = *(ipar->status);
break;
}
}
}
if(*status == 0) {
ccl_integ_spline(1, nk, lk_arr, &fk_arr,
1, -1, result, gsl_interp_akima,
status);
}
free(fk_arr);
free(lk_arr);
}
static void integ_cls_limber_qag_quad(ccl_cosmology *cosmo,
gsl_function *F,
double lkmin, double lkmax,
gsl_integration_workspace *w,
double *result, double *eresult,
int *status) {
int gslstatus;
size_t nevals;
gsl_integration_cquad_workspace *w_cquad = NULL;
// Integrate
gslstatus = gsl_integration_qag(F, lkmin, lkmax, 0,
cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,
cosmo->gsl_params.N_ITERATION,
cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,
w, result, eresult);
// Test if a round-off error occured in the evaluation of the integral
// If so, try another integration function, more robust but potentially slower
if (gslstatus == GSL_EROUND) {
ccl_raise_gsl_warning(gslstatus,
"ccl_cls.c: integ_cls_limber_qag_quad(): "
"Default GSL integration failure, attempting backup method.");
w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if (w_cquad == NULL)
*status = CCL_ERROR_MEMORY;
if (*status == 0) {
nevals = 0;
gslstatus = gsl_integration_cquad(F, lkmin, lkmax, 0,
cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,
w_cquad, result, eresult, &nevals);
}
}
gsl_integration_cquad_workspace_free(w_cquad);
if(*status == 0)
*status = gslstatus;
}
void ccl_angular_cls_limber(ccl_cosmology *cosmo,
ccl_cl_tracer_collection_t *trc1,
ccl_cl_tracer_collection_t *trc2,
ccl_f2d_t *psp,
int nl_out, double *l_out, double *cl_out,
ccl_integration_t integration_method,
int *status) {
// make sure to init core things for safety
if (!cosmo->computed_distances) {
*status = CCL_ERROR_DISTANCES_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_cls.c: ccl_angular_cls_limber(): distance splines have not been precomputed!");
return;
}
#pragma omp parallel shared(cosmo, trc1, trc2, l_out, cl_out, \
nl_out, status, psp, integration_method) \
default(none)
{
int clastatus, lind;
integ_cl_par ipar;
gsl_integration_workspace *w = NULL;
int local_status = *status;
gsl_function F;
double lkmin, lkmax, l, result, eresult;
if (local_status == 0) {
// Set up integrating function parameters
ipar.cosmo = cosmo;
ipar.trc1 = trc1;
ipar.trc2 = trc2;
ipar.psp = psp;
ipar.status = &clastatus;
}
if(integration_method == ccl_integration_qag_quad) {
if (local_status == 0) {
w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if (w == NULL) {
local_status = CCL_ERROR_MEMORY;
}
}
if (local_status == 0) {
// Set up integrating function
F.function = &cl_integrand;
F.params = &ipar;
}
}
#pragma omp for schedule(dynamic)
for (lind=0; lind < nl_out; ++lind) {
if (local_status == 0) {
l = l_out[lind];
clastatus = 0;
ipar.l = l;
// Get integration limits
get_k_interval(cosmo, trc1, trc2, l, &lkmin, &lkmax);
// Integrate
if(integration_method == ccl_integration_qag_quad) {
integ_cls_limber_qag_quad(cosmo, &F, lkmin, lkmax, w,
&result, &eresult, &local_status);
}
else if(integration_method == ccl_integration_spline) {
integ_cls_limber_spline(cosmo, &ipar, lkmin, lkmax,
&result, &local_status);
}
else
local_status = CCL_ERROR_NOT_IMPLEMENTED;
if ((*ipar.status == 0) && (local_status == 0)) {
cl_out[lind] = result / (l+0.5);
}
else {
ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cls_limber():");
cl_out[lind] = NAN;
local_status = CCL_ERROR_INTEG;
}
}
}
gsl_integration_workspace_free(w);
if (local_status) {
#pragma omp atomic write
*status = local_status;
}
}
if (*status) {
ccl_cosmology_set_status_message(
cosmo,
"ccl_cls.c: ccl_angular_cls_limber(); integration error\n");
}
}
void ccl_angular_cls_nonlimber(ccl_cosmology *cosmo,
ccl_cl_tracer_collection_t *trc1,
ccl_cl_tracer_collection_t *trc2,
ccl_f2d_t *psp,
int nl_out, int *l_out, double *cl_out,
int *status) {
*status = CCL_ERROR_INCONSISTENT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_cls.c: ccl_angular_cls_nonlimber(); non-Limber integrator not implemented yet\n");
}
static double cov_integrand(double chi, void *params)
{
double d1, d2, d3, d4, tkk, ker=1;
integ_cov_par *p = (integ_cov_par *)params;
double k1=(p->l1+0.5)/chi;
double k2=(p->l2+0.5)/chi;
double lk1=log(k1);
double lk2=log(k2);
double a = ccl_scale_factor_of_chi(p->cosmo, chi, p->status);
d1 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc1,
p->cosmo, NULL, 1, p->status);
if (d1 == 0)
return 0;
d2 = transfer_limber_wrap(p->l1, lk1, k1, chi, a, p->trc2,
p->cosmo, NULL, 1, p->status);
if (d2 == 0)
return 0;
d3 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc3,
p->cosmo, NULL, 1, p->status);
if (d3 == 0)
return 0;
d4 = transfer_limber_wrap(p->l2, lk2, k2, chi, a, p->trc4,
p->cosmo, NULL, 1, p->status);
if (d4 == 0)
return 0;
tkk = ccl_f3d_t_eval(p->tsp, lk1, lk2, a,
p->finda, p->cosmo, p->status);
if(p->ker_extra!=NULL)
ker = ccl_f1d_t_eval(p->ker_extra, a);
return d1*d2*d3*d4*tkk*ker/pow(chi, p->chipow);
}
static void integ_cov_limber_spline(ccl_cosmology *cosmo,
integ_cov_par *ipar,
double chimin, double chimax,
double *result, int *status)
{
int ichi;
int nchi = (int)(fmax((chimax - chimin) / cosmo->spline_params.DCHI_INTEGRATION + 0.5,
1))+1;
double *fchi_arr = NULL;
double *chi_arr = NULL;
chi_arr = ccl_linear_spacing(chimin, chimax, nchi);
if(chi_arr == NULL)
*status = CCL_ERROR_LOGSPACE;
if(*status == 0) {
fchi_arr = malloc(nchi * sizeof(double));
if(fchi_arr == NULL)
*status = CCL_ERROR_MEMORY;
}
if(*status == 0) {
for(ichi=0; ichi<nchi; ichi++) {
fchi_arr[ichi] = cov_integrand(chi_arr[ichi], ipar);
if(*(ipar->status)) {
*status = *(ipar->status);
break;
}
}
}
if(*status == 0) {
ccl_integ_spline(1, nchi, chi_arr, &fchi_arr,
1, -1, result, gsl_interp_akima,
status);
}
free(fchi_arr);
free(chi_arr);
}
static void integ_cov_limber_qag_quad(ccl_cosmology *cosmo,
gsl_function *F,
double chimin, double chimax,
gsl_integration_workspace *w,
double *result, double *eresult,
int *status) {
int gslstatus;
size_t nevals;
gsl_integration_cquad_workspace *w_cquad = NULL;
// Integrate
gslstatus = gsl_integration_qag(F, chimin, chimax, 0,
cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,
cosmo->gsl_params.N_ITERATION,
cosmo->gsl_params.INTEGRATION_LIMBER_GAUSS_KRONROD_POINTS,
w, result, eresult);
// Test if a round-off error occured in the evaluation of the integral
// If so, try another integration function, more robust but potentially slower
if (gslstatus == GSL_EROUND) {
ccl_raise_gsl_warning(gslstatus,
"ccl_cls.c: ccl_angular_cov_limber(): "
"Default GSL integration failure, attempting backup method.");
w_cquad = gsl_integration_cquad_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if (w_cquad == NULL)
*status = CCL_ERROR_MEMORY;
if (*status == 0) {
nevals = 0;
gslstatus = gsl_integration_cquad(F, chimin, chimax, 0,
cosmo->gsl_params.INTEGRATION_LIMBER_EPSREL,
w_cquad, result, eresult, &nevals);
}
}
gsl_integration_cquad_workspace_free(w_cquad);
if(*status == 0)
*status = gslstatus;
}
void ccl_angular_cl_covariance(ccl_cosmology *cosmo,
ccl_cl_tracer_collection_t *trc1,
ccl_cl_tracer_collection_t *trc2,
ccl_cl_tracer_collection_t *trc3,
ccl_cl_tracer_collection_t *trc4,
ccl_f3d_t *tsp,
int nl1_out, double *l1_out,
int nl2_out, double *l2_out,
double *cov_out,
ccl_integration_t integration_method,
int chi_exponent, ccl_f1d_t *kernel_extra,
double prefactor_extra, int *status)
{
if(!cosmo->computed_distances) {
*status = CCL_ERROR_DISTANCES_INIT;
ccl_cosmology_set_status_message(
cosmo,
"ccl_cls.c: ccl_angular_cl_limber(): distance splines have not been precomputed!");
return;
}
#pragma omp parallel shared(cosmo, trc1, trc2, trc3, trc4, tsp, \
nl1_out, l1_out, nl2_out, l2_out, cov_out, \
integration_method, chi_exponent, \
kernel_extra, prefactor_extra, status) \
default(none)
{
int clastatus, lind1,lind2;
integ_cov_par ipar;
gsl_integration_workspace *w = NULL;
int local_status = *status;
gsl_function F;
double chimin, chimax;
double l1, l2, result, eresult;
ccl_a_finder *finda = ccl_a_finder_new_from_f3d(tsp);
// Find integration limits
chimin = 1E15;
chimax = -1E15;
update_chi_limits(trc1, &chimin, &chimax, 1);
update_chi_limits(trc2, &chimin, &chimax, 0);
update_chi_limits(trc3, &chimin, &chimax, 0);
update_chi_limits(trc4, &chimin, &chimax, 0);
if (local_status == 0) {
// Set up integrating function parameters
ipar.cosmo = cosmo;
ipar.trc1 = trc1;
ipar.trc2 = trc2;
ipar.trc3 = trc3;
ipar.trc4 = trc4;
ipar.tsp = tsp;
ipar.ker_extra = kernel_extra;
ipar.finda = finda;
ipar.status = &clastatus;
ipar.chipow = chi_exponent;
}
if(integration_method == ccl_integration_qag_quad) {
if (local_status == 0) {
w = gsl_integration_workspace_alloc(cosmo->gsl_params.N_ITERATION);
if (w == NULL) {
local_status = CCL_ERROR_MEMORY;
}
}
if (local_status == 0) {
// Set up integrating function
F.function = &cov_integrand;
F.params = &ipar;
}
}
#pragma omp for schedule(dynamic)
for (lind1=0; lind1 < nl1_out; ++lind1) {
l1 = l1_out[lind1];
ipar.l1 = l1;
for (lind2=0; lind2 < nl2_out; ++lind2) {
if (local_status == 0) {
l2 = l2_out[lind2];
clastatus = 0;
ipar.l2 = l2;
// Integrate
if(integration_method == ccl_integration_qag_quad) {
integ_cov_limber_qag_quad(cosmo, &F, chimin, chimax, w,
&result, &eresult, &local_status);
}
else if(integration_method == ccl_integration_spline) {
integ_cov_limber_spline(cosmo, &ipar, chimin, chimax,
&result, &local_status);
}
else
local_status = CCL_ERROR_NOT_IMPLEMENTED;
if ((*ipar.status == 0) && (local_status == 0)) {
cov_out[lind1+nl1_out*lind2] = result * prefactor_extra;
}
else {
ccl_raise_gsl_warning(local_status, "ccl_cls.c: ccl_angular_cov_limber():");
cov_out[lind1+nl1_out*lind2] = NAN;
local_status = CCL_ERROR_INTEG;
}
}
}
}
gsl_integration_workspace_free(w);
if (local_status) {
#pragma omp atomic write
*status = local_status;
}
ccl_a_finder_free(finda);
}
if (*status) {
ccl_cosmology_set_status_message(
cosmo,
"ccl_cls.c: ccl_angular_cov_limber(); integration error\n");
}
}
|
convolution_sgemm_pack1to8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void im2col_sgemm_pack1to8_avx(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
// Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator);
const int size = bottom_im2col.w;
const int maxk = bottom_im2col.h;
const int inch = bottom_im2col.c;
const int outch = top_blob.c;
const float* bias = _bias;
// permute
Mat tmp;
if (size >= 8)
tmp.create(8 * maxk, inch, size / 8 + (size % 8) / 4 + size % 4, 4u, 1, opt.workspace_allocator);
else if (size >= 4)
tmp.create(4 * maxk, inch, size / 4 + size % 4, 4u, 1, opt.workspace_allocator);
else
tmp.create(maxk, inch, size, 4u, 1, opt.workspace_allocator);
{
int nn_size = size >> 3;
int remain_size_start = 0;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 8;
float* tmpptr = tmp.channel(i / 8);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
__m256 _r0 = _mm256_loadu_ps(img0);
_mm256_store_ps(tmpptr, _r0);
img0 += size;
tmpptr += 8;
}
}
}
remain_size_start += nn_size << 3;
nn_size = (size - remain_size_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii = 0; ii < nn_size; ii++)
{
int i = remain_size_start + ii * 4;
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
__m128 _r0 = _mm_loadu_ps(img0);
_mm_store_ps(tmpptr, _r0);
img0 += size;
tmpptr += 4;
}
}
}
remain_size_start += nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i = remain_size_start; i < size; i++)
{
float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
for (int q = 0; q < inch; q++)
{
const float* img0 = (const float*)bottom_im2col.channel(q) + i;
for (int k = 0; k < maxk; k++)
{
tmpptr[0] = img0[0];
img0 += size;
tmpptr += 1;
}
}
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* outptr0 = top_blob.channel(p);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + p * 8 : zeros;
int i = 0;
for (; i + 7 < size; i += 8)
{
const float* tmpptr = tmp.channel(i / 8);
const float* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
__m256 _sum0 = _mm256_loadu_ps(biasptr);
__m256 _sum1 = _sum0;
__m256 _sum2 = _sum0;
__m256 _sum3 = _sum0;
__m256 _sum4 = _sum0;
__m256 _sum5 = _sum0;
__m256 _sum6 = _sum0;
__m256 _sum7 = _sum0;
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(kptr0);
__m256 _val0 = _mm256_broadcast_ss(tmpptr);
__m256 _val1 = _mm256_broadcast_ss(tmpptr + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(tmpptr + 2);
__m256 _val3 = _mm256_broadcast_ss(tmpptr + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
__m256 _val4 = _mm256_broadcast_ss(tmpptr + 4);
__m256 _val5 = _mm256_broadcast_ss(tmpptr + 5);
_sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4);
_sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5);
__m256 _val6 = _mm256_broadcast_ss(tmpptr + 6);
__m256 _val7 = _mm256_broadcast_ss(tmpptr + 7);
_sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6);
_sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7);
tmpptr += 8;
kptr0 += 8;
}
_mm256_store_ps(outptr0, _sum0);
_mm256_store_ps(outptr0 + 8, _sum1);
_mm256_store_ps(outptr0 + 8 * 2, _sum2);
_mm256_store_ps(outptr0 + 8 * 3, _sum3);
_mm256_store_ps(outptr0 + 8 * 4, _sum4);
_mm256_store_ps(outptr0 + 8 * 5, _sum5);
_mm256_store_ps(outptr0 + 8 * 6, _sum6);
_mm256_store_ps(outptr0 + 8 * 7, _sum7);
outptr0 += 64;
}
for (; i + 3 < size; i += 4)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4);
const float* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
__m256 _sum0 = _mm256_loadu_ps(biasptr);
__m256 _sum1 = _sum0;
__m256 _sum2 = _sum0;
__m256 _sum3 = _sum0;
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(kptr0);
__m256 _val0 = _mm256_broadcast_ss(tmpptr);
__m256 _val1 = _mm256_broadcast_ss(tmpptr + 1);
__m256 _val2 = _mm256_broadcast_ss(tmpptr + 2);
__m256 _val3 = _mm256_broadcast_ss(tmpptr + 3);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
tmpptr += 4;
kptr0 += 8;
}
_mm256_store_ps(outptr0, _sum0);
_mm256_store_ps(outptr0 + 8, _sum1);
_mm256_store_ps(outptr0 + 16, _sum2);
_mm256_store_ps(outptr0 + 24, _sum3);
outptr0 += 32;
}
for (; i < size; i++)
{
const float* tmpptr = tmp.channel(i / 8 + (i % 8) / 4 + i % 4);
const float* kptr0 = kernel.channel(p);
int nn = inch * maxk; // inch always > 0
__m256 _sum = _mm256_loadu_ps(biasptr);
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(kptr0);
__m256 _val = _mm256_broadcast_ss(tmpptr);
_sum = _mm256_comp_fmadd_ps(_w0, _val, _sum);
tmpptr += 1;
kptr0 += 8;
}
_mm256_store_ps(outptr0, _sum);
outptr0 += 8;
}
}
}
static void convolution_im2col_sgemm_transform_kernel_pack1to8_avx(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h)
{
const int maxk = kernel_w * kernel_h;
// interleave
// src = maxk-inch-outch
// dst = 8b-4a-maxk-inch/4a-outch/8b
Mat kernel = _kernel.reshape(maxk, inch, outch);
kernel_tm.create(8 * maxk, inch, outch / 8);
int q = 0;
for (; q + 7 < outch; q += 8)
{
const Mat k0 = kernel.channel(q);
const Mat k1 = kernel.channel(q + 1);
const Mat k2 = kernel.channel(q + 2);
const Mat k3 = kernel.channel(q + 3);
const Mat k4 = kernel.channel(q + 4);
const Mat k5 = kernel.channel(q + 5);
const Mat k6 = kernel.channel(q + 6);
const Mat k7 = kernel.channel(q + 7);
float* g00 = kernel_tm.channel(q / 8);
for (int p = 0; p < inch; p++)
{
const float* k00 = k0.row(p);
const float* k10 = k1.row(p);
const float* k20 = k2.row(p);
const float* k30 = k3.row(p);
const float* k40 = k4.row(p);
const float* k50 = k5.row(p);
const float* k60 = k6.row(p);
const float* k70 = k7.row(p);
for (int k = 0; k < maxk; k++)
{
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00 += 8;
}
}
}
}
static void convolution_im2col_sgemm_pack1to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
const int size = outw * outh;
const int maxk = kernel_w * kernel_h;
// im2col
Mat bottom_im2col(size, maxk, inch, 4u, 1, opt.workspace_allocator);
{
const int gap = w * stride_h - outw * stride_w;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < inch; p++)
{
const Mat img = bottom_blob.channel(p);
float* ptr = bottom_im2col.channel(p);
for (int u = 0; u < kernel_h; u++)
{
for (int v = 0; v < kernel_w; v++)
{
const float* sptr = img.row<const float>(dilation_h * u) + dilation_w * v;
for (int i = 0; i < outh; i++)
{
int j = 0;
for (; j + 3 < outw; j += 4)
{
ptr[0] = sptr[0];
ptr[1] = sptr[stride_w];
ptr[2] = sptr[stride_w * 2];
ptr[3] = sptr[stride_w * 3];
sptr += stride_w * 4;
ptr += 4;
}
for (; j + 1 < outw; j += 2)
{
ptr[0] = sptr[0];
ptr[1] = sptr[stride_w];
sptr += stride_w * 2;
ptr += 2;
}
for (; j < outw; j++)
{
ptr[0] = sptr[0];
sptr += stride_w;
ptr += 1;
}
sptr += gap;
}
}
}
}
}
im2col_sgemm_pack1to8_avx(bottom_im2col, top_blob, kernel, _bias, opt);
}
|
diagmm_x_bsr_n_row.c | #include "alphasparse/kernel.h"
#include "alphasparse/util.h"
#include <memory.h>
#include "alphasparse/opt.h"
#ifdef _OPENMP
#include <omp.h>
#endif
alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_BSR *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy)
{
ALPHA_INT block_rowA = mat->rows;
ALPHA_INT rowA = mat->rows * mat->block_size;
ALPHA_INT rowC = mat->rows * mat->block_size;
ALPHA_INT colC = columns;
ALPHA_Number diag[rowA];
memset(diag, '\0', sizeof(ALPHA_Number) * rowA);
ALPHA_INT bs = mat->block_size;
ALPHA_INT num_threads = alpha_get_thread_num();
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT ar = 0; ar < block_rowA; ++ar)
{
for (ALPHA_INT ai = mat->rows_start[ar]; ai < mat->rows_end[ar]; ++ai)
{
if (mat->col_indx[ai] == ar)
{
for(ALPHA_INT block_i = 0; block_i < bs; block_i++)
{
diag[ar*bs+block_i] = mat->values[ai*bs*bs + block_i*bs + block_i];
}
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(num_threads)
#endif
for (ALPHA_INT cr = 0; cr < rowC; ++cr)
for (ALPHA_INT cc = 0; cc < colC; ++cc)
{
ALPHA_Number t1, t2;
alpha_mul(t1, beta, y[index2(cr, cc, ldy)]);
alpha_mul(t2, alpha, diag[cr]);
alpha_mul(t2, t2, x[index2(cr, cc, ldx)]);
alpha_add(y[index2(cr, cc, ldy)], t1, t2);
}
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
barrier.c | #include<stdio.h>
void do_sth()
{
printf ("hello.\n");
}
int main(void)
{
#pragma omp parallel
{
do_sth();
#pragma omp barrier
do_sth();
}
return 0;
}
|
arm_device.h | /* Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ANAKIN_SABER_LITE_CORE_ARM_DEVICE_H
#define ANAKIN_SABER_LITE_CORE_ARM_DEVICE_H
#include <stdio.h>
#include <vector>
#ifdef PLATFORM_ANDROID
#include <sys/syscall.h>
#include <unistd.h>
#define __NCPUBITS__ (8 * sizeof (unsigned long))
#define __CPU_SET(cpu, cpusetp) \
((cpusetp)->mask_bits[(cpu) / __NCPUBITS__] |= (1UL << ((cpu) % __NCPUBITS__)))
#define __CPU_ZERO(cpusetp) \
memset((cpusetp), 0, sizeof(cpu_set_t))
#endif
#if __APPLE__
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/machine.h>
#define __IOS__
#endif
#endif
#ifdef USE_ARM_PLACE
static int arm_get_cpucount() {
#ifdef PLATFORM_ANDROID
// get cpu count from /proc/cpuinfo
FILE* fp = fopen("/proc/cpuinfo", "rb");
if (!fp) {
return 1;
}
int count = 0;
char line[1024];
while (!feof(fp)) {
char* s = fgets(line, 1024, fp);
if (!s) {
break;
}
if (memcmp(line, "processor", 9) == 0) {
count++;
}
}
fclose(fp);
if (count < 1) {
count = 1;
}
return count;
#elif __IOS__
int count = 0;
size_t len = sizeof(count);
sysctlbyname("hw.ncpu", &count, &len, NULL, 0);
if (count < 1) {
count = 1;
}
return count;
#else
return 1;
#endif
}
static int arm_get_meminfo() {
#ifdef PLATFORM_ANDROID
// get cpu count from /proc/cpuinfo
FILE* fp = fopen("/proc/meminfo", "rb");
if (!fp) {
return 1;
}
int memsize = 0;
char line[1024];
while (!feof(fp)) {
char* s = fgets(line, 1024, fp);
if (!s) {
break;
}
sscanf(s, "MemTotal: %d kB", &memsize);
}
fclose(fp);
return memsize;
#elif __IOS__
// to be implemented
return 0;
#endif
}
#ifdef PLATFORM_ANDROID
static int get_max_freq_khz(int cpuid) {
// first try, for all possible cpu
char path[256];
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state",\
cpuid);
FILE* fp = fopen(path, "rb");
if (!fp) {
// second try, for online cpu
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state",\
cpuid);
fp = fopen(path, "rb");
if (!fp) {
// third try, for online cpu
snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq",\
cpuid);
fp = fopen(path, "rb");
if (!fp) {
return -1;
}
int max_freq_khz = -1;
fscanf(fp, "%d", &max_freq_khz);
fclose(fp);
return max_freq_khz;
}
}
int max_freq_khz = 0;
while (!feof(fp)) {
int freq_khz = 0;
int nscan = fscanf(fp, "%d %*d", &freq_khz);
if (nscan != 1) {
break;
}
if (freq_khz > max_freq_khz) {
max_freq_khz = freq_khz;
}
}
fclose(fp);
return max_freq_khz;
}
static int arm_sort_cpuid_by_max_frequency(int cpu_count, std::vector<int>& cpuids, \
std::vector<int>& cpu_freq, std::vector<int>& cluster_ids) {
//const int cpu_count = cpuids.size();
if (cpu_count == 0) {
return 0;
}
//std::vector<int> cpu_max_freq_khz;
cpuids.resize(cpu_count);
cpu_freq.resize(cpu_count);
cluster_ids.resize(cpu_count);
for (int i = 0; i < cpu_count; i++) {
int max_freq_khz = get_max_freq_khz(i);
//printf("%d max freq = %d khz\n", i, max_freq_khz);
cpuids[i] = i;
cpu_freq[i] = max_freq_khz / 1000;
}
// SMP
int mid_max_freq_khz = (cpu_freq.front() + cpu_freq.back()) / 2;
for (int i = 0; i < cpu_count; i++) {
if (cpu_freq[i] >= mid_max_freq_khz) {
cluster_ids[i] = 0;
}
else{
cluster_ids[i] = 1;
}
}
return 0;
}
#endif // __ANDROID__
#ifdef __IOS__
static int sort_cpuid_by_max_frequency(int cpu_count, std::vector<int>& cpuids, \
std::vector<int>& cpu_freq, std::vector<int>& cluster_ids){
if (cpu_count == 0) {
return 0;
}
cpuids.resize(cpu_count);
cpu_freq.resize(cpu_count);
cluster_ids.resize(cpu_count);
for (int i = 0; i < cpu_count; ++i) {
cpuids[i] = i;
cpu_freq[i] = 1000;
cluster_ids[i] = 0;
}
}
#endif
#ifdef PLATFORM_ANDROID
static int set_sched_affinity(const std::vector<int>& cpuids) {
// cpu_set_t definition
// ref http://stackoverflow.com/questions/16319725/android-set-thread-affinity
typedef struct {
unsigned long mask_bits[1024 / __NCPUBITS__];
} cpu_set_t;
// set affinity for thread
pid_t pid = gettid();
cpu_set_t mask;
__CPU_ZERO(&mask);
for (int i = 0; i < (int)cpuids.size(); i++) {
__CPU_SET(cpuids[i], &mask);
}
int syscallret = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallret) {
//LOG(ERROR) << "syscall error " << syscallret;
return -1;
}
return 0;
}
static int set_cpu_affinity(const std::vector<int>& cpuids){
#ifdef USE_OPENMP
int num_threads = cpuids.size();
omp_set_num_threads(num_threads);
std::vector<int> ssarets(num_threads, 0);
#pragma omp parallel for
for (int i = 0; i < num_threads; i++) {
ssarets[i] = set_sched_affinity(cpuids);
}
for (int i = 0; i < num_threads; i++) {
if (ssarets[i] != 0) {
//LOG(ERROR)<<"set cpu affinity failed, cpuID: " << cpuids[i];
return -1;
}
}
#else
std::vector<int> cpuid1;
cpuid1.push_back(cpuids[0]);
int ssaret = set_sched_affinity(cpuid1);
if (ssaret != 0) {
//LOG(ERROR)<<"set cpu affinity failed, cpuID: " << cpuids[0];
return -1;
}
#endif
}
#endif //PLATFORN_ANDROID
#endif //USE_ARM_PLACE
#endif //ANAKIN_SABER_LITE_CORE_ARM_DEVICE_H
|
multigridPara.c | /*
A parallel PDE-solver for Laplace's equation using Jacobi iterative and
multigrid methods
Authors: Andreas Hahr Kardå Chalak
hahr@kth.se kardac@kth.se
arg1: gridSize, the grid size for the coarsest grid, not including boundaries
(the true grid size will be 8xgridSize +7), default = 24
arg2: numIters, nr. Jacobi iterations for coarsest grid, default = 10
arg3: numProc, nr. of threads, default = omp_get_max_threads()
arg4: finIters, nr. Jacobi iterations for finer grids, default = 4
Grids: grid (coarsest),
grid2,
grid3,
grid4 (finest)
*/
#include <stdlib.h>
#include <stdio.h>
#include <omp.h>
void jacobi(double** grid, double** new, int gridSize, int iter);
void restriction(double** fine, double** coarse, int coarseSize);
void interpolation(double** coarse, double** fine, int coarseSize, int fineSize);
void dissBarrier();
void gridprint(double** grid, int gridSize);
int numIters, finIters, numProc;
int* barFlags;
int main(int argc, char *argv[]) {
int gridSize = 24, gridSize2, gridSize3, gridSize4;
double temp, maxdiff, timestamp = 0;
numIters = 10, finIters = 4, numProc = omp_get_max_threads();
switch (argc) {
case 5: finIters = atoi(argv[4]);
case 4: numProc = atoi(argv[3]);
case 3: numIters = atoi(argv[2]);
case 2: gridSize = atoi(argv[1]);
}
gridSize2 = 2*gridSize+1;
gridSize3 = 2*gridSize2+1;
gridSize4 = 2*gridSize3+1;
printf("gridSize: %d\n", gridSize);
printf("numIters: %d\n", numIters);
printf("numThreads: %d\n", numProc);
printf("finIters: %d\n", finIters);
/* allocating memory for barrier flags */
barFlags = (int *) calloc(numProc, sizeof(int));
/* allocating memory for the grids */
/* rows */
double **grid = (double **) malloc((gridSize+2) * sizeof(double*));
double **new = (double **) malloc((gridSize+2) * sizeof(double*));
double **grid2 = (double **) malloc((gridSize2+2) * sizeof(double*));
double **new2 = (double **) malloc((gridSize2+2) * sizeof(double*));
double **grid3 = (double **) malloc((gridSize3+2) * sizeof(double*));
double **new3 = (double **) malloc((gridSize3+2) * sizeof(double*));
double **grid4 = (double **) malloc((gridSize4+2) * sizeof(double*));
double **new4 = (double **) malloc((gridSize4+2) * sizeof(double*));
/* columns */
for(int i = 0; i < gridSize+2; i++) {
grid[i] = (double *) malloc((gridSize+2) * sizeof(double));
new[i] = (double *) malloc((gridSize+2) * sizeof(double));
}
for(int i = 0; i < gridSize2+2; i++) {
grid2[i] = (double *) malloc((gridSize2+2) * sizeof(double));
new2[i] = (double *) malloc((gridSize2+2) * sizeof(double));
}
for(int i = 0; i < gridSize3+2; i++) {
grid3[i] = (double *) malloc((gridSize3+2) * sizeof(double));
new3[i] = (double *) malloc((gridSize3+2) * sizeof(double));
}
for(int i = 0; i < gridSize4+2; i++) {
grid4[i] = (double *) malloc((gridSize4+2) * sizeof(double));
new4[i] = (double *) malloc((gridSize4+2) * sizeof(double));
}
/* set grid boundary points */
for(int i = 0; i < gridSize+2; i++) {
grid[0][i] = 1; // upper boundary
new[0][i] = 1;
grid[gridSize+1][i] = 1; // lower boundary
new[gridSize+1][i] = 1;
grid[i][0] = 1; // left boundary
new[i][0] = 1;
grid[i][gridSize+1] = 1; // right boundary
new[i][gridSize+1] = 1;
}
/* set grid2 boundary points */
for(int i = 0; i < gridSize2+2; i++) {
grid2[0][i] = 1; // upper boundary
new2[0][i] = 1;
grid2[gridSize2+1][i] = 1; // lower boundary
new2[gridSize2+1][i] = 1;
grid2[i][0] = 1; // left boundary
new2[i][0] = 1;
grid2[i][gridSize2+1] = 1; // right boundary
new2[i][gridSize2+1] = 1;
}
/* set grid3 boundary points */
for(int i = 0; i < gridSize3+2; i++) {
grid3[0][i] = 1; // upper boundary
new3[0][i] = 1;
grid3[gridSize3+1][i] = 1; // lower boundary
new3[gridSize3+1][i] = 1;
grid3[i][0] = 1; // left boundary
new3[i][0] = 1;
grid3[i][gridSize3+1] = 1; // right boundary
new3[i][gridSize3+1] = 1;
}
/* set grid4 boundary points */
for(int i = 0; i < gridSize4+2; i++) {
grid4[0][i] = 1; // upper boundary
new4[0][i] = 1;
grid4[gridSize4+1][i] = 1; // lower boundary
new4[gridSize4+1][i] = 1;
grid4[i][0] = 1; // left boundary
new4[i][0] = 1;
grid4[i][gridSize4+1] = 1; // right boundary
new4[i][gridSize4+1] = 1;
}
/* set grid4 interior points */
for(int i = 1; i < gridSize4+1; i++) {
for(int j = 1; j < gridSize4+1; j++) {
grid4[i][j] = 0;
}
}
timestamp -= omp_get_wtime(); // time
/* Full V-cycle */
#pragma omp parallel num_threads(numProc) // fork
{
jacobi(grid4, new4, gridSize4, finIters);
restriction(grid4, grid3, gridSize3); // move to coarser grid
jacobi(grid3, new3, gridSize3, finIters);
restriction(grid3, grid2, gridSize2); // move to coarser grid
jacobi(grid2, new2, gridSize2, finIters);
restriction(grid2, grid, gridSize); // move to coarser grid
jacobi(grid, new, gridSize, numIters); // coarsest grid
interpolation(grid, grid2, gridSize, gridSize2); // move to finer grid
jacobi(grid2, new2, gridSize2, finIters);
interpolation(grid2, grid3, gridSize2, gridSize3); // move to finer grid
jacobi(grid3, new3, gridSize3, finIters);
interpolation(grid3, grid4, gridSize3, gridSize4); // move to finest grid
jacobi(grid4, new4, gridSize4, finIters);
} // join threads
timestamp += omp_get_wtime(); // time
gridprint(grid4, gridSize4); // print grid to filedata.out
/* computation of the maximum difference */
/*maxdiff = 0;
for(int i = 1; i < gridSize4-1; i++) {
for(int j = 1; j < gridSize4-1; j++) {
temp = grid4[i][j] - new4[i][j];
if(temp < 0) temp = -temp;
if(temp > maxdiff) maxdiff = temp;
}
}
printf("Maximum difference: %f\n", maxdiff);*/
printf("Maximum final error: %f\n", 1.0-grid4[(gridSize4+1)/2][(gridSize4+1)/2]);
printf("Jacobi iterations runtime: %f seconds\n", timestamp);
exit(0);
}
void jacobi(double** grid, double** new, int gridSize, int iter) {
for(int k = 0; k < iter; k++) {
#pragma omp for nowait schedule(static)
for(int i = 1; i < gridSize+1; i++) {
for(int j = 1; j < gridSize+1; j++) {
new[i][j] = (grid[i-1][j] // value from left
+ grid[i+1][j] // value from right
+ grid[i][j-1] // value from above
+ grid[i][j+1]) * 0.25; // value from below
}
}
dissBarrier(); // dissemination barrier
#pragma omp for nowait schedule(static)
for(int i = 1; i < gridSize+1; i++) {
for(int j = 1; j < gridSize+1; j++) {
grid[i][j] = (new[i-1][j] // value from left
+ new[i+1][j] // value from right
+ new[i][j-1] // value from above
+ new[i][j+1]) * 0.25; // value from below
}
}
dissBarrier(); // dissemination barrier
}
}
void restriction(double** fine, double** coarse, int coarseSize) {
#pragma omp for nowait schedule(static)
for(int i = 1; i < coarseSize+1; i++) {
int m = i << 1;
for(int j = 1; j < coarseSize+1; j++) {
int n = j << 1;
coarse[i][j] = fine[m][n] * 0.5 +
(fine[m-1][n] + fine[m+1][n] + fine[m][n-1] + fine[m][n+1]) * 0.125;
}
}
dissBarrier();
}
void interpolation(double** coarse, double** fine, int coarseSize, int fineSize) {
/* place coarse grid points on finer grid */
#pragma omp for nowait schedule(static)
for(int i = 1; i < coarseSize+1; i++) {
int m = i << 1;
for(int j = 1; j < coarseSize+1; j++) {
int n = j << 1;
fine[m][n] = coarse[i][j];
}
}
dissBarrier();
/* set fine grid points in columns corresponding to coarser grid */
#pragma omp for nowait schedule(static)
for(int j = 2; j < fineSize; j+=2) {
for(int i = 1; i < fineSize+1; i+=2) {
fine[i][j] = (fine[i-1][j] + fine[i+1][j]) * 0.5;
}
}
dissBarrier();
/* set rest of the points */
#pragma omp for nowait schedule(static)
for(int i = 1; i < fineSize+1; i++) {
for(int j = 1; j < fineSize+1; j+=2) {
fine[i][j] = (fine[i][j-1] + fine[i][j+1]) * 0.5;
}
}
dissBarrier();
}
void dissBarrier() {
int me = omp_get_thread_num();
for(int s = 1; s < numProc; s <<= 1) {
barFlags[me] += 1;
while(barFlags[me] > barFlags[(me+s)%numProc]) {/* busy waiting...*/};
}
}
void gridprint(double** grid, int gridSize) {
FILE *fp;
fp = fopen("filedata.out", "w+");
for(int i = 0; i < gridSize+2; i++) {
for(int j = 0; j < gridSize+2; j++) {
fprintf(fp, "%f ", grid[i][j]);
}
fprintf(fp, "\n");
}
fclose(fp);
}
|
tree.h | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TREE_H_
#define LIGHTGBM_TREE_H_
#include <LightGBM/dataset.h>
#include <LightGBM/meta.h>
#include <string>
#include <map>
#include <memory>
#include <unordered_map>
#include <vector>
namespace LightGBM {
#define kCategoricalMask (1)
#define kDefaultLeftMask (2)
/*!
* \brief Tree model
*/
class Tree {
public:
/*!
* \brief Constructor
* \param max_leaves The number of max leaves
* \param track_branch_features Whether to keep track of ancestors of leaf nodes
* \param is_linear Whether the tree has linear models at each leaf
*/
explicit Tree(int max_leaves, bool track_branch_features, bool is_linear);
/*!
* \brief Constructor, from a string
* \param str Model string
* \param used_len used count of str
*/
Tree(const char* str, size_t* used_len);
~Tree() noexcept = default;
/*!
* \brief Performing a split on tree leaves.
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split
* \param threshold_double Threshold on feature value
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \param missing_type missing type
* \param default_left default direction for missing value
* \return The index of new leaf.
*/
int Split(int leaf, int feature, int real_feature, uint32_t threshold_bin,
double threshold_double, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight,
float gain, MissingType missing_type, bool default_left);
/*!
* \brief Performing a split on tree leaves, with categorical feature
* \param leaf Index of leaf to be split
* \param feature Index of feature; the converted index after removing useless features
* \param real_feature Index of feature, the original index on data
* \param threshold_bin Threshold(bin) of split, use bitset to represent
* \param num_threshold_bin size of threshold_bin
* \param threshold Thresholds of real feature value, use bitset to represent
* \param num_threshold size of threshold
* \param left_value Model Left child output
* \param right_value Model Right child output
* \param left_cnt Count of left child
* \param right_cnt Count of right child
* \param left_weight Weight of left child
* \param right_weight Weight of right child
* \param gain Split gain
* \return The index of new leaf.
*/
int SplitCategorical(int leaf, int feature, int real_feature, const uint32_t* threshold_bin, int num_threshold_bin,
const uint32_t* threshold, int num_threshold, double left_value, double right_value,
int left_cnt, int right_cnt, double left_weight, double right_weight, float gain, MissingType missing_type);
/*! \brief Get the output of one leaf */
inline double LeafOutput(int leaf) const { return leaf_value_[leaf]; }
/*! \brief Set the output of one leaf */
inline void SetLeafOutput(int leaf, double output) {
leaf_value_[leaf] = MaybeRoundToZero(output);
}
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
data_size_t num_data,
double* score) const;
/*!
* \brief Adding prediction value of this tree model to scores
* \param data The dataset
* \param used_data_indices Indices of used data
* \param num_data Number of total data
* \param score Will add prediction to score
*/
void AddPredictionToScore(const Dataset* data,
const data_size_t* used_data_indices,
data_size_t num_data, double* score) const;
/*!
* \brief Get upper bound leaf value of this tree model
*/
double GetUpperBoundValue() const;
/*!
* \brief Get lower bound leaf value of this tree model
*/
double GetLowerBoundValue() const;
/*!
* \brief Prediction on one record
* \param feature_values Feature value of this record
* \return Prediction result
*/
inline double Predict(const double* feature_values) const;
inline double PredictByMap(const std::unordered_map<int, double>& feature_values) const;
inline int PredictLeafIndex(const double* feature_values) const;
inline int PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const;
inline void PredictContrib(const double* feature_values, int num_features, double* output);
inline void PredictContribByMap(const std::unordered_map<int, double>& feature_values,
int num_features, std::unordered_map<int, double>* output);
/*! \brief Get Number of leaves*/
inline int num_leaves() const { return num_leaves_; }
/*! \brief Get depth of specific leaf*/
inline int leaf_depth(int leaf_idx) const { return leaf_depth_[leaf_idx]; }
/*! \brief Get parent of specific leaf*/
inline int leaf_parent(int leaf_idx) const {return leaf_parent_[leaf_idx]; }
/*! \brief Get feature of specific split (original feature index)*/
inline int split_feature(int split_idx) const { return split_feature_[split_idx]; }
/*! \brief Get feature of specific split*/
inline int split_feature_inner(int split_idx) const { return split_feature_inner_[split_idx]; }
/*! \brief Get features on leaf's branch*/
inline std::vector<int> branch_features(int leaf) const { return branch_features_[leaf]; }
inline double split_gain(int split_idx) const { return split_gain_[split_idx]; }
inline double internal_value(int node_idx) const {
return internal_value_[node_idx];
}
inline bool IsNumericalSplit(int node_idx) const {
return !GetDecisionType(decision_type_[node_idx], kCategoricalMask);
}
inline int left_child(int node_idx) const { return left_child_[node_idx]; }
inline int right_child(int node_idx) const { return right_child_[node_idx]; }
inline uint32_t threshold_in_bin(int node_idx) const {
return threshold_in_bin_[node_idx];
}
/*! \brief Get the number of data points that fall at or below this node*/
inline int data_count(int node) const { return node >= 0 ? internal_count_[node] : leaf_count_[~node]; }
/*!
* \brief Shrinkage for the tree's output
* shrinkage rate (a.k.a learning rate) is used to tune the training process
* \param rate The factor of shrinkage
*/
inline void Shrinkage(double rate) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] * rate);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] * rate);
if (is_linear_) {
leaf_const_[i] = MaybeRoundToZero(leaf_const_[i] * rate);
for (size_t j = 0; j < leaf_coeff_[i].size(); ++j) {
leaf_coeff_[i][j] = MaybeRoundToZero(leaf_coeff_[i][j] * rate);
}
}
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] * rate);
if (is_linear_) {
leaf_const_[num_leaves_ - 1] = MaybeRoundToZero(leaf_const_[num_leaves_ - 1] * rate);
for (size_t j = 0; j < leaf_coeff_[num_leaves_ - 1].size(); ++j) {
leaf_coeff_[num_leaves_ - 1][j] = MaybeRoundToZero(leaf_coeff_[num_leaves_ - 1][j] * rate);
}
}
shrinkage_ *= rate;
}
inline double shrinkage() const { return shrinkage_; }
inline void AddBias(double val) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_value_[i] = MaybeRoundToZero(leaf_value_[i] + val);
internal_value_[i] = MaybeRoundToZero(internal_value_[i] + val);
}
leaf_value_[num_leaves_ - 1] =
MaybeRoundToZero(leaf_value_[num_leaves_ - 1] + val);
if (is_linear_) {
#pragma omp parallel for schedule(static, 1024) if (num_leaves_ >= 2048)
for (int i = 0; i < num_leaves_ - 1; ++i) {
leaf_const_[i] = MaybeRoundToZero(leaf_const_[i] + val);
}
leaf_const_[num_leaves_ - 1] = MaybeRoundToZero(leaf_const_[num_leaves_ - 1] + val);
}
// force to 1.0
shrinkage_ = 1.0f;
}
inline void AsConstantTree(double val) {
num_leaves_ = 1;
shrinkage_ = 1.0f;
leaf_value_[0] = val;
if (is_linear_) {
leaf_const_[0] = val;
}
}
/*! \brief Serialize this object to string*/
std::string ToString() const;
/*! \brief Serialize this object to json*/
std::string ToJSON() const;
/*! \brief Serialize this object to if-else statement*/
std::string ToIfElse(int index, bool predict_leaf_index) const;
inline static bool IsZero(double fval) {
return (fval >= -kZeroThreshold && fval <= kZeroThreshold);
}
inline static double MaybeRoundToZero(double fval) {
return IsZero(fval) ? 0 : fval;
}
inline static bool GetDecisionType(int8_t decision_type, int8_t mask) {
return (decision_type & mask) > 0;
}
inline static void SetDecisionType(int8_t* decision_type, bool input, int8_t mask) {
if (input) {
(*decision_type) |= mask;
} else {
(*decision_type) &= (127 - mask);
}
}
inline static int8_t GetMissingType(int8_t decision_type) {
return (decision_type >> 2) & 3;
}
inline static void SetMissingType(int8_t* decision_type, int8_t input) {
(*decision_type) &= 3;
(*decision_type) |= (input << 2);
}
void RecomputeMaxDepth();
int NextLeafId() const { return num_leaves_; }
/*! \brief Get the linear model constant term (bias) of one leaf */
inline double LeafConst(int leaf) const { return leaf_const_[leaf]; }
/*! \brief Get the linear model coefficients of one leaf */
inline std::vector<double> LeafCoeffs(int leaf) const { return leaf_coeff_[leaf]; }
/*! \brief Get the linear model features of one leaf */
inline std::vector<int> LeafFeaturesInner(int leaf) const {return leaf_features_inner_[leaf]; }
/*! \brief Get the linear model features of one leaf */
inline std::vector<int> LeafFeatures(int leaf) const {return leaf_features_[leaf]; }
/*! \brief Set the linear model coefficients on one leaf */
inline void SetLeafCoeffs(int leaf, const std::vector<double>& output) {
leaf_coeff_[leaf].resize(output.size());
for (size_t i = 0; i < output.size(); ++i) {
leaf_coeff_[leaf][i] = MaybeRoundToZero(output[i]);
}
}
/*! \brief Set the linear model constant term (bias) on one leaf */
inline void SetLeafConst(int leaf, double output) {
leaf_const_[leaf] = MaybeRoundToZero(output);
}
/*! \brief Set the linear model features on one leaf */
inline void SetLeafFeaturesInner(int leaf, const std::vector<int>& features) {
leaf_features_inner_[leaf] = features;
}
/*! \brief Set the linear model features on one leaf */
inline void SetLeafFeatures(int leaf, const std::vector<int>& features) {
leaf_features_[leaf] = features;
}
inline bool is_linear() const { return is_linear_; }
inline void SetIsLinear(bool is_linear) {
is_linear_ = is_linear;
}
private:
std::string NumericalDecisionIfElse(int node) const;
std::string CategoricalDecisionIfElse(int node) const;
inline int NumericalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if (std::isnan(fval) && missing_type != MissingType::NaN) {
fval = 0.0f;
}
if ((missing_type == MissingType::Zero && IsZero(fval))
|| (missing_type == MissingType::NaN && std::isnan(fval))) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int NumericalDecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
if ((missing_type == MissingType::Zero && fval == default_bin)
|| (missing_type == MissingType::NaN && fval == max_bin)) {
if (GetDecisionType(decision_type_[node], kDefaultLeftMask)) {
return left_child_[node];
} else {
return right_child_[node];
}
}
if (fval <= threshold_in_bin_[node]) {
return left_child_[node];
} else {
return right_child_[node];
}
}
inline int CategoricalDecision(double fval, int node) const {
uint8_t missing_type = GetMissingType(decision_type_[node]);
int int_fval = static_cast<int>(fval);
if (int_fval < 0) {
return right_child_[node];;
} else if (std::isnan(fval)) {
// NaN is always in the right
if (missing_type == MissingType::NaN) {
return right_child_[node];
}
int_fval = 0;
}
int cat_idx = static_cast<int>(threshold_[node]);
if (Common::FindInBitset(cat_threshold_.data() + cat_boundaries_[cat_idx],
cat_boundaries_[cat_idx + 1] - cat_boundaries_[cat_idx], int_fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int CategoricalDecisionInner(uint32_t fval, int node) const {
int cat_idx = static_cast<int>(threshold_in_bin_[node]);
if (Common::FindInBitset(cat_threshold_inner_.data() + cat_boundaries_inner_[cat_idx],
cat_boundaries_inner_[cat_idx + 1] - cat_boundaries_inner_[cat_idx], fval)) {
return left_child_[node];
}
return right_child_[node];
}
inline int Decision(double fval, int node) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecision(fval, node);
} else {
return NumericalDecision(fval, node);
}
}
inline int DecisionInner(uint32_t fval, int node, uint32_t default_bin, uint32_t max_bin) const {
if (GetDecisionType(decision_type_[node], kCategoricalMask)) {
return CategoricalDecisionInner(fval, node);
} else {
return NumericalDecisionInner(fval, node, default_bin, max_bin);
}
}
inline void Split(int leaf, int feature, int real_feature, double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain);
/*!
* \brief Find leaf index of which record belongs by features
* \param feature_values Feature value of this record
* \return Leaf index
*/
inline int GetLeaf(const double* feature_values) const;
inline int GetLeafByMap(const std::unordered_map<int, double>& feature_values) const;
/*! \brief Serialize one node to json*/
std::string NodeToJSON(int index) const;
/*! \brief Serialize one node to if-else statement*/
std::string NodeToIfElse(int index, bool predict_leaf_index) const;
std::string NodeToIfElseByMap(int index, bool predict_leaf_index) const;
double ExpectedValue() const;
/*! \brief This is used fill in leaf_depth_ after reloading a model*/
inline void RecomputeLeafDepths(int node = 0, int depth = 0);
/*!
* \brief Used by TreeSHAP for data we keep about our decision path
*/
struct PathElement {
int feature_index;
double zero_fraction;
double one_fraction;
// note that pweight is included for convenience and is not tied with the other attributes,
// the pweight of the i'th path element is the permutation weight of paths with i-1 ones in them
double pweight;
PathElement() {}
PathElement(int i, double z, double o, double w) : feature_index(i), zero_fraction(z), one_fraction(o), pweight(w) {}
};
/*! \brief Polynomial time algorithm for SHAP values (arXiv:1706.06060)*/
void TreeSHAP(const double *feature_values, double *phi,
int node, int unique_depth,
PathElement *parent_unique_path, double parent_zero_fraction,
double parent_one_fraction, int parent_feature_index) const;
void TreeSHAPByMap(const std::unordered_map<int, double>& feature_values,
std::unordered_map<int, double>* phi,
int node, int unique_depth,
PathElement *parent_unique_path, double parent_zero_fraction,
double parent_one_fraction, int parent_feature_index) const;
/*! \brief Extend our decision path with a fraction of one and zero extensions for TreeSHAP*/
static void ExtendPath(PathElement *unique_path, int unique_depth,
double zero_fraction, double one_fraction, int feature_index);
/*! \brief Undo a previous extension of the decision path for TreeSHAP*/
static void UnwindPath(PathElement *unique_path, int unique_depth, int path_index);
/*! determine what the total permutation weight would be if we unwound a previous extension in the decision path*/
static double UnwoundPathSum(const PathElement *unique_path, int unique_depth, int path_index);
/*! \brief Number of max leaves*/
int max_leaves_;
/*! \brief Number of current leaves*/
int num_leaves_;
// following values used for non-leaf node
/*! \brief A non-leaf node's left child */
std::vector<int> left_child_;
/*! \brief A non-leaf node's right child */
std::vector<int> right_child_;
/*! \brief A non-leaf node's split feature */
std::vector<int> split_feature_inner_;
/*! \brief A non-leaf node's split feature, the original index */
std::vector<int> split_feature_;
/*! \brief A non-leaf node's split threshold in bin */
std::vector<uint32_t> threshold_in_bin_;
/*! \brief A non-leaf node's split threshold in feature value */
std::vector<double> threshold_;
int num_cat_;
std::vector<int> cat_boundaries_inner_;
std::vector<uint32_t> cat_threshold_inner_;
std::vector<int> cat_boundaries_;
std::vector<uint32_t> cat_threshold_;
/*! \brief Store the information for categorical feature handle and missing value handle. */
std::vector<int8_t> decision_type_;
/*! \brief A non-leaf node's split gain */
std::vector<float> split_gain_;
// used for leaf node
/*! \brief The parent of leaf */
std::vector<int> leaf_parent_;
/*! \brief Output of leaves */
std::vector<double> leaf_value_;
/*! \brief weight of leaves */
std::vector<double> leaf_weight_;
/*! \brief DataCount of leaves */
std::vector<int> leaf_count_;
/*! \brief Output of non-leaf nodes */
std::vector<double> internal_value_;
/*! \brief weight of non-leaf nodes */
std::vector<double> internal_weight_;
/*! \brief DataCount of non-leaf nodes */
std::vector<int> internal_count_;
/*! \brief Depth for leaves */
std::vector<int> leaf_depth_;
/*! \brief whether to keep track of ancestor nodes for each leaf (only needed when feature interactions are restricted) */
bool track_branch_features_;
/*! \brief Features on leaf's branch, original index */
std::vector<std::vector<int>> branch_features_;
double shrinkage_;
int max_depth_;
/*! \brief Tree has linear model at each leaf */
bool is_linear_;
/*! \brief coefficients of linear models on leaves */
std::vector<std::vector<double>> leaf_coeff_;
/*! \brief constant term (bias) of linear models on leaves */
std::vector<double> leaf_const_;
/* \brief features used in leaf linear models; indexing is relative to num_total_features_ */
std::vector<std::vector<int>> leaf_features_;
/* \brief features used in leaf linear models; indexing is relative to used_features_ */
std::vector<std::vector<int>> leaf_features_inner_;
};
inline void Tree::Split(int leaf, int feature, int real_feature,
double left_value, double right_value, int left_cnt, int right_cnt,
double left_weight, double right_weight, float gain) {
int new_node_idx = num_leaves_ - 1;
// update parent info
int parent = leaf_parent_[leaf];
if (parent >= 0) {
// if cur node is left child
if (left_child_[parent] == ~leaf) {
left_child_[parent] = new_node_idx;
} else {
right_child_[parent] = new_node_idx;
}
}
// add new node
split_feature_inner_[new_node_idx] = feature;
split_feature_[new_node_idx] = real_feature;
split_gain_[new_node_idx] = gain;
// add two new leaves
left_child_[new_node_idx] = ~leaf;
right_child_[new_node_idx] = ~num_leaves_;
// update new leaves
leaf_parent_[leaf] = new_node_idx;
leaf_parent_[num_leaves_] = new_node_idx;
// save current leaf value to internal node before change
internal_weight_[new_node_idx] = leaf_weight_[leaf];
internal_value_[new_node_idx] = leaf_value_[leaf];
internal_count_[new_node_idx] = left_cnt + right_cnt;
leaf_value_[leaf] = std::isnan(left_value) ? 0.0f : left_value;
leaf_weight_[leaf] = left_weight;
leaf_count_[leaf] = left_cnt;
leaf_value_[num_leaves_] = std::isnan(right_value) ? 0.0f : right_value;
leaf_weight_[num_leaves_] = right_weight;
leaf_count_[num_leaves_] = right_cnt;
// update leaf depth
leaf_depth_[num_leaves_] = leaf_depth_[leaf] + 1;
leaf_depth_[leaf]++;
if (track_branch_features_) {
branch_features_[num_leaves_] = branch_features_[leaf];
branch_features_[num_leaves_].push_back(split_feature_[new_node_idx]);
branch_features_[leaf].push_back(split_feature_[new_node_idx]);
}
}
inline double Tree::Predict(const double* feature_values) const {
if (is_linear_) {
int leaf = (num_leaves_ > 1) ? GetLeaf(feature_values) : 0;
double output = leaf_const_[leaf];
bool nan_found = false;
for (size_t i = 0; i < leaf_features_[leaf].size(); ++i) {
int feat_raw = leaf_features_[leaf][i];
double feat_val = feature_values[feat_raw];
if (std::isnan(feat_val)) {
nan_found = true;
break;
} else {
output += leaf_coeff_[leaf][i] * feat_val;
}
}
if (nan_found) {
return LeafOutput(leaf);
} else {
return output;
}
} else {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
}
inline double Tree::PredictByMap(const std::unordered_map<int, double>& feature_values) const {
if (is_linear_) {
int leaf = (num_leaves_ > 1) ? GetLeafByMap(feature_values) : 0;
double output = leaf_const_[leaf];
bool nan_found = false;
for (size_t i = 0; i < leaf_features_[leaf].size(); ++i) {
int feat = leaf_features_[leaf][i];
auto val_it = feature_values.find(feat);
if (val_it != feature_values.end()) {
double feat_val = val_it->second;
if (std::isnan(feat_val)) {
nan_found = true;
break;
} else {
output += leaf_coeff_[leaf][i] * feat_val;
}
}
}
if (nan_found) {
return LeafOutput(leaf);
} else {
return output;
}
} else {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return LeafOutput(leaf);
} else {
return leaf_value_[0];
}
}
}
inline int Tree::PredictLeafIndex(const double* feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeaf(feature_values);
return leaf;
} else {
return 0;
}
}
inline int Tree::PredictLeafIndexByMap(const std::unordered_map<int, double>& feature_values) const {
if (num_leaves_ > 1) {
int leaf = GetLeafByMap(feature_values);
return leaf;
} else {
return 0;
}
}
inline void Tree::PredictContrib(const double* feature_values, int num_features, double* output) {
output[num_features] += ExpectedValue();
// Run the recursion with preallocated space for the unique path data
if (num_leaves_ > 1) {
CHECK_GE(max_depth_, 0);
const int max_path_len = max_depth_ + 1;
std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
TreeSHAP(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
}
}
inline void Tree::PredictContribByMap(const std::unordered_map<int, double>& feature_values,
int num_features, std::unordered_map<int, double>* output) {
(*output)[num_features] += ExpectedValue();
// Run the recursion with preallocated space for the unique path data
if (num_leaves_ > 1) {
CHECK_GE(max_depth_, 0);
const int max_path_len = max_depth_ + 1;
std::vector<PathElement> unique_path_data(max_path_len*(max_path_len + 1) / 2);
TreeSHAPByMap(feature_values, output, 0, 0, unique_path_data.data(), 1, 1, -1);
}
}
inline void Tree::RecomputeLeafDepths(int node, int depth) {
if (node == 0) leaf_depth_.resize(num_leaves());
if (node < 0) {
leaf_depth_[~node] = depth;
} else {
RecomputeLeafDepths(left_child_[node], depth + 1);
RecomputeLeafDepths(right_child_[node], depth + 1);
}
}
inline int Tree::GetLeaf(const double* feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values[split_feature_[node]], node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values[split_feature_[node]], node);
}
}
return ~node;
}
inline int Tree::GetLeafByMap(const std::unordered_map<int, double>& feature_values) const {
int node = 0;
if (num_cat_ > 0) {
while (node >= 0) {
node = Decision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
} else {
while (node >= 0) {
node = NumericalDecision(feature_values.count(split_feature_[node]) > 0 ? feature_values.at(split_feature_[node]) : 0.0f, node);
}
}
return ~node;
}
} // namespace LightGBM
#endif // LightGBM_TREE_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-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/accelerate-private.h"
#include "magick/animate.h"
#include "magick/animate.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/cache-private.h"
#include "magick/cache-view.h"
#include "magick/client.h"
#include "magick/color.h"
#include "magick/color-private.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/composite.h"
#include "magick/composite-private.h"
#include "magick/compress.h"
#include "magick/constitute.h"
#include "magick/deprecate.h"
#include "magick/display.h"
#include "magick/draw.h"
#include "magick/enhance.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/gem.h"
#include "magick/geometry.h"
#include "magick/list.h"
#include "magick/image-private.h"
#include "magick/magic.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/module.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/paint.h"
#include "magick/pixel-private.h"
#include "magick/profile.h"
#include "magick/property.h"
#include "magick/quantize.h"
#include "magick/random_.h"
#include "magick/random-private.h"
#include "magick/resource_.h"
#include "magick/segment.h"
#include "magick/semaphore.h"
#include "magick/signature-private.h"
#include "magick/statistic.h"
#include "magick/string_.h"
#include "magick/thread-private.h"
#include "magick/timer.h"
#include "magick/utility.h"
#include "magick/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 EvaluateImageChannel 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)
% MagickBooleanType EvaluateImageChannel(Image *image,
% const ChannelType channel,const MagickEvaluateOperator op,
% const double value,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% o op: A channel op.
%
% o value: A value value.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickPixelPacket **DestroyPixelThreadSet(MagickPixelPacket **pixels)
{
register ssize_t
i;
assert(pixels != (MagickPixelPacket **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (pixels[i] != (MagickPixelPacket *) NULL)
pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]);
pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels);
return(pixels);
}
static MagickPixelPacket **AcquirePixelThreadSet(const Image *image,
const size_t number_images)
{
MagickPixelPacket
**pixels;
register ssize_t
i,
j;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads,
sizeof(*pixels));
if (pixels == (MagickPixelPacket **) NULL)
return((MagickPixelPacket **) NULL);
(void) memset(pixels,0,number_threads*sizeof(*pixels));
for (i=0; i < (ssize_t) number_threads; i++)
{
pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(image->columns,
sizeof(**pixels));
if (pixels[i] == (MagickPixelPacket *) NULL)
return(DestroyPixelThreadSet(pixels));
for (j=0; j < (ssize_t) image->columns; j++)
GetMagickPixelPacket(image,&pixels[i][j]);
}
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 MagickPixelPacket
*color_1,
*color_2;
int
intensity;
color_1=(const MagickPixelPacket *) x;
color_2=(const MagickPixelPacket *) y;
intensity=(int) MagickPixelIntensity(color_2)-(int)
MagickPixelIntensity(color_1);
return(intensity);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info,
const Quantum pixel,const MagickEvaluateOperator op,
const MagickRealType value)
{
MagickRealType
result;
result=0.0;
switch (op)
{
case UndefinedEvaluateOperator:
break;
case AbsEvaluateOperator:
{
result=(MagickRealType) fabs((double) (pixel+value));
break;
}
case AddEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case AddModulusEvaluateOperator:
{
/*
This returns a 'floored modulus' of the addition which is a
positive result. It differs from % or fmod() which 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=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5));
break;
}
case CosineEvaluateOperator:
{
result=(MagickRealType) (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=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale*
pixel)));
break;
}
case GaussianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
GaussianNoise,value);
break;
}
case ImpulseNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
ImpulseNoise,value);
break;
}
case LaplacianNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
LaplacianNoise,value);
break;
}
case LeftShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5));
break;
}
case LogEvaluateOperator:
{
if ((QuantumScale*pixel) >= MagickEpsilon)
result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value*
pixel+1.0))/log((double) (value+1.0)));
break;
}
case MaxEvaluateOperator:
{
result=(MagickRealType) EvaluateMax((double) pixel,value);
break;
}
case MeanEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MedianEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case MinEvaluateOperator:
{
result=(MagickRealType) MagickMin((double) pixel,value);
break;
}
case MultiplicativeNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
MultiplicativeGaussianNoise,value);
break;
}
case MultiplyEvaluateOperator:
{
result=(MagickRealType) (value*pixel);
break;
}
case OrEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5));
break;
}
case PoissonNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
PoissonNoise,value);
break;
}
case PowEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel),
(double) value));
break;
}
case RightShiftEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5));
break;
}
case RootMeanSquareEvaluateOperator:
{
result=(MagickRealType) (pixel*pixel+value);
break;
}
case SetEvaluateOperator:
{
result=value;
break;
}
case SineEvaluateOperator:
{
result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI*
QuantumScale*pixel*value))+0.5));
break;
}
case SubtractEvaluateOperator:
{
result=(MagickRealType) (pixel-value);
break;
}
case SumEvaluateOperator:
{
result=(MagickRealType) (pixel+value);
break;
}
case ThresholdEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 :
QuantumRange);
break;
}
case ThresholdBlackEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel);
break;
}
case ThresholdWhiteEvaluateOperator:
{
result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange :
pixel);
break;
}
case UniformNoiseEvaluateOperator:
{
result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel,
UniformNoise,value);
break;
}
case XorEvaluateOperator:
{
result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5));
break;
}
}
return(result);
}
static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception)
{
const Image
*p,
*q;
size_t
columns,
number_channels,
rows;
q=images;
columns=images->columns;
rows=images->rows;
number_channels=0;
for (p=images; p != (Image *) NULL; p=p->next)
{
size_t
channels;
channels=3;
if (p->matte != MagickFalse)
channels+=1;
if (p->colorspace == CMYKColorspace)
channels+=1;
if (channels > number_channels)
{
number_channels=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 MagickBooleanType EvaluateImage(Image *image,
const MagickEvaluateOperator op,const double value,ExceptionInfo *exception)
{
MagickBooleanType
status;
status=EvaluateImageChannel(image,CompositeChannels,op,value,exception);
return(status);
}
MagickExport Image *EvaluateImages(const Image *images,
const MagickEvaluateOperator op,ExceptionInfo *exception)
{
#define EvaluateImageTag "Evaluate/Image"
CacheView
*evaluate_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict evaluate_pixels,
zero;
RandomInfo
**magick_restrict random_info;
size_t
number_images;
ssize_t
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) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
number_images=GetImageListLength(images);
evaluate_pixels=AcquirePixelThreadSet(images,number_images);
if (evaluate_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Evaluate image pixels.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(images,&zero);
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++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
i;
for (i=0; i < (ssize_t) number_images; i++)
evaluate_pixel[i]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),op,evaluate_pixel[i].red);
evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),op,evaluate_pixel[i].green);
evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),op,evaluate_pixel[i].blue);
evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),op,evaluate_pixel[i].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id],
*indexes,op,evaluate_pixel[i].index);
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel),
IntensityCompare);
SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+i,ClampToQuantum(
evaluate_pixel[i/2].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_EvaluateImages)
#endif
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++)
{
CacheView
*image_view;
const Image
*next;
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict evaluate_indexes;
register ssize_t
i,
x;
register MagickPixelPacket
*evaluate_pixel;
register PixelPacket
*magick_restrict q;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view);
evaluate_pixel=evaluate_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
evaluate_pixel[x]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,
exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id],
GetPixelRed(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].red);
evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id],
GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].green);
evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id],
GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].blue);
evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id],
GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].opacity);
if (image->colorspace == CMYKColorspace)
evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id],
GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op,
evaluate_pixel[x].index);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
if (op == MeanEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red/=number_images;
evaluate_pixel[x].green/=number_images;
evaluate_pixel[x].blue/=number_images;
evaluate_pixel[x].opacity/=number_images;
evaluate_pixel[x].index/=number_images;
}
if (op == RootMeanSquareEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/
number_images);
evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/
number_images);
evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/
number_images);
evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/
number_images);
evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/
number_images);
}
if (op == MultiplyEvaluateOperator)
for (x=0; x < (ssize_t) image->columns; x++)
{
register ssize_t
j;
for (j=0; j < (ssize_t) (number_images-1); j++)
{
evaluate_pixel[x].red*=(MagickRealType) QuantumScale;
evaluate_pixel[x].green*=(MagickRealType) QuantumScale;
evaluate_pixel[x].blue*=(MagickRealType) QuantumScale;
evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale;
evaluate_pixel[x].index*=(MagickRealType) QuantumScale;
}
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue));
SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(evaluate_indexes+x,ClampToQuantum(
evaluate_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_EvaluateImages)
#endif
proceed=SetImageProgress(images,EvaluateImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
}
evaluate_view=DestroyCacheView(evaluate_view);
evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels);
random_info=DestroyRandomInfoThreadSet(random_info);
if (status == MagickFalse)
image=DestroyImage(image);
return(image);
}
MagickExport MagickBooleanType EvaluateImageChannel(Image *image,
const ChannelType channel,const MagickEvaluateOperator op,const double value,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
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) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
status=MagickTrue;
progress=0;
random_info=AcquireRandomInfoThreadSet();
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
key=GetRandomSecretKey(random_info[0]);
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,key == ~0UL)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
const int
id = GetOpenMPThreadId();
register IndexPacket
*magick_restrict indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
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);
for (x=0; x < (ssize_t) image->columns; x++)
{
MagickRealType
result;
if ((channel & RedChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelRed(q,ClampToQuantum(result));
}
if ((channel & GreenChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelGreen(q,ClampToQuantum(result));
}
if ((channel & BlueChannel) != 0)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op,
value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelBlue(q,ClampToQuantum(result));
}
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
{
result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelOpacity(q,ClampToQuantum(result));
}
else
{
result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelAlpha(q,ClampToQuantum(result));
}
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
{
result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x),
op,value);
if (op == MeanEvaluateOperator)
result/=2.0;
SetPixelIndex(indexes+x,ClampToQuantum(result));
}
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_EvaluateImageChannel)
#endif
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 FunctionImageChannel method is:
%
% MagickBooleanType FunctionImage(Image *image,
% const MagickFunction function,const ssize_t number_parameters,
% const double *parameters,ExceptionInfo *exception)
% MagickBooleanType FunctionImageChannel(Image *image,
% const ChannelType channel,const MagickFunction function,
% const ssize_t number_parameters,const double *argument,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
MagickRealType
result;
register ssize_t
i;
(void) exception;
result=0.0;
switch (function)
{
case PolynomialFunction:
{
/*
* Polynomial
* Parameters: polynomial constants, highest to lowest order
* For example: 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:
{
/* Sinusoid Function
* Parameters: Freq, Phase, Ampl, bias
*/
double freq,phase,ampl,bias;
freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0;
phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0;
ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5;
bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5;
result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI*
(freq*QuantumScale*pixel + phase/360.0) )) + bias ) );
break;
}
case ArcsinFunction:
{
/* Arcsin Function (peged at range limits for invalid results)
* Parameters: Width, Center, Range, Bias
*/
double width,range,center,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/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=(MagickRealType) (range/MagickPI*asin((double) result)+bias);
result *= QuantumRange;
break;
}
case ArctanFunction:
{
/* Arctan Function
* Parameters: Slope, Center, Range, Bias
*/
double slope,range,center,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=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center));
result=(MagickRealType) (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)
{
MagickBooleanType
status;
status=FunctionImageChannel(image,CompositeChannels,function,
number_parameters,parameters,exception);
return(status);
}
MagickExport MagickBooleanType FunctionImageChannel(Image *image,
const ChannelType channel,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 (SetImageStorageClass(image,DirectClass) == MagickFalse)
{
InheritException(exception,&image->exception);
return(MagickFalse);
}
#if defined(MAGICKCORE_OPENCL_SUPPORT)
status=AccelerateFunctionImage(image,channel,function,number_parameters,
parameters,exception);
if (status != MagickFalse)
return(status);
#endif
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(progress,status) \
magick_number_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
register 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);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
SetPixelRed(q,ApplyFunction(GetPixelRed(q),function,
number_parameters,parameters,exception));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function,
number_parameters,parameters,exception));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function,
number_parameters,parameters,exception));
if ((channel & OpacityChannel) != 0)
{
if (image->matte == MagickFalse)
SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function,
number_parameters,parameters,exception));
else
SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function,
number_parameters,parameters,exception));
}
if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL))
SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function,
number_parameters,parameters,exception));
q++;
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_FunctionImageChannel)
#endif
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 C h a n n e l E n t r o p y %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelEntropy() returns the entropy of one or more image channels.
%
% The format of the GetImageChannelEntropy method is:
%
% MagickBooleanType GetImageChannelEntropy(const Image *image,
% const ChannelType channel,double *entropy,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
MagickBooleanType
status;
status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image,
const ChannelType channel,double *entropy,ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].entropy=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[RedChannel].entropy;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[GreenChannel].entropy;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlueChannel].entropy;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[OpacityChannel].entropy;
channels++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].entropy+=
channel_statistics[BlackChannel].entropy;
channels++;
}
channel_statistics[CompositeChannels].entropy/=channels;
*entropy=channel_statistics[CompositeChannels].entropy;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t I m a g e C h a n n e l E x t r e m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelExtrema() returns the extrema of one or more image channels.
%
% The format of the GetImageChannelExtrema method is:
%
% MagickBooleanType GetImageChannelExtrema(const Image *image,
% const ChannelType channel,size_t *minima,size_t *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
MagickBooleanType
status;
status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image,
const ChannelType channel,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=GetImageChannelRange(image,channel,&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 C h a n n e l K u r t o s i s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelKurtosis() returns the kurtosis and skewness of one or more
% image channels.
%
% The format of the GetImageChannelKurtosis method is:
%
% MagickBooleanType GetImageChannelKurtosis(const Image *image,
% const ChannelType channel,double *kurtosis,double *skewness,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
MagickBooleanType
status;
status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image,
const ChannelType channel,double *kurtosis,double *skewness,
ExceptionInfo *exception)
{
double
area,
mean,
standard_deviation,
sum_squares,
sum_cubes,
sum_fourth_power;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*kurtosis=0.0;
*skewness=0.0;
area=0.0;
mean=0.0;
standard_deviation=0.0;
sum_squares=0.0;
sum_cubes=0.0;
sum_fourth_power=0.0;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
if ((channel & RedChannel) != 0)
{
mean+=GetPixelRed(p);
sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p);
sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*
GetPixelRed(p)*GetPixelRed(p);
area++;
}
if ((channel & GreenChannel) != 0)
{
mean+=GetPixelGreen(p);
sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p);
sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p);
sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
area++;
}
if ((channel & BlueChannel) != 0)
{
mean+=GetPixelBlue(p);
sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p);
sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
area++;
}
if ((channel & OpacityChannel) != 0)
{
mean+=GetPixelAlpha(p);
sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p);
sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)*
GetPixelAlpha(p);
sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*
GetPixelAlpha(p)*GetPixelAlpha(p);
area++;
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
double
index;
index=(double) GetPixelIndex(indexes+x);
mean+=index;
sum_squares+=index*index;
sum_cubes+=index*index*index;
sum_fourth_power+=index*index*index*index;
area++;
}
p++;
}
}
if (y < (ssize_t) image->rows)
return(MagickFalse);
if (area != 0.0)
{
mean/=area;
sum_squares/=area;
sum_cubes/=area;
sum_fourth_power/=area;
}
standard_deviation=sqrt(sum_squares-(mean*mean));
if (standard_deviation != 0.0)
{
*kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares-
3.0*mean*mean*mean*mean;
*kurtosis/=standard_deviation*standard_deviation*standard_deviation*
standard_deviation;
*kurtosis-=3.0;
*skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean;
*skewness/=standard_deviation*standard_deviation*standard_deviation;
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M e a n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMean() returns the mean and standard deviation of one or more
% image channels.
%
% The format of the GetImageChannelMean method is:
%
% MagickBooleanType GetImageChannelMean(const Image *image,
% const ChannelType channel,double *mean,double *standard_deviation,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
MagickBooleanType
status;
status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation,
exception);
return(status);
}
MagickExport MagickBooleanType GetImageChannelMean(const Image *image,
const ChannelType channel,double *mean,double *standard_deviation,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
size_t
channels;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
channel_statistics=GetImageChannelStatistics(image,exception);
if (channel_statistics == (ChannelStatistics *) NULL)
return(MagickFalse);
channels=0;
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
if ((channel & RedChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[RedChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[RedChannel].standard_deviation;
channels++;
}
if ((channel & GreenChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[GreenChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[GreenChannel].standard_deviation;
channels++;
}
if ((channel & BlueChannel) != 0)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlueChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[BlueChannel].standard_deviation;
channels++;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
channel_statistics[CompositeChannels].mean+=
(QuantumRange-channel_statistics[OpacityChannel].mean);
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[OpacityChannel].standard_deviation;
channels++;
}
if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace))
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[BlackChannel].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[CompositeChannels].standard_deviation;
channels++;
}
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].standard_deviation/=channels;
*mean=channel_statistics[CompositeChannels].mean;
*standard_deviation=channel_statistics[CompositeChannels].standard_deviation;
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l M o m e n t s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelMoments() returns the normalized moments of one or more image
% channels.
%
% The format of the GetImageChannelMoments method is:
%
% ChannelMoments *GetImageChannelMoments(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 *GetImageChannelMoments(const Image *image,
ExceptionInfo *exception)
{
#define MaxNumberImageMoments 8
ChannelMoments
*channel_moments;
double
M00[CompositeChannels+1],
M01[CompositeChannels+1],
M02[CompositeChannels+1],
M03[CompositeChannels+1],
M10[CompositeChannels+1],
M11[CompositeChannels+1],
M12[CompositeChannels+1],
M20[CompositeChannels+1],
M21[CompositeChannels+1],
M22[CompositeChannels+1],
M30[CompositeChannels+1];
MagickPixelPacket
pixel;
PointInfo
centroid[CompositeChannels+1];
ssize_t
channel,
channels,
y;
size_t
length;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_moments=(ChannelMoments *) AcquireQuantumMemory(length,
sizeof(*channel_moments));
if (channel_moments == (ChannelMoments *) NULL)
return(channel_moments);
(void) memset(channel_moments,0,length*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));
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute center of mass (centroid).
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M00[RedChannel]+=QuantumScale*pixel.red;
M10[RedChannel]+=x*QuantumScale*pixel.red;
M01[RedChannel]+=y*QuantumScale*pixel.red;
M00[GreenChannel]+=QuantumScale*pixel.green;
M10[GreenChannel]+=x*QuantumScale*pixel.green;
M01[GreenChannel]+=y*QuantumScale*pixel.green;
M00[BlueChannel]+=QuantumScale*pixel.blue;
M10[BlueChannel]+=x*QuantumScale*pixel.blue;
M01[BlueChannel]+=y*QuantumScale*pixel.blue;
if (image->matte != MagickFalse)
{
M00[OpacityChannel]+=QuantumScale*pixel.opacity;
M10[OpacityChannel]+=x*QuantumScale*pixel.opacity;
M01[OpacityChannel]+=y*QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M00[IndexChannel]+=QuantumScale*pixel.index;
M10[IndexChannel]+=x*QuantumScale*pixel.index;
M01[IndexChannel]+=y*QuantumScale*pixel.index;
}
p++;
}
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute center of mass (centroid).
*/
if (M00[channel] < MagickEpsilon)
{
M00[channel]+=MagickEpsilon;
centroid[channel].x=(double) image->columns/2.0;
centroid[channel].y=(double) image->rows/2.0;
continue;
}
M00[channel]+=MagickEpsilon;
centroid[channel].x=M10[channel]/M00[channel];
centroid[channel].y=M01[channel]/M00[channel];
}
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute the image moments.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
M11[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M20[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*QuantumScale*pixel.red;
M02[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M21[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M12[RedChannel]+=(x-centroid[RedChannel].x)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M22[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*QuantumScale*pixel.red;
M30[RedChannel]+=(x-centroid[RedChannel].x)*(x-
centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale*
pixel.red;
M03[RedChannel]+=(y-centroid[RedChannel].y)*(y-
centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale*
pixel.red;
M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*QuantumScale*pixel.green;
M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*QuantumScale*pixel.green;
M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x-
centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale*
pixel.green;
M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y-
centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale*
pixel.green;
M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*QuantumScale*pixel.blue;
M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*QuantumScale*pixel.blue;
M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x-
centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale*
pixel.blue;
M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y-
centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale*
pixel.blue;
if (image->matte != MagickFalse)
{
M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*QuantumScale*pixel.opacity;
M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*QuantumScale*pixel.opacity;
M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x-
centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)*
QuantumScale*pixel.opacity;
M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y-
centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)*
QuantumScale*pixel.opacity;
}
if (image->colorspace == CMYKColorspace)
{
M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*QuantumScale*pixel.index;
M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*QuantumScale*pixel.index;
M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x-
centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)*
QuantumScale*pixel.index;
M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y-
centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)*
QuantumScale*pixel.index;
}
p++;
}
}
channels=3;
M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]);
M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]);
M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]);
M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]);
M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]);
M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]);
M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]);
M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]);
M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]);
M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]);
M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]);
if (image->matte != MagickFalse)
{
channels+=1;
M00[CompositeChannels]+=M00[OpacityChannel];
M01[CompositeChannels]+=M01[OpacityChannel];
M02[CompositeChannels]+=M02[OpacityChannel];
M03[CompositeChannels]+=M03[OpacityChannel];
M10[CompositeChannels]+=M10[OpacityChannel];
M11[CompositeChannels]+=M11[OpacityChannel];
M12[CompositeChannels]+=M12[OpacityChannel];
M20[CompositeChannels]+=M20[OpacityChannel];
M21[CompositeChannels]+=M21[OpacityChannel];
M22[CompositeChannels]+=M22[OpacityChannel];
M30[CompositeChannels]+=M30[OpacityChannel];
}
if (image->colorspace == CMYKColorspace)
{
channels+=1;
M00[CompositeChannels]+=M00[IndexChannel];
M01[CompositeChannels]+=M01[IndexChannel];
M02[CompositeChannels]+=M02[IndexChannel];
M03[CompositeChannels]+=M03[IndexChannel];
M10[CompositeChannels]+=M10[IndexChannel];
M11[CompositeChannels]+=M11[IndexChannel];
M12[CompositeChannels]+=M12[IndexChannel];
M20[CompositeChannels]+=M20[IndexChannel];
M21[CompositeChannels]+=M21[IndexChannel];
M22[CompositeChannels]+=M22[IndexChannel];
M30[CompositeChannels]+=M30[IndexChannel];
}
M00[CompositeChannels]/=(double) channels;
M01[CompositeChannels]/=(double) channels;
M02[CompositeChannels]/=(double) channels;
M03[CompositeChannels]/=(double) channels;
M10[CompositeChannels]/=(double) channels;
M11[CompositeChannels]/=(double) channels;
M12[CompositeChannels]/=(double) channels;
M20[CompositeChannels]/=(double) channels;
M21[CompositeChannels]/=(double) channels;
M22[CompositeChannels]/=(double) channels;
M30[CompositeChannels]/=(double) channels;
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute elliptical angle, major and minor axes, eccentricity, & intensity.
*/
channel_moments[channel].centroid=centroid[channel];
channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])*
((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+
(M20[channel]-M02[channel])*(M20[channel]-M02[channel]))));
channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0*
M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon)));
if (fabs(M11[channel]) < MagickEpsilon)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
else
if (M11[channel] < 0.0)
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=180.0;
}
else
{
if (fabs(M20[channel]-M02[channel]) < MagickEpsilon)
channel_moments[channel].ellipse_angle+=0.0;
else
if ((M20[channel]-M02[channel]) < 0.0)
channel_moments[channel].ellipse_angle+=90.0;
else
channel_moments[channel].ellipse_angle+=0.0;
}
channel_moments[channel].ellipse_eccentricity=sqrt(1.0-(
channel_moments[channel].ellipse_axis.y/
(channel_moments[channel].ellipse_axis.x+MagickEpsilon)));
channel_moments[channel].ellipse_intensity=M00[channel]/
(MagickPI*channel_moments[channel].ellipse_axis.x*
channel_moments[channel].ellipse_axis.y+MagickEpsilon);
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Normalize image moments.
*/
M10[channel]=0.0;
M01[channel]=0.0;
M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0);
M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0);
M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0);
M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0);
M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0);
M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0);
M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0);
M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0);
M00[channel]=1.0;
}
for (channel=0; channel <= CompositeChannels; channel++)
{
/*
Compute Hu invariant moments.
*/
channel_moments[channel].I[0]=M20[channel]+M02[channel];
channel_moments[channel].I[1]=(M20[channel]-M02[channel])*
(M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel];
channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])*
(M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])*
(3.0*M21[channel]-M03[channel]);
channel_moments[channel].I[3]=(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])+(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]);
channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[5]=(M20[channel]-M02[channel])*
((M30[channel]+M12[channel])*(M30[channel]+M12[channel])-
(M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+
4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]);
channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])*
(M30[channel]+M12[channel])*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])*
(M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M21[channel]+M03[channel])*
(M21[channel]+M03[channel]));
channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])*
(M30[channel]+M12[channel])-(M03[channel]+M21[channel])*
(M03[channel]+M21[channel]))-(M20[channel]-M02[channel])*
(M30[channel]+M12[channel])*(M03[channel]+M21[channel]);
}
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 %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelPerceptualHash() returns the perceptual hash of one or more
% image channels.
%
% The format of the GetImageChannelPerceptualHash method is:
%
% ChannelPerceptualHash *GetImageChannelPerceptualHash(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 *GetImageChannelPerceptualHash(
const Image *image,ExceptionInfo *exception)
{
ChannelMoments
*moments;
ChannelPerceptualHash
*perceptual_hash;
Image
*hash_image;
MagickBooleanType
status;
register ssize_t
i;
ssize_t
channel;
/*
Blur then transform to sRGB colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
return((ChannelPerceptualHash *) NULL);
hash_image->depth=8;
status=TransformImageColorspace(hash_image,sRGBColorspace);
if (status == MagickFalse)
return((ChannelPerceptualHash *) NULL);
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
return((ChannelPerceptualHash *) NULL);
perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory(
CompositeChannels+1UL,sizeof(*perceptual_hash));
if (perceptual_hash == (ChannelPerceptualHash *) NULL)
return((ChannelPerceptualHash *) NULL);
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
/*
Blur then transform to HCLp colorspace.
*/
hash_image=BlurImage(image,0.0,1.0,exception);
if (hash_image == (Image *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
hash_image->depth=8;
status=TransformImageColorspace(hash_image,HCLpColorspace);
if (status == MagickFalse)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
moments=GetImageChannelMoments(hash_image,exception);
hash_image=DestroyImage(hash_image);
if (moments == (ChannelMoments *) NULL)
{
perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory(
perceptual_hash);
return((ChannelPerceptualHash *) NULL);
}
for (channel=0; channel <= CompositeChannels; channel++)
for (i=0; i < MaximumNumberOfImageMoments; i++)
perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i]));
moments=(ChannelMoments *) RelinquishMagickMemory(moments);
return(perceptual_hash);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l R a n g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelRange() returns the range of one or more image channels.
%
% The format of the GetImageChannelRange method is:
%
% MagickBooleanType GetImageChannelRange(const Image *image,
% const ChannelType channel,double *minima,double *maxima,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the channel.
%
% 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)
{
return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception));
}
MagickExport MagickBooleanType GetImageChannelRange(const Image *image,
const ChannelType channel,double *minima,double *maxima,
ExceptionInfo *exception)
{
MagickPixelPacket
pixel;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
*maxima=(-MagickMaximumValue);
*minima=MagickMaximumValue;
GetMagickPixelPacket(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; x++)
{
SetMagickPixelPacket(image,p,indexes+x,&pixel);
if ((channel & RedChannel) != 0)
{
if (pixel.red < *minima)
*minima=(double) pixel.red;
if (pixel.red > *maxima)
*maxima=(double) pixel.red;
}
if ((channel & GreenChannel) != 0)
{
if (pixel.green < *minima)
*minima=(double) pixel.green;
if (pixel.green > *maxima)
*maxima=(double) pixel.green;
}
if ((channel & BlueChannel) != 0)
{
if (pixel.blue < *minima)
*minima=(double) pixel.blue;
if (pixel.blue > *maxima)
*maxima=(double) pixel.blue;
}
if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse))
{
if ((QuantumRange-pixel.opacity) < *minima)
*minima=(double) (QuantumRange-pixel.opacity);
if ((QuantumRange-pixel.opacity) > *maxima)
*maxima=(double) (QuantumRange-pixel.opacity);
}
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
{
if ((double) pixel.index < *minima)
*minima=(double) pixel.index;
if ((double) pixel.index > *maxima)
*maxima=(double) pixel.index;
}
p++;
}
}
return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t I m a g e C h a n n e l S t a t i s t i c s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetImageChannelStatistics() 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=GetImageChannelStatistics(image,exception);
% red_mean=channel_statistics[RedChannel].mean;
%
% Use MagickRelinquishMemory() to free the statistics buffer.
%
% The format of the GetImageChannelStatistics method is:
%
% ChannelStatistics *GetImageChannelStatistics(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 ChannelStatistics *GetImageChannelStatistics(const Image *image,
ExceptionInfo *exception)
{
ChannelStatistics
*channel_statistics;
double
area,
standard_deviation;
MagickPixelPacket
number_bins,
*histogram;
QuantumAny
range;
register ssize_t
i;
size_t
channels,
depth,
length;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
length=CompositeChannels+1UL;
channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length,
sizeof(*channel_statistics));
histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U,
sizeof(*histogram));
if ((channel_statistics == (ChannelStatistics *) NULL) ||
(histogram == (MagickPixelPacket *) NULL))
{
if (histogram != (MagickPixelPacket *) NULL)
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
if (channel_statistics != (ChannelStatistics *) NULL)
channel_statistics=(ChannelStatistics *) RelinquishMagickMemory(
channel_statistics);
return(channel_statistics);
}
(void) memset(channel_statistics,0,length*
sizeof(*channel_statistics));
for (i=0; i <= (ssize_t) CompositeChannels; i++)
{
channel_statistics[i].depth=1;
channel_statistics[i].maxima=(-MagickMaximumValue);
channel_statistics[i].minima=MagickMaximumValue;
}
(void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram));
(void) memset(&number_bins,0,sizeof(number_bins));
for (y=0; y < (ssize_t) image->rows; y++)
{
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register ssize_t
x;
/*
Compute pixel statistics.
*/
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
indexes=GetVirtualIndexQueue(image);
for (x=0; x < (ssize_t) image->columns; )
{
if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[RedChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse)
{
channel_statistics[RedChannel].depth++;
continue;
}
}
if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[GreenChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse)
{
channel_statistics[GreenChannel].depth++;
continue;
}
}
if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlueChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse)
{
channel_statistics[BlueChannel].depth++;
continue;
}
}
if (image->matte != MagickFalse)
{
if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[OpacityChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse)
{
channel_statistics[OpacityChannel].depth++;
continue;
}
}
}
if (image->colorspace == CMYKColorspace)
{
if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH)
{
depth=channel_statistics[BlackChannel].depth;
range=GetQuantumRange(depth);
if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse)
{
channel_statistics[BlackChannel].depth++;
continue;
}
}
}
if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima)
channel_statistics[RedChannel].minima=(double) GetPixelRed(p);
if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima)
channel_statistics[RedChannel].maxima=(double) GetPixelRed(p);
channel_statistics[RedChannel].sum+=GetPixelRed(p);
channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)*
GetPixelRed(p);
channel_statistics[RedChannel].sum_cubed+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
channel_statistics[RedChannel].sum_fourth_power+=(double)
GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p);
if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima)
channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p);
if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima)
channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p);
channel_statistics[GreenChannel].sum+=GetPixelGreen(p);
channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)*
GetPixelGreen(p);
channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)*
GetPixelGreen(p)*GetPixelGreen(p);
channel_statistics[GreenChannel].sum_fourth_power+=(double)
GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p);
if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima)
channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p);
if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima)
channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p);
channel_statistics[BlueChannel].sum+=GetPixelBlue(p);
channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)*
GetPixelBlue(p);
channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)*
GetPixelBlue(p)*GetPixelBlue(p);
channel_statistics[BlueChannel].sum_fourth_power+=(double)
GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p);
histogram[ScaleQuantumToMap(GetPixelRed(p))].red++;
histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++;
histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++;
if (image->matte != MagickFalse)
{
if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima)
channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p);
if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima)
channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_squared+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_cubed+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
channel_statistics[OpacityChannel].sum_fourth_power+=(double)
GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p);
histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++;
}
if (image->colorspace == CMYKColorspace)
{
if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima)
channel_statistics[BlackChannel].minima=(double)
GetPixelIndex(indexes+x);
if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima)
channel_statistics[BlackChannel].maxima=(double)
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_squared+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_cubed+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x);
channel_statistics[BlackChannel].sum_fourth_power+=(double)
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)*
GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x);
histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++;
}
x++;
p++;
}
}
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
double
area,
mean,
standard_deviation;
/*
Normalize pixel statistics.
*/
area=PerceptibleReciprocal((double) image->columns*image->rows);
mean=channel_statistics[i].sum*area;
channel_statistics[i].sum=mean;
channel_statistics[i].sum_squared*=area;
channel_statistics[i].sum_cubed*=area;
channel_statistics[i].sum_fourth_power*=area;
channel_statistics[i].mean=mean;
channel_statistics[i].variance=channel_statistics[i].sum_squared;
standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
}
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
if (histogram[i].red > 0.0)
number_bins.red++;
if (histogram[i].green > 0.0)
number_bins.green++;
if (histogram[i].blue > 0.0)
number_bins.blue++;
if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0))
number_bins.opacity++;
if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0))
number_bins.index++;
}
area=PerceptibleReciprocal((double) image->columns*image->rows);
for (i=0; i < (ssize_t) (MaxMap+1U); i++)
{
/*
Compute pixel entropy.
*/
histogram[i].red*=area;
channel_statistics[RedChannel].entropy+=-histogram[i].red*
MagickLog10(histogram[i].red)*
PerceptibleReciprocal(MagickLog10((double) number_bins.red));
histogram[i].green*=area;
channel_statistics[GreenChannel].entropy+=-histogram[i].green*
MagickLog10(histogram[i].green)*
PerceptibleReciprocal(MagickLog10((double) number_bins.green));
histogram[i].blue*=area;
channel_statistics[BlueChannel].entropy+=-histogram[i].blue*
MagickLog10(histogram[i].blue)*
PerceptibleReciprocal(MagickLog10((double) number_bins.blue));
if (image->matte != MagickFalse)
{
histogram[i].opacity*=area;
channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity*
MagickLog10(histogram[i].opacity)*
PerceptibleReciprocal(MagickLog10((double) number_bins.opacity));
}
if (image->colorspace == CMYKColorspace)
{
histogram[i].index*=area;
channel_statistics[IndexChannel].entropy+=-histogram[i].index*
MagickLog10(histogram[i].index)*
PerceptibleReciprocal(MagickLog10((double) number_bins.index));
}
}
/*
Compute overall statistics.
*/
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double)
channel_statistics[CompositeChannels].depth,(double)
channel_statistics[i].depth);
channel_statistics[CompositeChannels].minima=MagickMin(
channel_statistics[CompositeChannels].minima,
channel_statistics[i].minima);
channel_statistics[CompositeChannels].maxima=EvaluateMax(
channel_statistics[CompositeChannels].maxima,
channel_statistics[i].maxima);
channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum;
channel_statistics[CompositeChannels].sum_squared+=
channel_statistics[i].sum_squared;
channel_statistics[CompositeChannels].sum_cubed+=
channel_statistics[i].sum_cubed;
channel_statistics[CompositeChannels].sum_fourth_power+=
channel_statistics[i].sum_fourth_power;
channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean;
channel_statistics[CompositeChannels].variance+=
channel_statistics[i].variance-channel_statistics[i].mean*
channel_statistics[i].mean;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)*
((double) image->columns*image->rows);
standard_deviation=sqrt(area*standard_deviation*standard_deviation);
channel_statistics[CompositeChannels].standard_deviation=standard_deviation;
channel_statistics[CompositeChannels].entropy+=
channel_statistics[i].entropy;
}
channels=3;
if (image->matte != MagickFalse)
channels++;
if (image->colorspace == CMYKColorspace)
channels++;
channel_statistics[CompositeChannels].sum/=channels;
channel_statistics[CompositeChannels].sum_squared/=channels;
channel_statistics[CompositeChannels].sum_cubed/=channels;
channel_statistics[CompositeChannels].sum_fourth_power/=channels;
channel_statistics[CompositeChannels].mean/=channels;
channel_statistics[CompositeChannels].kurtosis/=channels;
channel_statistics[CompositeChannels].skewness/=channels;
channel_statistics[CompositeChannels].entropy/=channels;
i=CompositeChannels;
area=PerceptibleReciprocal((double) channels*image->columns*image->rows);
channel_statistics[i].variance=channel_statistics[i].sum_squared;
channel_statistics[i].mean=channel_statistics[i].sum;
standard_deviation=sqrt(channel_statistics[i].variance-
(channel_statistics[i].mean*channel_statistics[i].mean));
standard_deviation=sqrt(PerceptibleReciprocal((double) channels*
image->columns*image->rows-1.0)*channels*image->columns*image->rows*
standard_deviation*standard_deviation);
channel_statistics[i].standard_deviation=standard_deviation;
for (i=0; i <= (ssize_t) CompositeChannels; 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;
}
channel_statistics[CompositeChannels].mean=0.0;
channel_statistics[CompositeChannels].standard_deviation=0.0;
for (i=0; i < (ssize_t) CompositeChannels; i++)
{
channel_statistics[CompositeChannels].mean+=
channel_statistics[i].mean;
channel_statistics[CompositeChannels].standard_deviation+=
channel_statistics[i].standard_deviation;
}
channel_statistics[CompositeChannels].mean/=(double) channels;
channel_statistics[CompositeChannels].standard_deviation/=(double) channels;
histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram);
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)
% Image *PolynomialImageChannel(const Image *images,
% const size_t number_terms,const ChannelType channel,
% const double *terms,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o images: the image sequence.
%
% o channel: the channel.
%
% 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)
{
Image
*polynomial_image;
polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms,
terms,exception);
return(polynomial_image);
}
MagickExport Image *PolynomialImageChannel(const Image *images,
const ChannelType channel,const size_t number_terms,const double *terms,
ExceptionInfo *exception)
{
#define PolynomialImageTag "Polynomial/Image"
CacheView
*polynomial_view;
Image
*image;
MagickBooleanType
status;
MagickOffsetType
progress;
MagickPixelPacket
**magick_restrict polynomial_pixels,
zero;
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) == MagickFalse)
{
InheritException(exception,&image->exception);
image=DestroyImage(image);
return((Image *) NULL);
}
number_images=GetImageListLength(images);
polynomial_pixels=AcquirePixelThreadSet(images,number_images);
if (polynomial_pixels == (MagickPixelPacket **) NULL)
{
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename);
return((Image *) NULL);
}
/*
Polynomial image pixels.
*/
status=MagickTrue;
progress=0;
GetMagickPixelPacket(images,&zero);
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();
register IndexPacket
*magick_restrict polynomial_indexes;
register MagickPixelPacket
*polynomial_pixel;
register PixelPacket
*magick_restrict q;
register ssize_t
i,
x;
if (status == MagickFalse)
continue;
q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1,
exception);
if (q == (PixelPacket *) NULL)
{
status=MagickFalse;
continue;
}
polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view);
polynomial_pixel=polynomial_pixels[id];
for (x=0; x < (ssize_t) image->columns; x++)
polynomial_pixel[x]=zero;
next=images;
for (i=0; i < (ssize_t) number_images; i++)
{
register const IndexPacket
*indexes;
register const PixelPacket
*p;
if (i >= (ssize_t) number_terms)
break;
image_view=AcquireVirtualCacheView(next,exception);
p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
{
image_view=DestroyCacheView(image_view);
break;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
for (x=0; x < (ssize_t) image->columns; x++)
{
double
coefficient,
degree;
coefficient=terms[i << 1];
degree=terms[(i << 1)+1];
if ((channel & RedChannel) != 0)
polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree);
if ((channel & GreenChannel) != 0)
polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green,
degree);
if ((channel & BlueChannel) != 0)
polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue,
degree);
if ((channel & OpacityChannel) != 0)
polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale*
(QuantumRange-p->opacity),degree);
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x],
degree);
p++;
}
image_view=DestroyCacheView(image_view);
next=GetNextImageInList(next);
}
for (x=0; x < (ssize_t) image->columns; x++)
{
SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red));
SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green));
SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue));
if (image->matte == MagickFalse)
SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
else
SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange*
polynomial_pixel[x].opacity));
if (image->colorspace == CMYKColorspace)
SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange*
polynomial_pixel[x].index));
q++;
}
if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse)
status=MagickFalse;
if (images->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_PolynomialImages)
#endif
proceed=SetImageProgress(images,PolynomialImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
polynomial_view=DestroyCacheView(polynomial_view);
polynomial_pixels=DestroyPixelThreadSet(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)
% Image *StatisticImageChannel(const Image *image,
% const ChannelType channel,const StatisticType type,
% const size_t width,const size_t height,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o channel: the image channel.
%
% 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.
%
*/
#define ListChannels 5
typedef struct _ListNode
{
size_t
next[9],
count,
signature;
} ListNode;
typedef struct _SkipList
{
ssize_t
level;
ListNode
*nodes;
} SkipList;
typedef struct _PixelList
{
size_t
length,
seed,
signature;
SkipList
lists[ListChannels];
} PixelList;
static PixelList *DestroyPixelList(PixelList *pixel_list)
{
register ssize_t
i;
if (pixel_list == (PixelList *) NULL)
return((PixelList *) NULL);
for (i=0; i < ListChannels; i++)
if (pixel_list->lists[i].nodes != (ListNode *) NULL)
pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory(
pixel_list->lists[i].nodes);
pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list);
return(pixel_list);
}
static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list)
{
register 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;
register ssize_t
i;
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;
for (i=0; i < ListChannels; i++)
{
pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL,
sizeof(*pixel_list->lists[i].nodes));
if (pixel_list->lists[i].nodes == (ListNode *) NULL)
return(DestroyPixelList(pixel_list));
(void) memset(pixel_list->lists[i].nodes,0,65537UL*
sizeof(*pixel_list->lists[i].nodes));
}
pixel_list->signature=MagickCoreSignature;
return(pixel_list);
}
static PixelList **AcquirePixelListThreadSet(const size_t width,
const size_t height)
{
PixelList
**pixel_list;
register 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 ssize_t channel,
const size_t color)
{
register SkipList
*list;
register ssize_t
level;
size_t
search,
update[9];
/*
Initialize the node.
*/
list=pixel_list->lists+channel;
list->nodes[color].signature=pixel_list->signature;
list->nodes[color].count=1;
/*
Determine where it belongs in the list.
*/
search=65536UL;
for (level=list->level; level >= 0; level--)
{
while (list->nodes[search].next[level] < color)
search=list->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 > (list->level+2))
level=list->level+2;
/*
If we're raising the list's level, link back to the root node.
*/
while (level > list->level)
{
list->level++;
update[list->level]=65536UL;
}
/*
Link the node into the skip-list.
*/
do
{
list->nodes[color].next[level]=list->nodes[update[level]].next[level];
list->nodes[update[level]].next[level]=color;
} while (level-- > 0);
}
static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
maximum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the maximum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
maximum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color > maximum)
maximum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) maximum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the mean value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the median value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
do
{
color=list->nodes[color].next[0];
count+=list->nodes[color].count;
} while (count <= (ssize_t) (pixel_list->length >> 1));
channels[channel]=(unsigned short) color;
}
GetMagickPixelPacket((const Image *) NULL,pixel);
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
minimum;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the minimum value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
count=0;
color=65536UL;
minimum=list->nodes[color].next[0];
do
{
color=list->nodes[color].next[0];
if (color < minimum)
minimum=color;
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) minimum;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
max_count,
mode;
ssize_t
count;
unsigned short
channels[5];
/*
Make each pixel the 'predominant color' of the specified neighborhood.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
mode=color;
max_count=list->nodes[mode].count;
count=0;
do
{
color=list->nodes[color].next[0];
if (list->nodes[color].count > max_count)
{
mode=color;
max_count=list->nodes[mode].count;
}
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
channels[channel]=(unsigned short) mode;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel)
{
register SkipList
*list;
register ssize_t
channel;
size_t
color,
next,
previous;
ssize_t
count;
unsigned short
channels[5];
/*
Finds the non peak value for each of the colors.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
next=list->nodes[color].next[0];
count=0;
do
{
previous=color;
color=next;
next=list->nodes[color].next[0];
count+=list->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;
channels[channel]=(unsigned short) color;
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetRootMeanSquarePixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the root mean square value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
do
{
color=list->nodes[color].next[0];
sum+=(MagickRealType) (list->nodes[color].count*color*color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum);
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static void GetStandardDeviationPixelList(PixelList *pixel_list,
MagickPixelPacket *pixel)
{
MagickRealType
sum,
sum_squared;
register SkipList
*list;
register ssize_t
channel;
size_t
color;
ssize_t
count;
unsigned short
channels[ListChannels];
/*
Find the standard-deviation value for each of the color.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
color=65536L;
count=0;
sum=0.0;
sum_squared=0.0;
do
{
register ssize_t
i;
color=list->nodes[color].next[0];
sum+=(MagickRealType) list->nodes[color].count*color;
for (i=0; i < (ssize_t) list->nodes[color].count; i++)
sum_squared+=((MagickRealType) color)*((MagickRealType) color);
count+=list->nodes[color].count;
} while (count < (ssize_t) pixel_list->length);
sum/=pixel_list->length;
sum_squared/=pixel_list->length;
channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum));
}
pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]);
pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]);
pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]);
pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]);
pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]);
}
static inline void InsertPixelList(const Image *image,const PixelPacket *pixel,
const IndexPacket *indexes,PixelList *pixel_list)
{
size_t
signature;
unsigned short
index;
index=ScaleQuantumToShort(GetPixelRed(pixel));
signature=pixel_list->lists[0].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[0].nodes[index].count++;
else
AddNodePixelList(pixel_list,0,index);
index=ScaleQuantumToShort(GetPixelGreen(pixel));
signature=pixel_list->lists[1].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[1].nodes[index].count++;
else
AddNodePixelList(pixel_list,1,index);
index=ScaleQuantumToShort(GetPixelBlue(pixel));
signature=pixel_list->lists[2].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[2].nodes[index].count++;
else
AddNodePixelList(pixel_list,2,index);
index=ScaleQuantumToShort(GetPixelOpacity(pixel));
signature=pixel_list->lists[3].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[3].nodes[index].count++;
else
AddNodePixelList(pixel_list,3,index);
if (image->colorspace == CMYKColorspace)
index=ScaleQuantumToShort(GetPixelIndex(indexes));
signature=pixel_list->lists[4].nodes[index].signature;
if (signature == pixel_list->signature)
pixel_list->lists[4].nodes[index].count++;
else
AddNodePixelList(pixel_list,4,index);
}
static void ResetPixelList(PixelList *pixel_list)
{
int
level;
register ListNode
*root;
register SkipList
*list;
register ssize_t
channel;
/*
Reset the skip-list.
*/
for (channel=0; channel < 5; channel++)
{
list=pixel_list->lists+channel;
root=list->nodes+65536UL;
list->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)
{
Image
*statistic_image;
statistic_image=StatisticImageChannel(image,DefaultChannels,type,width,
height,exception);
return(statistic_image);
}
MagickExport Image *StatisticImageChannel(const Image *image,
const ChannelType channel,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;
size_t
neighbor_height,
neighbor_width;
ssize_t
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);
if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse)
{
InheritException(exception,&statistic_image->exception);
statistic_image=DestroyImage(statistic_image);
return((Image *) NULL);
}
neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) :
width;
neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) :
height;
pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height);
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.
*/
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();
register const IndexPacket
*magick_restrict indexes;
register const PixelPacket
*magick_restrict p;
register IndexPacket
*magick_restrict statistic_indexes;
register PixelPacket
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y-
(ssize_t) (neighbor_height/2L),image->columns+neighbor_width,
neighbor_height,exception);
q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception);
if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL))
{
status=MagickFalse;
continue;
}
indexes=GetCacheViewVirtualIndexQueue(image_view);
statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view);
for (x=0; x < (ssize_t) statistic_image->columns; x++)
{
MagickPixelPacket
pixel;
register const IndexPacket
*magick_restrict s;
register const PixelPacket
*magick_restrict r;
register ssize_t
u,
v;
r=p;
s=indexes+x;
ResetPixelList(pixel_list[id]);
for (v=0; v < (ssize_t) neighbor_height; v++)
{
for (u=0; u < (ssize_t) neighbor_width; u++)
InsertPixelList(image,r+u,s+u,pixel_list[id]);
r+=image->columns+neighbor_width;
s+=image->columns+neighbor_width;
}
GetMagickPixelPacket(image,&pixel);
SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+
neighbor_width*neighbor_height/2,&pixel);
switch (type)
{
case GradientStatistic:
{
MagickPixelPacket
maximum,
minimum;
GetMinimumPixelList(pixel_list[id],&pixel);
minimum=pixel;
GetMaximumPixelList(pixel_list[id],&pixel);
maximum=pixel;
pixel.red=MagickAbsoluteValue(maximum.red-minimum.red);
pixel.green=MagickAbsoluteValue(maximum.green-minimum.green);
pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue);
pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity);
if (image->colorspace == CMYKColorspace)
pixel.index=MagickAbsoluteValue(maximum.index-minimum.index);
break;
}
case MaximumStatistic:
{
GetMaximumPixelList(pixel_list[id],&pixel);
break;
}
case MeanStatistic:
{
GetMeanPixelList(pixel_list[id],&pixel);
break;
}
case MedianStatistic:
default:
{
GetMedianPixelList(pixel_list[id],&pixel);
break;
}
case MinimumStatistic:
{
GetMinimumPixelList(pixel_list[id],&pixel);
break;
}
case ModeStatistic:
{
GetModePixelList(pixel_list[id],&pixel);
break;
}
case NonpeakStatistic:
{
GetNonpeakPixelList(pixel_list[id],&pixel);
break;
}
case RootMeanSquareStatistic:
{
GetRootMeanSquarePixelList(pixel_list[id],&pixel);
break;
}
case StandardDeviationStatistic:
{
GetStandardDeviationPixelList(pixel_list[id],&pixel);
break;
}
}
if ((channel & RedChannel) != 0)
SetPixelRed(q,ClampToQuantum(pixel.red));
if ((channel & GreenChannel) != 0)
SetPixelGreen(q,ClampToQuantum(pixel.green));
if ((channel & BlueChannel) != 0)
SetPixelBlue(q,ClampToQuantum(pixel.blue));
if ((channel & OpacityChannel) != 0)
SetPixelOpacity(q,ClampToQuantum(pixel.opacity));
if (((channel & IndexChannel) != 0) &&
(image->colorspace == CMYKColorspace))
SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index));
p++;
q++;
}
if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_StatisticImage)
#endif
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);
}
|
paint.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% PPPP AAA IIIII N N TTTTT %
% P P A A I NN N T %
% PPPP AAAAA I N N N T %
% P A A I N NN T %
% P A A IIIII N N T %
% %
% %
% Methods to Paint on an Image %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/artifact.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/gem-private.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/resource_.h"
#include "MagickCore/statistic.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% F l o o d f i l l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% FloodfillPaintImage() changes the color value of any pixel that matches
% target and is an immediate neighbor. If the method FillToBorderMethod is
% specified, the color value is changed for any neighbor pixel that does not
% match the bordercolor member of image.
%
% By default target must match a particular pixel color exactly. However,
% in many cases two colors may differ by a small amount. The fuzz member of
% image defines how much tolerance is acceptable to consider two colors as
% the same. For example, set fuzz to 10 and the color red at intensities of
% 100 and 102 respectively are now interpreted as the same color for the
% purposes of the floodfill.
%
% The format of the FloodfillPaintImage method is:
%
% MagickBooleanType FloodfillPaintImage(Image *image,
% const DrawInfo *draw_info,const PixelInfo target,
% const ssize_t x_offset,const ssize_t y_offset,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o target: the RGB value of the target color.
%
% o x_offset,y_offset: the starting location of the operation.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType FloodfillPaintImage(Image *image,
const DrawInfo *draw_info,const PixelInfo *target,const ssize_t x_offset,
const ssize_t y_offset,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define MaxStacksize 524288UL
#define PushSegmentStack(up,left,right,delta) \
{ \
if (s >= (segment_stack+MaxStacksize)) \
ThrowBinaryException(DrawError,"SegmentStackOverflow",image->filename) \
else \
{ \
if ((((up)+(delta)) >= 0) && (((up)+(delta)) < (ssize_t) image->rows)) \
{ \
s->x1=(double) (left); \
s->y1=(double) (up); \
s->x2=(double) (right); \
s->y2=(double) (delta); \
s++; \
} \
} \
}
CacheView
*floodplane_view,
*image_view;
Image
*floodplane_image;
MagickBooleanType
skip,
status;
MemoryInfo
*segment_info;
PixelInfo
fill_color,
pixel;
register SegmentInfo
*s;
SegmentInfo
*segment_stack;
ssize_t
offset,
start,
x1,
x2,
y;
/*
Check boundary conditions.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns))
return(MagickFalse);
if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows))
return(MagickFalse);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (IsGrayColorspace(image->colorspace) != MagickFalse)
(void) SetImageColorspace(image,sRGBColorspace,exception);
if ((image->alpha_trait == UndefinedPixelTrait) &&
(draw_info->fill.alpha_trait != UndefinedPixelTrait))
(void) SetImageAlpha(image,OpaqueAlpha,exception);
/*
Set floodfill state.
*/
floodplane_image=CloneImage(image,image->columns,image->rows,MagickTrue,
exception);
if (floodplane_image == (Image *) NULL)
return(MagickFalse);
floodplane_image->alpha_trait=UndefinedPixelTrait;
floodplane_image->colorspace=GRAYColorspace;
(void) QueryColorCompliance("#000",AllCompliance,
&floodplane_image->background_color,exception);
(void) SetImageBackgroundColor(floodplane_image,exception);
segment_info=AcquireVirtualMemory(MaxStacksize,sizeof(*segment_stack));
if (segment_info == (MemoryInfo *) NULL)
{
floodplane_image=DestroyImage(floodplane_image);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
segment_stack=(SegmentInfo *) GetVirtualMemoryBlob(segment_info);
/*
Push initial segment on stack.
*/
status=MagickTrue;
start=0;
s=segment_stack;
PushSegmentStack(y_offset,x_offset,x_offset,1);
PushSegmentStack(y_offset+1,x_offset,x_offset,-1);
GetPixelInfo(image,&pixel);
image_view=AcquireVirtualCacheView(image,exception);
floodplane_view=AcquireAuthenticCacheView(floodplane_image,exception);
while (s > segment_stack)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
/*
Pop segment off stack.
*/
s--;
x1=(ssize_t) s->x1;
x2=(ssize_t) s->x2;
offset=(ssize_t) s->y2;
y=(ssize_t) s->y1+offset;
/*
Recolor neighboring pixels.
*/
p=GetCacheViewVirtualPixels(image_view,0,y,(size_t) (x1+1),1,exception);
q=GetCacheViewAuthenticPixels(floodplane_view,0,y,(size_t) (x1+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
p+=x1*GetPixelChannels(image);
q+=x1*GetPixelChannels(floodplane_image);
for (x=x1; x >= 0; x--)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p-=GetPixelChannels(image);
q-=GetPixelChannels(floodplane_image);
}
if (SyncCacheViewAuthenticPixels(floodplane_view,exception) == MagickFalse)
break;
skip=x >= x1 ? MagickTrue : MagickFalse;
if (skip == MagickFalse)
{
start=x+1;
if (start < x1)
PushSegmentStack(y,start,x1-1,-offset);
x=x1+1;
}
do
{
if (skip == MagickFalse)
{
if (x < (ssize_t) image->columns)
{
p=GetCacheViewVirtualPixels(image_view,x,y,image->columns-x,1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,image->columns-
x,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) == invert)
break;
SetPixelGray(floodplane_image,QuantumRange,q);
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
status=SyncCacheViewAuthenticPixels(floodplane_view,exception);
if (status == MagickFalse)
break;
}
PushSegmentStack(y,start,x-1,offset);
if (x > (x2+1))
PushSegmentStack(y,x2+1,x-1,-offset);
}
skip=MagickFalse;
x++;
if (x <= x2)
{
p=GetCacheViewVirtualPixels(image_view,x,y,(size_t) (x2-x+1),1,
exception);
q=GetCacheViewAuthenticPixels(floodplane_view,x,y,(size_t) (x2-x+1),1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
break;
for ( ; x <= x2; x++)
{
if (GetPixelGray(floodplane_image,q) != 0)
break;
GetPixelInfoPixel(image,p,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
break;
p+=GetPixelChannels(image);
q+=GetPixelChannels(floodplane_image);
}
}
start=x;
} while (x <= x2);
}
status=MagickTrue;
for (y=0; y < (ssize_t) image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register ssize_t
x;
/*
Tile fill color onto floodplane.
*/
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(floodplane_view,0,y,image->columns,1,exception);
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelGray(floodplane_image,p) != 0)
{
GetFillColor(draw_info,x,y,&fill_color,exception);
SetPixelViaPixelInfo(image,&fill_color,q);
}
p+=GetPixelChannels(floodplane_image);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
floodplane_view=DestroyCacheView(floodplane_view);
image_view=DestroyCacheView(image_view);
segment_info=RelinquishVirtualMemory(segment_info);
floodplane_image=DestroyImage(floodplane_image);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GradientImage() applies a continuously smooth color transitions along a
% vector from one color to another.
%
% Note, the interface of this method will change in the future to support
% more than one transistion.
%
% The format of the GradientImage method is:
%
% MagickBooleanType GradientImage(Image *image,const GradientType type,
% const SpreadMethod method,const PixelInfo *start_color,
% const PixelInfo *stop_color,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o type: the gradient type: linear or radial.
%
% o spread: the gradient spread meathod: pad, reflect, or repeat.
%
% o start_color: the start color.
%
% o stop_color: the stop color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType GradientImage(Image *image,
const GradientType type,const SpreadMethod method,const StopInfo *stops,
const size_t number_stops,ExceptionInfo *exception)
{
const char
*artifact;
DrawInfo
*draw_info;
GradientInfo
*gradient;
MagickBooleanType
status;
/*
Set gradient start-stop end points.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(stops != (const StopInfo *) NULL);
assert(number_stops > 0);
draw_info=AcquireDrawInfo();
gradient=(&draw_info->gradient);
gradient->type=type;
gradient->bounding_box.width=image->columns;
gradient->bounding_box.height=image->rows;
artifact=GetImageArtifact(image,"gradient:bounding-box");
if (artifact != (const char *) NULL)
(void) ParseAbsoluteGeometry(artifact,&gradient->bounding_box);
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
artifact=GetImageArtifact(image,"gradient:direction");
if (artifact != (const char *) NULL)
{
GravityType
direction;
direction=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,artifact);
switch (direction)
{
case NorthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case NorthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=(double) image->rows-1;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case WestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=0.0;
break;
}
case EastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=0.0;
break;
}
case SouthWestGravity:
{
gradient->gradient_vector.x1=(double) image->columns-1;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
case SouthGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=0.0;
gradient->gradient_vector.y2=(double) image->columns-1;
break;
}
case SouthEastGravity:
{
gradient->gradient_vector.x1=0.0;
gradient->gradient_vector.y1=0.0;
gradient->gradient_vector.x2=(double) image->columns-1;
gradient->gradient_vector.y2=(double) image->rows-1;
break;
}
default:
break;
}
}
artifact=GetImageArtifact(image,"gradient:angle");
if (artifact != (const char *) NULL)
gradient->angle=StringToDouble(artifact,(char **) NULL);
artifact=GetImageArtifact(image,"gradient:vector");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf",
&gradient->gradient_vector.x1,&gradient->gradient_vector.y1,
&gradient->gradient_vector.x2,&gradient->gradient_vector.y2);
if ((GetImageArtifact(image,"gradient:angle") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:direction") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:extent") == (const char *) NULL) &&
(GetImageArtifact(image,"gradient:vector") == (const char *) NULL))
if ((type == LinearGradient) && (gradient->gradient_vector.y2 != 0.0))
gradient->gradient_vector.x2=0.0;
gradient->center.x=(double) gradient->gradient_vector.x2/2.0;
gradient->center.y=(double) gradient->gradient_vector.y2/2.0;
artifact=GetImageArtifact(image,"gradient:center");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->center.x,
&gradient->center.y);
artifact=GetImageArtifact(image,"gradient:angle");
if ((type == LinearGradient) && (artifact != (const char *) NULL))
{
double
sine,
cosine,
distance;
/*
Reference https://drafts.csswg.org/css-images-3/#linear-gradients.
*/
sine=sin((double) DegreesToRadians(gradient->angle-90.0));
cosine=cos((double) DegreesToRadians(gradient->angle-90.0));
distance=fabs((double) image->columns*cosine)+
fabs((double) image->rows*sine);
gradient->gradient_vector.x1=0.5*(image->columns-distance*cosine);
gradient->gradient_vector.y1=0.5*(image->rows-distance*sine);
gradient->gradient_vector.x2=0.5*(image->columns+distance*cosine);
gradient->gradient_vector.y2=0.5*(image->rows+distance*sine);
}
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
artifact=GetImageArtifact(image,"gradient:extent");
if (artifact != (const char *) NULL)
{
if (LocaleCompare(artifact,"Circle") == 0)
{
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Diagonal") == 0)
{
gradient->radii.x=(double) (sqrt(image->columns*image->columns+
image->rows*image->rows))/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Ellipse") == 0)
{
gradient->radii.x=(double) image->columns/2.0;
gradient->radii.y=(double) image->rows/2.0;
}
if (LocaleCompare(artifact,"Maximum") == 0)
{
gradient->radii.x=(double) MagickMax(image->columns,image->rows)/2.0;
gradient->radii.y=gradient->radii.x;
}
if (LocaleCompare(artifact,"Minimum") == 0)
{
gradient->radii.x=(double) (MagickMin(image->columns,image->rows))/
2.0;
gradient->radii.y=gradient->radii.x;
}
}
artifact=GetImageArtifact(image,"gradient:radii");
if (artifact != (const char *) NULL)
(void) sscanf(artifact,"%lf%*[ ,]%lf",&gradient->radii.x,
&gradient->radii.y);
gradient->radius=MagickMax(gradient->radii.x,gradient->radii.y);
gradient->spread=method;
/*
Define the gradient to fill between the stops.
*/
gradient->number_stops=number_stops;
gradient->stops=(StopInfo *) AcquireQuantumMemory(gradient->number_stops,
sizeof(*gradient->stops));
if (gradient->stops == (StopInfo *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
(void) CopyMagickMemory(gradient->stops,stops,(size_t) number_stops*
sizeof(*stops));
/*
Draw a gradient on the image.
*/
status=DrawGradientImage(image,draw_info,exception);
draw_info=DestroyDrawInfo(draw_info);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O i l P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OilPaintImage() applies a special effect filter that simulates an oil
% painting. Each pixel is replaced by the most frequent color occurring
% in a circular region defined by radius.
%
% The format of the OilPaintImage method is:
%
% Image *OilPaintImage(const Image *image,const double radius,
% const double sigma,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o radius: the radius of the circular neighborhood.
%
% o sigma: the standard deviation of the Gaussian, in pixels.
%
% o exception: return any errors or warnings in this structure.
%
*/
static size_t **DestroyHistogramThreadSet(size_t **histogram)
{
register ssize_t
i;
assert(histogram != (size_t **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (histogram[i] != (size_t *) NULL)
histogram[i]=(size_t *) RelinquishMagickMemory(histogram[i]);
histogram=(size_t **) RelinquishMagickMemory(histogram);
return(histogram);
}
static size_t **AcquireHistogramThreadSet(const size_t count)
{
register ssize_t
i;
size_t
**histogram,
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
histogram=(size_t **) AcquireQuantumMemory(number_threads,sizeof(*histogram));
if (histogram == (size_t **) NULL)
return((size_t **) NULL);
(void) ResetMagickMemory(histogram,0,number_threads*sizeof(*histogram));
for (i=0; i < (ssize_t) number_threads; i++)
{
histogram[i]=(size_t *) AcquireQuantumMemory(count,sizeof(**histogram));
if (histogram[i] == (size_t *) NULL)
return(DestroyHistogramThreadSet(histogram));
}
return(histogram);
}
MagickExport Image *OilPaintImage(const Image *image,const double radius,
const double sigma,ExceptionInfo *exception)
{
#define NumberPaintBins 256
#define OilPaintImageTag "OilPaint/Image"
CacheView
*image_view,
*paint_view;
Image
*linear_image,
*paint_image;
MagickBooleanType
status;
MagickOffsetType
progress;
size_t
**histograms,
width;
ssize_t
center,
y;
/*
Initialize painted image attributes.
*/
assert(image != (const Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
width=GetOptimalKernelWidth2D(radius,sigma);
linear_image=CloneImage(image,0,0,MagickTrue,exception);
paint_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception);
if ((linear_image == (Image *) NULL) || (paint_image == (Image *) NULL))
{
if (linear_image != (Image *) NULL)
linear_image=DestroyImage(linear_image);
if (paint_image != (Image *) NULL)
linear_image=DestroyImage(paint_image);
return((Image *) NULL);
}
if (SetImageStorageClass(paint_image,DirectClass,exception) == MagickFalse)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
return((Image *) NULL);
}
histograms=AcquireHistogramThreadSet(NumberPaintBins);
if (histograms == (size_t **) NULL)
{
linear_image=DestroyImage(linear_image);
paint_image=DestroyImage(paint_image);
ThrowImageException(ResourceLimitError,"MemoryAllocationFailed");
}
/*
Oil paint image.
*/
status=MagickTrue;
progress=0;
center=(ssize_t) GetPixelChannels(linear_image)*(linear_image->columns+width)*
(width/2L)+GetPixelChannels(linear_image)*(width/2L);
image_view=AcquireVirtualCacheView(linear_image,exception);
paint_view=AcquireAuthenticCacheView(paint_image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(linear_image,paint_image,linear_image->rows,1)
#endif
for (y=0; y < (ssize_t) linear_image->rows; y++)
{
register const Quantum
*magick_restrict p;
register Quantum
*magick_restrict q;
register size_t
*histogram;
register ssize_t
x;
if (status == MagickFalse)
continue;
p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t)
(width/2L),linear_image->columns+width,width,exception);
q=QueueCacheViewAuthenticPixels(paint_view,0,y,paint_image->columns,1,
exception);
if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))
{
status=MagickFalse;
continue;
}
histogram=histograms[GetOpenMPThreadId()];
for (x=0; x < (ssize_t) linear_image->columns; x++)
{
register ssize_t
i,
u;
size_t
count;
ssize_t
j,
k,
n,
v;
/*
Assign most frequent color.
*/
k=0;
j=0;
count=0;
(void) ResetMagickMemory(histogram,0,NumberPaintBins* sizeof(*histogram));
for (v=0; v < (ssize_t) width; v++)
{
for (u=0; u < (ssize_t) width; u++)
{
n=(ssize_t) ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(
linear_image,p+GetPixelChannels(linear_image)*(u+k))));
histogram[n]++;
if (histogram[n] > count)
{
j=k+u;
count=histogram[n];
}
}
k+=(ssize_t) (linear_image->columns+width);
}
for (i=0; i < (ssize_t) GetPixelChannels(linear_image); i++)
{
PixelChannel channel=GetPixelChannelChannel(linear_image,i);
PixelTrait traits=GetPixelChannelTraits(linear_image,channel);
PixelTrait paint_traits=GetPixelChannelTraits(paint_image,channel);
if ((traits == UndefinedPixelTrait) ||
(paint_traits == UndefinedPixelTrait))
continue;
if (((paint_traits & CopyPixelTrait) != 0) ||
(GetPixelWriteMask(linear_image,p) == 0))
{
SetPixelChannel(paint_image,channel,p[center+i],q);
continue;
}
SetPixelChannel(paint_image,channel,p[j*GetPixelChannels(linear_image)+
i],q);
}
p+=GetPixelChannels(linear_image);
q+=GetPixelChannels(paint_image);
}
if (SyncCacheViewAuthenticPixels(paint_view,exception) == MagickFalse)
status=MagickFalse;
if (linear_image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_OilPaintImage)
#endif
proceed=SetImageProgress(linear_image,OilPaintImageTag,progress++,
linear_image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
paint_view=DestroyCacheView(paint_view);
image_view=DestroyCacheView(image_view);
histograms=DestroyHistogramThreadSet(histograms);
linear_image=DestroyImage(linear_image);
if (status == MagickFalse)
paint_image=DestroyImage(paint_image);
return(paint_image);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% O p a q u e P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% OpaquePaintImage() changes any pixel that matches color with the color
% defined by fill argument.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the OpaquePaintImage method is:
%
% MagickBooleanType OpaquePaintImage(Image *image,const PixelInfo *target,
% const PixelInfo *fill,const MagickBooleanType invert,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the RGB value of the target color.
%
% o fill: the replacement color.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType OpaquePaintImage(Image *image,
const PixelInfo *target,const PixelInfo *fill,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define OpaquePaintImageTag "Opaque/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
conform_fill,
conform_target,
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
assert(fill != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
ConformPixelInfo(image,fill,&conform_fill,exception);
ConformPixelInfo(image,target,&conform_target,exception);
/*
Make image color opaque.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&conform_target) != invert)
{
PixelTrait
traits;
traits=GetPixelChannelTraits(image,RedPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelRed(image,conform_fill.red,q);
traits=GetPixelChannelTraits(image,GreenPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelGreen(image,conform_fill.green,q);
traits=GetPixelChannelTraits(image,BluePixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelBlue(image,conform_fill.blue,q);
traits=GetPixelChannelTraits(image,BlackPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelBlack(image,conform_fill.black,q);
traits=GetPixelChannelTraits(image,AlphaPixelChannel);
if ((traits & UpdatePixelTrait) != 0)
SetPixelAlpha(image,conform_fill.alpha,q);
}
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_OpaquePaintImage)
#endif
proceed=SetImageProgress(image,OpaquePaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImage() changes the opacity value associated with any pixel
% that matches color to the value defined by opacity.
%
% By default color must match a particular pixel color exactly. However, in
% many cases two colors may differ by a small amount. Fuzz defines how much
% tolerance is acceptable to consider two colors as the same. For example,
% set fuzz to 10 and the color red at intensities of 100 and 102 respectively
% are now interpreted as the same color.
%
% The format of the TransparentPaintImage method is:
%
% MagickBooleanType TransparentPaintImage(Image *image,
% const PixelInfo *target,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o target: the target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImage(Image *image,
const PixelInfo *target,const Quantum opacity,const MagickBooleanType invert,
ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
PixelInfo
zero;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(target != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
status=MagickTrue;
progress=0;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
PixelInfo
pixel;
register ssize_t
x;
register Quantum
*magick_restrict q;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,target) != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransparentPaintImage)
#endif
proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% T r a n s p a r e n t P a i n t I m a g e C h r o m a %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TransparentPaintImageChroma() changes the opacity value associated with any
% pixel that matches color to the value defined by opacity.
%
% As there is one fuzz value for the all the channels, TransparentPaintImage()
% is not suitable for the operations like chroma, where the tolerance for
% similarity of two color component (RGB) can be different. Thus we define
% this method to take two target pixels (one low and one high) and all the
% pixels of an image which are lying between these two pixels are made
% transparent.
%
% The format of the TransparentPaintImageChroma method is:
%
% MagickBooleanType TransparentPaintImageChroma(Image *image,
% const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
% const MagickBooleanType invert,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o low: the low target color.
%
% o high: the high target color.
%
% o opacity: the replacement opacity value.
%
% o invert: paint any pixel that does not match the target color.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType TransparentPaintImageChroma(Image *image,
const PixelInfo *low,const PixelInfo *high,const Quantum opacity,
const MagickBooleanType invert,ExceptionInfo *exception)
{
#define TransparentPaintImageTag "Transparent/Image"
CacheView
*image_view;
MagickBooleanType
status;
MagickOffsetType
progress;
ssize_t
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
assert(high != (PixelInfo *) NULL);
assert(low != (PixelInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
/*
Make image color transparent.
*/
status=MagickTrue;
progress=0;
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static,4) shared(progress,status) \
magick_threads(image,image,image->rows,1)
#endif
for (y=0; y < (ssize_t) image->rows; y++)
{
MagickBooleanType
match;
PixelInfo
pixel;
register Quantum
*magick_restrict q;
register ssize_t
x;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelWriteMask(image,q) == 0)
{
q+=GetPixelChannels(image);
continue;
}
GetPixelInfoPixel(image,q,&pixel);
match=((pixel.red >= low->red) && (pixel.red <= high->red) &&
(pixel.green >= low->green) && (pixel.green <= high->green) &&
(pixel.blue >= low->blue) && (pixel.blue <= high->blue)) ? MagickTrue :
MagickFalse;
if (match != invert)
SetPixelAlpha(image,opacity,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
MagickBooleanType
proceed;
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (MagickCore_TransparentPaintImageChroma)
#endif
proceed=SetImageProgress(image,TransparentPaintImageTag,progress++,
image->rows);
if (proceed == MagickFalse)
status=MagickFalse;
}
}
image_view=DestroyCacheView(image_view);
return(status);
}
|
variable_utils.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Riccardo Rossi
// Ruben Zorrilla
// Vicente Mataix Ferrandiz
//
//
#if !defined(KRATOS_VARIABLE_UTILS )
#define KRATOS_VARIABLE_UTILS
/* System includes */
/* External includes */
/* Project includes */
#include "includes/define.h"
#include "includes/model_part.h"
#include "includes/checks.h"
#include "utilities/parallel_utilities.h"
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @class VariableUtils
* @ingroup KratosCore
* @brief This class implements a set of auxiliar, already parallelized, methods to
* perform some common tasks related with the variable values and fixity.
* @details The methods are exported to python in order to add this improvements to the python interface
* @author Riccardo Rossi
* @author Ruben Zorrilla
* @author Vicente Mataix Ferrandiz
*/
class KRATOS_API(KRATOS_CORE) VariableUtils
{
public:
///@name Type Definitions
///@{
/// The node type
typedef ModelPart::NodeType NodeType;
/// The condition type
typedef ModelPart::ConditionType ConditionType;
/// The element type
typedef ModelPart::ElementType ElementType;
/// We create the Pointer related to VariableUtils
KRATOS_CLASS_POINTER_DEFINITION(VariableUtils);
/// The nodes container
typedef ModelPart::NodesContainerType NodesContainerType;
/// The conditions container
typedef ModelPart::ConditionsContainerType ConditionsContainerType;
/// The elements container
typedef ModelPart::ElementsContainerType ElementsContainerType;
/// A definition of the double variable
typedef Variable< double > DoubleVarType;
/// A definition of the array variable
typedef Variable< array_1d<double, 3 > > ArrayVarType;
///@}
///@name Life Cycle
///@{
/** Constructor.
*/
/** Destructor.
*/
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief Copies the nodal value of a variable from an origin model
* part nodes to the nodes in a destination model part. It is assumed that
* both origin and destination model parts have the same number of nodes.
* @param rVariable reference to the variable to get the value from
* @param rDestinationVariable reference to the variable to be set
* @param rOriginModelPart origin model part from where the values are retrieved
* @param rDestinationModelPart destination model part to where the values are copied to
* @param BuffStep buffer step
*/
template< class TVarType >
void CopyModelPartNodalVar(
const TVarType& rVariable,
const TVarType& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const unsigned int BuffStep = 0)
{
const int n_orig_nodes = rOriginModelPart.NumberOfNodes();
const int n_dest_nodes = rDestinationModelPart.NumberOfNodes();
KRATOS_ERROR_IF_NOT(n_orig_nodes == n_dest_nodes) << "Origin and destination model parts have different number of nodes."
<< "\n\t- Number of origin nodes: " << n_orig_nodes
<< "\n\t- Number of destination nodes: " << n_dest_nodes << std::endl;
#pragma omp parallel for
for(int i_node = 0; i_node < n_orig_nodes; ++i_node){
auto it_dest_node = rDestinationModelPart.NodesBegin() + i_node;
const auto &it_orig_node = rOriginModelPart.NodesBegin() + i_node;
const auto &r_value = it_orig_node->GetSolutionStepValue(rVariable, BuffStep);
it_dest_node->GetSolutionStepValue(rDestinationVariable, BuffStep) = r_value;
}
}
/**
* @brief Copies the nodal value of a variable from an origin model
* part nodes to the nodes in a destination model part. It is assumed that
* both origin and destination model parts have the same number of nodes.
* @param rVariable reference to the variable to get the value from and to save in
* @param rOriginModelPart origin model part from where the values are retrieved
* @param rDestinationModelPart destination model part to where the values are copied to
* @param BuffStep buffer step
*/
template< class TVarType >
void CopyModelPartNodalVar(
const TVarType& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const unsigned int BuffStep = 0)
{
this->CopyModelPartNodalVar(rVariable, rVariable, rOriginModelPart, rDestinationModelPart, BuffStep);
}
template< class TVarType >
void CopyModelPartNodalVarToNonHistoricalVar(
const TVarType &rVariable,
const TVarType &rDestinationVariable,
const ModelPart &rOriginModelPart,
ModelPart &rDestinationModelPart,
const unsigned int BuffStep = 0)
{
const int n_orig_nodes = rOriginModelPart.NumberOfNodes();
const int n_dest_nodes = rDestinationModelPart.NumberOfNodes();
KRATOS_ERROR_IF_NOT(n_orig_nodes == n_dest_nodes) <<
"Origin and destination model parts have different number of nodes." <<
"\n\t- Number of origin nodes: " << n_orig_nodes <<
"\n\t- Number of destination nodes: " << n_dest_nodes << std::endl;
#pragma omp parallel for
for(int i_node = 0; i_node < n_orig_nodes; ++i_node){
auto it_dest_node = rDestinationModelPart.NodesBegin() + i_node;
const auto &it_orig_node = rOriginModelPart.NodesBegin() + i_node;
const auto &r_value = it_orig_node->GetSolutionStepValue(rVariable, BuffStep);
it_dest_node->GetValue(rDestinationVariable) = r_value;
}
}
template< class TVarType >
void CopyModelPartNodalVarToNonHistoricalVar(
const TVarType &rVariable,
const ModelPart &rOriginModelPart,
ModelPart &rDestinationModelPart,
const unsigned int BuffStep = 0)
{
this->CopyModelPartNodalVarToNonHistoricalVar(rVariable, rVariable, rOriginModelPart, rDestinationModelPart, BuffStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0,
const unsigned int WriteBufferStep = 0)
{
KRATOS_TRY
KRATOS_ERROR_IF(
rOriginModelPart.FullName() == rDestinationModelPart.FullName() &&
rOriginVariable == rDestinationVariable &&
ReadBufferStep == WriteBufferStep)
<< "Trying to copy flagged nodal solution step values with the same origin and destination model parts/variables/buffer steps. This is not permitted ( Origin model part: "
<< rOriginModelPart.Name() << ", destination model part: " << rDestinationModelPart.Name()
<< ", variable: " << rOriginVariable.Name() << ", buffer step: " << ReadBufferStep << " ) !";
KRATOS_ERROR_IF_NOT(rOriginModelPart.HasNodalSolutionStepVariable(rOriginVariable))
<< rOriginVariable.Name() << " is not found in nodal solution step variables list in origin model part ( "
<< rOriginModelPart.Name() << " ).";
KRATOS_ERROR_IF_NOT(rDestinationModelPart.HasNodalSolutionStepVariable(rDestinationVariable))
<< rDestinationVariable.Name() << " is not found in nodal solution step variables list in destination model part ( "
<< rDestinationModelPart.Name() << " ).";
KRATOS_ERROR_IF(ReadBufferStep >= rOriginModelPart.GetBufferSize())
<< "Origin model part ( " << rOriginModelPart.Name()
<< " ) buffer size is smaller or equal than read buffer size [ "
<< rOriginModelPart.GetBufferSize() << " <= " << ReadBufferStep << " ].";
KRATOS_ERROR_IF(WriteBufferStep >= rDestinationModelPart.GetBufferSize())
<< "Destination model part ( " << rDestinationModelPart.Name()
<< " ) buffer size is smaller or equal than read buffer size [ "
<< rDestinationModelPart.GetBufferSize() << " <= " << WriteBufferStep << " ].";
CopyModelPartFlaggedVariable<NodesContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](NodeType& rDestNode, const TDataType& rValue) {
rDestNode.FastGetSolutionStepValue(
rDestinationVariable, WriteBufferStep) = rValue;
},
[&](const NodeType& rOriginNode) -> const TDataType& {
return rOriginNode.FastGetSolutionStepValue(rOriginVariable, ReadBufferStep);
});
rDestinationModelPart.GetCommunicator().SynchronizeVariable(rDestinationVariable);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0,
const unsigned int WriteBufferStep = 0)
{
KRATOS_TRY
CopyModelPartFlaggedNodalHistoricalVarToHistoricalVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart,
rFlag, CheckValue, ReadBufferStep, WriteBufferStep);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToHistoricalVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0,
const unsigned int WriteBufferStep = 0)
{
KRATOS_TRY
CopyModelPartFlaggedNodalHistoricalVarToHistoricalVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart,
rFlag, CheckValue, ReadBufferStep, WriteBufferStep);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0)
{
KRATOS_TRY
KRATOS_ERROR_IF_NOT(rOriginModelPart.HasNodalSolutionStepVariable(rOriginVariable))
<< rOriginVariable.Name() << " is not found in nodal solution step variables list in origin model part ( "
<< rOriginModelPart.Name() << " ).";
KRATOS_ERROR_IF(ReadBufferStep >= rOriginModelPart.GetBufferSize())
<< "Origin model part ( " << rOriginModelPart.Name()
<< " ) buffer size is smaller or equal than read buffer size [ "
<< rOriginModelPart.GetBufferSize() << " <= " << ReadBufferStep << " ].";
CopyModelPartFlaggedVariable<NodesContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](NodeType& rDestNode, const TDataType& rValue) {
rDestNode.SetValue(rDestinationVariable, rValue);
},
[&](const NodeType& rOriginNode) -> const TDataType& {
return rOriginNode.FastGetSolutionStepValue(rOriginVariable, ReadBufferStep);
});
rDestinationModelPart.GetCommunicator().SynchronizeNonHistoricalVariable(rDestinationVariable);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0)
{
CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart,
rFlag, CheckValue, ReadBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0)
{
CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart,
rFlag, CheckValue, ReadBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int ReadBufferStep = 0)
{
CopyModelPartFlaggedNodalHistoricalVarToNonHistoricalVar(
rVariable, rVariable, rModelPart, rModelPart,
rFlag, CheckValue, ReadBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int WriteBufferStep = 0)
{
KRATOS_TRY
KRATOS_ERROR_IF_NOT(rDestinationModelPart.HasNodalSolutionStepVariable(rDestinationVariable))
<< rDestinationVariable.Name() << " is not found in nodal solution step variables list in destination model part ( "
<< rDestinationModelPart.Name() << " ).";
KRATOS_ERROR_IF(WriteBufferStep >= rDestinationModelPart.GetBufferSize())
<< "Destination model part ( " << rDestinationModelPart.Name()
<< " ) buffer size is smaller or equal than read buffer size [ "
<< rDestinationModelPart.GetBufferSize() << " <= " << WriteBufferStep << " ].";
CopyModelPartFlaggedVariable<NodesContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](NodeType& rDestNode, const TDataType& rValue) {
rDestNode.FastGetSolutionStepValue(
rDestinationVariable, WriteBufferStep) = rValue;
},
[&](const NodeType& rOriginNode) -> const TDataType& {
return rOriginNode.GetValue(rOriginVariable);
});
rDestinationModelPart.GetCommunicator().SynchronizeVariable(rDestinationVariable);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int WriteBufferStep = 0)
{
CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart,
rFlag, CheckValue, WriteBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int WriteBufferStep = 0)
{
CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart,
rFlag, CheckValue, WriteBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
const Variable<TDataType>& rVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true,
const unsigned int WriteBufferStep = 0)
{
CopyModelPartFlaggedNodalNonHistoricalVarToHistoricalVar(
rVariable, rVariable, rModelPart, rModelPart,
rFlag, CheckValue, WriteBufferStep);
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
KRATOS_TRY
KRATOS_ERROR_IF(
rOriginModelPart.FullName() == rDestinationModelPart.FullName() &&
rOriginVariable == rDestinationVariable
) << "Trying to copy flagged nodal non-historical values with the same model parts/variables. This is not permitted ( Origin model part: "
<< rOriginModelPart.Name() << ", destination model part: " << rDestinationModelPart.Name()
<< ", variable: " << rOriginVariable.Name() << " ) !";
CopyModelPartFlaggedVariable<NodesContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](NodeType& rDestNode, const TDataType& rValue) {
rDestNode.SetValue(rDestinationVariable, rValue);
},
[&](const NodeType& rOriginNode) -> const TDataType& {
return rOriginNode.GetValue(rOriginVariable);
});
rDestinationModelPart.GetCommunicator().SynchronizeNonHistoricalVariable(rDestinationVariable);
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedNodalNonHistoricalVarToNonHistoricalVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart, rFlag, CheckValue);
}
template <class TDataType>
void CopyModelPartFlaggedNodalNonHistoricalVarToNonHistoricalVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedNodalNonHistoricalVarToNonHistoricalVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart, rFlag, CheckValue);
}
template <class TDataType>
void CopyModelPartFlaggedElementVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
KRATOS_TRY
KRATOS_ERROR_IF(rOriginModelPart.FullName() == rDestinationModelPart.FullName() && rOriginVariable == rDestinationVariable)
<< "Trying to copy flagged elemental variable data with the same model "
"parts/variables. This is not permitted ( Origin model part: "
<< rOriginModelPart.Name() << ", destination model part: " << rDestinationModelPart.Name()
<< ", variable: " << rOriginVariable.Name() << " ) !";
CopyModelPartFlaggedVariable<ElementsContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](ElementType& rDestElement, const TDataType& rValue) {
rDestElement.SetValue(rDestinationVariable, rValue);
},
[&](const ElementType& rOriginElement) -> const TDataType& {
return rOriginElement.GetValue(rOriginVariable);
});
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedElementVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedElementVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart, rFlag, CheckValue);
}
template <class TDataType>
void CopyModelPartFlaggedElementVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedElementVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart, rFlag, CheckValue);
}
template <class TDataType>
void CopyModelPartFlaggedConditionVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
KRATOS_TRY
KRATOS_ERROR_IF(rOriginModelPart.FullName() == rDestinationModelPart.FullName() && rOriginVariable == rDestinationVariable)
<< "Trying to copy flagged condition variable data with the same model "
"parts/variables. This is not permitted ( Origin model part: "
<< rOriginModelPart.Name() << ", destination model part: " << rDestinationModelPart.Name()
<< ", variable: " << rOriginVariable.Name() << " ) !";
CopyModelPartFlaggedVariable<ConditionsContainerType>(
rOriginModelPart, rDestinationModelPart, rFlag, CheckValue,
[&](ConditionType& rDestCondition, const TDataType& rValue) {
rDestCondition.SetValue(rDestinationVariable, rValue);
},
[&](const ConditionType& rOriginCondition) -> const TDataType& {
return rOriginCondition.GetValue(rOriginVariable);
});
KRATOS_CATCH("");
}
template <class TDataType>
void CopyModelPartFlaggedConditionVar(
const Variable<TDataType>& rOriginVariable,
const Variable<TDataType>& rDestinationVariable,
ModelPart& rModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedConditionVar(
rOriginVariable, rDestinationVariable, rModelPart, rModelPart, rFlag, CheckValue);
}
template <class TDataType>
void CopyModelPartFlaggedConditionVar(
const Variable<TDataType>& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue = true)
{
CopyModelPartFlaggedConditionVar(
rVariable, rVariable, rOriginModelPart, rDestinationModelPart, rFlag, CheckValue);
}
/**
* @brief Copies the elemental value of a variable from an origin model
* part elements to the elements in a destination model part. It is assumed that
* both origin and destination model parts have the same number of elements.
* @param rVariable reference to the variable to be set
* @param rOriginModelPart origin model part from where the values are retrieved
* @param rDestinationModelPart destination model part to where the values are copied to
* @param BuffStep buffer step
*/
template< class TVarType >
void CopyModelPartElementalVar(
const TVarType& rVariable,
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart){
const int n_orig_elems = rOriginModelPart.NumberOfElements();
const int n_dest_elems = rDestinationModelPart.NumberOfElements();
KRATOS_ERROR_IF_NOT(n_orig_elems == n_dest_elems) << "Origin and destination model parts have different number of elements."
<< "\n\t- Number of origin elements: " << n_orig_elems
<< "\n\t- Number of destination elements: " << n_dest_elems << std::endl;
#pragma omp parallel for
for(int i_elems = 0; i_elems < n_orig_elems; ++i_elems){
auto it_dest_elems = rDestinationModelPart.ElementsBegin() + i_elems;
const auto &it_orig_elems = rOriginModelPart.ElementsBegin() + i_elems;
const auto &r_value = it_orig_elems->GetValue(rVariable);
it_dest_elems->SetValue(rVariable,r_value);
}
}
/**
* @brief Sets the nodal value of a scalar variable
* @tparam TDataType Variable data type
* @tparam Variable<TDataType> Variable type
* @param rVariable reference to the scalar variable to be set
* @param Value Value to be set
* @param rNodes reference to the objective node set
*/
template<class TDataType, class TVarType = Variable<TDataType> >
void SetVariable(
const TVarType& rVariable,
const TDataType& rValue,
NodesContainerType& rNodes
)
{
KRATOS_TRY
block_for_each(rNodes, [&](Node<3>& rNode) {
rNode.FastGetSolutionStepValue(rVariable) = rValue;
});
KRATOS_CATCH("")
}
/**
* @brief Sets the nodal value of a scalar variable (considering flag)
* @tparam TDataType Variable data type
* @tparam Variable<TDataType> Variable type
* @param rVariable reference to the scalar variable to be set
* @param rValue Value to be set
* @param rNodes reference to the objective node set
* @param Flag The flag to be considered in the assignation
* @param Check What is checked from the flag
*/
template <class TDataType, class TVarType = Variable<TDataType>>
void SetVariable(
const TVarType &rVariable,
const TDataType &rValue,
NodesContainerType &rNodes,
const Flags Flag,
const bool CheckValue = true)
{
KRATOS_TRY
#pragma omp parallel for
for (int k = 0; k < static_cast<int>(rNodes.size()); ++k)
{
auto it_node = rNodes.begin() + k;
if (it_node->Is(Flag) == CheckValue)
{
it_node->FastGetSolutionStepValue(rVariable) = rValue;
}
}
KRATOS_CATCH("")
}
/**
* @brief Sets the nodal value of any variable to zero
* @param rVariable reference to the scalar variable to be set
* @param rNodes reference to the objective node set
*/
template< class TType , class TContainerType>
void SetNonHistoricalVariableToZero(
const Variable< TType >& rVariable,
TContainerType& rContainer)
{
KRATOS_TRY
this->SetNonHistoricalVariable(rVariable, rVariable.Zero(), rContainer);
KRATOS_CATCH("")
}
/**
* @brief Sets the nodal value of any variable to zero
* @param rVariable reference to the scalar variable to be set
* @param rNodes reference to the objective node set
*/
template< class TType >
void SetHistoricalVariableToZero(
const Variable< TType >& rVariable,
NodesContainerType& rNodes)
{
KRATOS_TRY
this->SetVariable(rVariable, rVariable.Zero(), rNodes);
KRATOS_CATCH("")
}
/**
* @brief Sets the container value of any type of non historical variable
* @param rVariable reference to the scalar variable to be set
* @param Value Value to be set
* @param rContainer Reference to the objective container
*/
template< class TType, class TContainerType, class TVarType = Variable< TType >>
void SetNonHistoricalVariable(
const TVarType& rVariable,
const TType& Value,
TContainerType& rContainer
)
{
KRATOS_TRY
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = rContainer.begin() + k;
it_cont->SetValue(rVariable, Value);
}
KRATOS_CATCH("")
}
/**
* @brief Sets the container value of any type of non historical variable (considering flag)
* @param rVariable reference to the scalar variable to be set
* @param Value Value to be set
* @param rContainer Reference to the objective container
* @param Flag The flag to be considered in the assignation
* @param Check What is checked from the flag
*/
template< class TType, class TContainerType, class TVarType = Variable< TType >>
void SetNonHistoricalVariable(
const TVarType& rVariable,
const TType& rValue,
TContainerType& rContainer,
const Flags Flag,
const bool Check = true
)
{
KRATOS_TRY
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = rContainer.begin() + k;
if (it_cont->Is(Flag) == Check) {
it_cont->SetValue(rVariable, rValue);
}
}
KRATOS_CATCH("")
}
/**
* @brief Clears the container data value container
* @param rContainer Reference to the objective container
*/
template< class TContainerType>
void ClearNonHistoricalData(TContainerType& rContainer)
{
KRATOS_TRY
const auto it_cont_begin = rContainer.begin();
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = it_cont_begin + k;
it_cont->Data().Clear();
}
KRATOS_CATCH("")
}
/**
* @brief Distributes variable values in TContainerType container to nodes
*
* This method distributes variables values stored in TContainerType data value container in rModelPart
* to nodes. Constant weighting is used for each node based on rWeightVariable value. The result
* is stored in nodal non-historical data value container under the same rVariable. If IsInverseWeightProvided
* is true, then the weights provided by rWeightVariable is inverted to get nodal weight. Otherwise, the value
* given by rWeightVariable is used as weight.
*
*
* @tparam TDataType Data type
* @tparam TContainerType ContainerType of model part
* @tparam TWeightDataType Data type of weight variable (this should be either int or double)
* @param rModelPart Model part
* @param rVariable Variable to be distributed
* @param rWeightVariable Variable which holds weight to distribute entity values to nodes
* @param IsInverseWeightProvided Whether the weight is provided as inverse or not.
*/
template <class TDataType, class TContainerType, class TWeightDataType>
void WeightedAccumulateVariableOnNodes(
ModelPart& rModelPart,
const Variable<TDataType>& rVariable,
const Variable<TWeightDataType>& rWeightVariable,
const bool IsInverseWeightProvided = false);
/**
* @brief Sets a flag according to a given status over a given container
* @param rFlag flag to be set
* @param rFlagValue flag value to be set
* @param rContainer Reference to the objective container
*/
template< class TContainerType >
void SetFlag(
const Flags& rFlag,
const bool& rFlagValue,
TContainerType& rContainer
)
{
KRATOS_TRY
const auto it_cont_begin = rContainer.begin();
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = it_cont_begin + k;
it_cont->Set(rFlag, rFlagValue);
}
KRATOS_CATCH("")
}
/**
* @brief Flips a flag over a given container
* @param rFlag flag to be set
* @param rContainer Reference to the objective container
*/
template< class TContainerType >
void ResetFlag(
const Flags& rFlag,
TContainerType& rContainer
)
{
KRATOS_TRY
const auto it_cont_begin = rContainer.begin();
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = it_cont_begin + k;
it_cont->Reset(rFlag);
}
KRATOS_CATCH("")
}
/**
* @brief Flips a flag over a given container
* @param rFlag flag to be set
* @param rContainer Reference to the objective container
*/
template< class TContainerType >
void FlipFlag(
const Flags& rFlag,
TContainerType& rContainer
)
{
KRATOS_TRY
const auto it_cont_begin = rContainer.begin();
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) {
auto it_cont = it_cont_begin + k;
it_cont->Flip(rFlag);
}
KRATOS_CATCH("")
}
/**
* @brief Takes the value of a non-historical variable and saves it in another variable
* For a nodal container, this takes the value of a non-historical variable and saves it in another one
* @tparam TDataType The variable data type
* @tparam Variable<TDataType> The variable type
* @param rOriginVariable Reference to the origin variable
* @param rSavedVariable Reference to the destination variable
* @param rNodesContainer Reference to the nodal container
*/
template< class TDataType, class TVariableType = Variable<TDataType> >
void SaveVariable(
const TVariableType &rOriginVariable,
const TVariableType &rSavedVariable,
NodesContainerType &rNodesContainer)
{
KRATOS_TRY
#pragma omp parallel for
for (int i_node = 0; i_node < static_cast<int>(rNodesContainer.size()); ++i_node) {
auto it_node = rNodesContainer.begin() + i_node;
it_node->SetValue(rSavedVariable, it_node->FastGetSolutionStepValue(rOriginVariable));
}
KRATOS_CATCH("")
}
/**
* @brief Takes the value of a non-historical variable and saves it in another historical variable
* For a non-nodal container, this method takes the value of an origin variable and saves it in a destination one
* @tparam TDataType The variable data type
* @tparam TContainerType The container type
* @tparam Variable<TDataType> The variable type
* @param rOriginVariable Reference to the origin variable
* @param rSavedVariable Reference to the destination variable
* @param rContainer Reference to the container of interest
*/
template< class TDataType, class TContainerType, class TVariableType = Variable<TDataType> >
void SaveNonHistoricalVariable(
const TVariableType &rOriginVariable,
const TVariableType &rSavedVariable,
TContainerType &rContainer
)
{
KRATOS_TRY
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rContainer.size()); ++i) {
auto it_cont = rContainer.begin() + i;
it_cont->SetValue(rSavedVariable, it_cont->GetValue(rOriginVariable));
}
KRATOS_CATCH("")
}
/**
* @brief Takes the value of an historical variable and sets it in another variable
* This function takes the value of an historical variable and sets in another
* variable in all the nodes of the provided container.
* @tparam TDataType The variable data type
* @tparam Variable<TDataType> The variable type
* @param rOriginVariable Reference to the origin variable
* @param rDestinationVariable Reference to the destination variable
* @param rNodesContainer Reference to the nodes container
*/
template< class TDataType, class TVariableType = Variable<TDataType> >
void CopyVariable(
const TVariableType &rOriginVariable,
const TVariableType &rDestinationVariable,
NodesContainerType &rNodesContainer)
{
KRATOS_TRY
#pragma omp parallel for
for (int i_node = 0; i_node < static_cast<int>(rNodesContainer.size()); ++i_node) {
auto it_node = rNodesContainer.begin() + i_node;
it_node->FastGetSolutionStepValue(rDestinationVariable) = it_node->FastGetSolutionStepValue(rOriginVariable);
}
KRATOS_CATCH("")
}
/**
* @brief Returns a list of nodes filtered using the given double variable and value
* @param Variable reference to the double variable to be filtered
* @param Value Filtering Value
* @param rOriginNodes Reference to the objective node set
* @return selected_nodes: List of filtered nodes
*/
NodesContainerType SelectNodeList(
const DoubleVarType& Variable,
const double Value,
const NodesContainerType& rOriginNodes
);
/**
* @brief Checks if all the nodes of a node set has the specified variable
* @param rVariable reference to a variable to be checked
* @param rNodes reference to the nodes set to be checked
* @return 0: if succeeds, return 0
*/
template<class TVarType>
int CheckVariableExists(
const TVarType& rVariable,
const NodesContainerType& rNodes
)
{
KRATOS_TRY
for (auto& i_node : rNodes)
KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(rVariable, i_node);
return 0;
KRATOS_CATCH("");
}
/**
* @brief Fixes or frees a variable for all of the nodes in the list. The dof has to exist.
* @param rVar reference to the variable to be fixed or freed
* @param IsFixed if true fixes, if false frees
* @param rNodes reference to the nodes set to be frixed or freed
*/
template< class TVarType >
void ApplyFixity(
const TVarType& rVar,
const bool IsFixed,
NodesContainerType& rNodes
)
{
KRATOS_TRY
if (rNodes.size() != 0) {
// checking the first node to avoid error being thrown in parallel region
KRATOS_ERROR_IF_NOT(rNodes.begin()->HasDofFor(rVar)) << "Trying to fix/free dof of variable " << rVar.Name() << " but this dof does not exist in node #" << rNodes.begin()->Id() << "!" << std::endl;
#ifdef KRATOS_DEBUG
for (const auto& r_node : rNodes) {
KRATOS_ERROR_IF_NOT(r_node.HasDofFor(rVar)) << "Trying to fix/free dof of variable " << rVar.Name() << " but this dof does not exist in node #" << r_node.Id() << "!" << std::endl;
}
#endif
CheckVariableExists(rVar, rNodes);
if (IsFixed) {
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) {
NodesContainerType::iterator it_node = rNodes.begin() + k;
it_node->pGetDof(rVar)->FixDof();
}
} else {
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) {
NodesContainerType::iterator it_node = rNodes.begin() + k;
it_node->pGetDof(rVar)->FreeDof();
}
}
}
KRATOS_CATCH("")
}
/**
* @brief Fixes/Frees dofs based on a flag
*
* This method fixes/frees given rVariable, if rFlag matches CheckValue provided for that
* specific node.
*
* @tparam TVarType Variable type
* @param rVariable Variable to be fixed or freed
* @param IsFixed True to fix variable, false to free variable
* @param rNodes Nodes container
* @param rFlag Flag to be checked to fix or free
* @param CheckValue Flag value which is checked against
*/
template< class TVarType >
void ApplyFixity(
const TVarType& rVariable,
const bool IsFixed,
NodesContainerType& rNodes,
const Flags& rFlag,
const bool CheckValue = true)
{
KRATOS_TRY
if (rNodes.size() != 0) {
// checking the first node to avoid error being thrown in parallel region
KRATOS_ERROR_IF_NOT(rNodes.begin()->HasDofFor(rVariable))
<< "Trying to fix/free dof of variable " << rVariable.Name()
<< " but this dof does not exist in node #"
<< rNodes.begin()->Id() << "!" << std::endl;
#ifdef KRATOS_DEBUG
for (const auto& r_node : rNodes) {
KRATOS_ERROR_IF_NOT(r_node.HasDofFor(rVariable))
<< "Trying to fix/free dof of variable " << rVariable.Name()
<< " but this dof does not exist in node #" << r_node.Id()
<< "!" << std::endl;
}
#endif
CheckVariableExists(rVariable, rNodes);
if (IsFixed) {
BlockPartition<NodesContainerType>(rNodes).for_each(
[&rVariable, &rFlag, CheckValue](NodeType& rNode) {
if (rNode.Is(rFlag) == CheckValue) {
rNode.pGetDof(rVariable)->FixDof();
}
});
}
else {
BlockPartition<NodesContainerType>(rNodes).for_each(
[&rVariable, &rFlag, CheckValue](NodeType& rNode) {
if (rNode.Is(rFlag) == CheckValue) {
rNode.pGetDof(rVariable)->FreeDof();
}
});
}
}
KRATOS_CATCH("");
}
/**
* @brief Loops along a vector data to set its values to the nodes contained in a node set.
* @note This function is suitable for scalar historical variables, since each
* one of the values in the data vector is set to its correspondent node. Besides,
* the values must be sorted as the nodes are (value i corresponds to node i).
* @param rVar reference to the variable to be fixed or freed
* @param rData rData vector. Note that its lenght must equal the number of nodes
* @param rNodes reference to the nodes set to be set
*/
template< class TVarType >
void ApplyVector(
const TVarType& rVar,
const Vector& rData,
NodesContainerType& rNodes
)
{
KRATOS_TRY
if(rNodes.size() != 0 && rNodes.size() == rData.size()) {
// First we do a check
CheckVariableExists(rVar, rNodes);
#pragma omp parallel for
for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) {
NodesContainerType::iterator it_node = rNodes.begin() + k;
it_node->FastGetSolutionStepValue(rVar) = rData[k];
}
} else
KRATOS_ERROR << "There is a mismatch between the size of data array and the number of nodes ";
KRATOS_CATCH("")
}
/**
* @brief Returns the nodal value summation of a non-historical vector variable.
* @param rVar reference to the vector variable to summed
* @param rModelPart reference to the model part that contains the objective node set
* @return sum_value: summation vector result
*/
array_1d<double, 3> SumNonHistoricalNodeVectorVariable(
const ArrayVarType& rVar,
const ModelPart& rModelPart
);
/**
* @brief Returns the nodal value summation of a non-historical scalar variable.
* @param rVar reference to the scalar variable to be summed
* @param rModelPart reference to the model part that contains the objective node set
* @return sum_value: summation result
*/
template< class TVarType >
double SumNonHistoricalNodeScalarVariable(
const TVarType& rVar,
const ModelPart& rModelPart
)
{
KRATOS_TRY
double sum_value = 0.0;
// Getting info
const auto& r_communicator = rModelPart.GetCommunicator();
const auto& r_local_mesh = r_communicator.LocalMesh();
const auto& r_nodes_array = r_local_mesh.Nodes();
const auto it_node_begin = r_nodes_array.begin();
#pragma omp parallel for reduction(+:sum_value)
for (int k = 0; k < static_cast<int>(r_nodes_array.size()); ++k) {
const auto it_node = it_node_begin + k;
sum_value += it_node->GetValue(rVar);
}
return r_communicator.GetDataCommunicator().SumAll(sum_value);
KRATOS_CATCH("")
}
/**
* @brief This method accumulates and return a variable value
* For a nodal historical variable, this method accumulates and
* returns the summation in a model part.
* @tparam TDataType Variable datatype
* @tparam Variable<TDataType> Variable type
* @param rVariable Nodal historical variable to be accumulated
* @param rModelPart Model part in where the summation is done
* @param BuffStep Buffer position
* @return TDataType Value of the summation
*/
template< class TDataType, class TVarType = Variable<TDataType> >
TDataType SumHistoricalVariable(
const TVarType &rVariable,
const ModelPart &rModelPart,
const unsigned int BuffStep = 0
)
{
KRATOS_TRY
TDataType sum_value;
AuxiliaryInitializeValue(sum_value);
const auto &r_communicator = rModelPart.GetCommunicator();
const int n_nodes = r_communicator.LocalMesh().NumberOfNodes();
#pragma omp parallel firstprivate(n_nodes)
{
TDataType private_sum_value;
AuxiliaryInitializeValue(private_sum_value);
#pragma omp for
for (int i_node = 0; i_node < n_nodes; ++i_node) {
const auto it_node = r_communicator.LocalMesh().NodesBegin() + i_node;
private_sum_value += it_node->GetSolutionStepValue(rVariable, BuffStep);
}
AuxiliaryAtomicAdd(private_sum_value, sum_value);
}
return r_communicator.GetDataCommunicator().SumAll(sum_value);
KRATOS_CATCH("")
}
/**
* @brief Returns the condition value summation of a historical vector variable
* @param rVar reference to the vector variable to be summed
* @param rModelPart reference to the model part that contains the objective condition set
* @return sum_value: summation result
*/
array_1d<double, 3> SumConditionVectorVariable(
const ArrayVarType& rVar,
const ModelPart& rModelPart
);
/**
* @brief Returns the condition value summation of a historical scalar variable
* @param rVar reference to the scalar variable to be summed
* @param rModelPart reference to the model part that contains the objective condition set
* @return sum_value: summation result
*/
template< class TVarType >
double SumConditionScalarVariable(
const TVarType& rVar,
const ModelPart& rModelPart
)
{
KRATOS_TRY
double sum_value = 0.0;
// Getting info
const auto& r_communicator = rModelPart.GetCommunicator();
const auto& r_local_mesh = r_communicator.LocalMesh();
const auto& r_conditions_array = r_local_mesh.Conditions();
const auto it_cond_begin = r_conditions_array.begin();
#pragma omp parallel for reduction(+:sum_value)
for (int k = 0; k < static_cast<int>(r_conditions_array.size()); ++k) {
const auto it_cond = it_cond_begin + k;
sum_value += it_cond->GetValue(rVar);
}
return r_communicator.GetDataCommunicator().SumAll(sum_value);
KRATOS_CATCH("")
}
/**
* @brief Returns the element value summation of a historical vector variable
* @param rVar reference to the vector variable to be summed
* @param rModelPart reference to the model part that contains the objective element set
* @return sum_value: summation result
*/
array_1d<double, 3> SumElementVectorVariable(
const ArrayVarType& rVar,
const ModelPart& rModelPart
);
/**
* @brief Returns the element value summation of a historical scalar variable
* @param rVar reference to the scalar variable to be summed
* @param rModelPart reference to the model part that contains the objective element set
* @return sum_value: summation result
*/
template< class TVarType >
double SumElementScalarVariable(
const TVarType& rVar,
const ModelPart& rModelPart
)
{
KRATOS_TRY
double sum_value = 0.0;
// Getting info
const auto& r_communicator = rModelPart.GetCommunicator();
const auto& r_local_mesh = r_communicator.LocalMesh();
const auto& r_elements_array = r_local_mesh.Elements();
const auto it_elem_begin = r_elements_array.begin();
#pragma omp parallel for reduction(+:sum_value)
for (int k = 0; k < static_cast<int>(r_elements_array.size()); ++k) {
const auto it_elem = it_elem_begin + k;
sum_value += it_elem->GetValue(rVar);
}
return r_communicator.GetDataCommunicator().SumAll(sum_value);
KRATOS_CATCH("")
}
/**
* @brief This function add dofs to the nodes in a model part. It is useful since addition is done in parallel
* @param rVar The variable to be added as DoF
* @param rModelPart reference to the model part that contains the objective element set
*/
template< class TVarType >
void AddDof(
const TVarType& rVar,
ModelPart& rModelPart
)
{
KRATOS_TRY
// First we do a chek
if(rModelPart.NumberOfNodes() != 0)
KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rVar)) << "ERROR:: Variable : " << rVar << "not included in the Solution step data ";
rModelPart.GetNodalSolutionStepVariablesList().AddDof(&rVar);
#pragma omp parallel for
for (int k = 0; k < static_cast<int>(rModelPart.NumberOfNodes()); ++k) {
auto it_node = rModelPart.NodesBegin() + k;
it_node->AddDof(rVar);
}
KRATOS_CATCH("")
}
/**
* @brief This function add dofs to the nodes in a model part. It is useful since addition is done in parallel
* @param rVar The variable to be added as DoF
* @param rReactionVar The corresponding reaction to the added DoF
* @param rModelPart reference to the model part that contains the objective element set
*/
template< class TVarType >
void AddDofWithReaction(
const TVarType& rVar,
const TVarType& rReactionVar,
ModelPart& rModelPart
)
{
KRATOS_TRY
if(rModelPart.NumberOfNodes() != 0) {
KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rVar)) << "ERROR:: DoF Variable : " << rVar << "not included in the Soluttion step data ";
KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rReactionVar)) << "ERROR:: Reaction Variable : " << rReactionVar << "not included in the Soluttion step data ";
}
// If in debug we do a check for all nodes
#ifdef KRATOS_DEBUG
CheckVariableExists(rVar, rModelPart.Nodes());
CheckVariableExists(rReactionVar, rModelPart.Nodes());
#endif
rModelPart.GetNodalSolutionStepVariablesList().AddDof(&rVar, &rReactionVar);
#pragma omp parallel for
for (int k = 0; k < static_cast<int>(rModelPart.NumberOfNodes()); ++k) {
auto it_node = rModelPart.NodesBegin() + k;
it_node->AddDof(rVar,rReactionVar);
}
KRATOS_CATCH("")
}
/**
* @brief This method checks the variable keys
* @return True if all the keys are correct
*/
bool CheckVariableKeys();
/**
* @brief This method updates the current nodal coordinates back to the initial coordinates
* @param rNodes the nodes to be updated
*/
void UpdateCurrentToInitialConfiguration(const ModelPart::NodesContainerType& rNodes);
/**
* @param rNodes the nodes to be updated
* @brief This method updates the initial nodal coordinates to the current coordinates
*/
void UpdateInitialToCurrentConfiguration(const ModelPart::NodesContainerType& rNodes);
/**
* @brief This method updates the current coordinates
* For each node, this method takes the value of the provided variable and updates the
* current position as the initial position (X0, Y0, Z0) plus such variable value
* @param rNodes
* @param rUpdateVariable variable to retrieve the updating values from
*/
void UpdateCurrentPosition(
const ModelPart::NodesContainerType& rNodes,
const ArrayVarType& rUpdateVariable = DISPLACEMENT,
const IndexType BufferPosition = 0
);
///@}
///@name Acces
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Friends
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
/**
* @brief Auxiliary double initialize method
* Auxiliary method to initialize a double value
* @param rValue Variable to initialize
*/
void AuxiliaryInitializeValue(double &rValue);
/**
* @brief Auxiliary array initialize method
* Auxiliary method to initialize an array value
* @param rValue Variable to initialize
*/
void AuxiliaryInitializeValue(array_1d<double,3> &rValue);
/**
* @brief Auxiliary scalar reduce method
* Auxiliary method to perform the reduction of a scalar value
* @param rPrivateValue Private variable to reduce
* @param rSumValue Variable to save the reduction
*/
void AuxiliaryAtomicAdd(
const double &rPrivateValue,
double &rSumValue
);
/**
* @brief Auxiliary array reduce method
* Auxiliary method to perform the reduction of an array value
* @param rPrivateValue Private variable to reduce
* @param rSumValue Variable to save the reduction
*/
void AuxiliaryAtomicAdd(
const array_1d<double,3> &rPrivateValue,
array_1d<double,3> &rSumValue
);
/**
* @brief This is auxiliar method to check the keys
* @return True if all the keys are OK
*/
template< class TVarType >
bool CheckVariableKeysHelper()
{
KRATOS_TRY
for (const auto& var : KratosComponents< TVarType >::GetComponents()) {
if (var.first == "NONE" || var.first == "")
std::cout << " var first is NONE or empty " << var.first << var.second << std::endl;
if (var.second->Name() == "NONE" || var.second->Name() == "")
std::cout << var.first << var.second << std::endl;
if (var.first != var.second->Name()) //name of registration does not correspond to the var name
std::cout << "Registration Name = " << var.first << " Variable Name = " << std::endl;
}
return true;
KRATOS_CATCH("")
}
template <class TContainerType>
TContainerType& GetContainer(ModelPart& rModelPart);
template <class TContainerType>
const TContainerType& GetContainer(const ModelPart& rModelPart);
template <class TContainerType, class TSetterFunction, class TGetterFunction>
void CopyModelPartFlaggedVariable(
const ModelPart& rOriginModelPart,
ModelPart& rDestinationModelPart,
const Flags& rFlag,
const bool CheckValue,
TSetterFunction&& rSetterFunction,
TGetterFunction&& rGetterFunction)
{
KRATOS_TRY
const auto& r_origin_container = GetContainer<TContainerType>(rOriginModelPart);
auto& r_destination_container = GetContainer<TContainerType>(rDestinationModelPart);
const int number_of_origin_items = r_origin_container.size();
const int number_of_destination_items = r_destination_container.size();
KRATOS_ERROR_IF_NOT(number_of_origin_items == number_of_destination_items)
<< "Origin ( " << rOriginModelPart.Name() << " ) and destination ( "
<< rDestinationModelPart.Name() << " ) model parts have different number of items."
<< "\n\t- Number of origin items: " << number_of_origin_items
<< "\n\t- Number of destination items: " << number_of_destination_items
<< std::endl;
IndexPartition<int>(number_of_origin_items).for_each([&](int i_node) {
const auto& r_orig_item = *(r_origin_container.begin() + i_node);
auto& r_dest_item = *(r_destination_container.begin() + i_node);
if (r_orig_item.Is(rFlag) == CheckValue) {
rSetterFunction(r_dest_item, rGetterFunction(r_orig_item));
}
});
KRATOS_CATCH("");
}
///@}
///@name Private Acces
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
///@}
}; /* Class VariableUtils */
///@}
///@name Type Definitions
///@{
///@}
} /* namespace Kratos.*/
#endif /* KRATOS_VARIABLE_UTILS defined */
|
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] = 4;
tile_size[1] = 4;
tile_size[2] = 32;
tile_size[3] = 2048;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
const double alpha = 0.0876;
const double beta = 0.0765;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
#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;
}
|
noble_1962.c | #include "noble_1962.h"
GET_CELL_MODEL_DATA(init_cell_model_data) {
if(get_initial_v)
cell_model->initial_v = INITIAL_V;
if(get_neq)
cell_model->number_of_ode_equations = NEQ;
}
SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) {
// Normal
//sv[0] = -75.5344986658f; // V millivolt
//sv[1] = 0.060546727200f; // m dimensionless
//sv[2] = 0.725900135500f; // h dimensionless
//sv[3] = 0.470923970800f; // n dimensionless
// BCL = 300ms | 10 pulses
sv[0] = -81.1893; // V millivolt
sv[1] = 0.0443563; // m dimensionless
sv[2] = 0.851652; // h dimensionless
sv[3] = 0.58291; // n dimensionless
// BCL = 500ms | 30 pulses
//sv[0] = -75.238;
//sv[1] = 0.0615111;
//sv[2] = 0.718401;
//sv[3] = 0.467409;
}
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) {
real rY[NEQ], rDY[NEQ];
for(int i = 0; i < NEQ; i++)
rY[i] = sv[i];
RHS_cpu(rY, rDY, stim_current);
for(int i = 0; i < NEQ; i++)
sv[i] = dt*rDY[i] + rY[i];
}
void RHS_cpu(const real *sv, real *rDY_, real stim_current) {
//State variables
const real V_old_ = sv[0];
const real m_old_ = sv[1];
const real h_old_ = sv[2];
const real n_old_ = sv[3];
//Parameters
//const real Cm = 12.00000000000000000e+00f; // (microF)
//const real g_na_max = 400000.00000000000000000e+00f; // (microS)
//const real E_na = 40.00000000000000000e+00f; // (millivolt)
//const real g_L = 75.00000000000000000e+00f; // (microS)
//const real E_L = -60.00000000000000000e+00f; // (millivolt)
const real Cm = 12.0; // (microF)
const real g_na_max = 400.0; // (microS)
const real E_na = 40.0; // (millivolt)
const real g_L = 0.075; // (microS)
const real E_L = -60.0; // (millivolt)
real calc_I_stim = stim_current;
// Algebraics
//real g_na = pow(m_old_, 3.00000)*h_old_*g_na_max;
//real alpha_m = ( 100.000*(- V_old_ - 48.0000))/(exp((- V_old_ - 48.0000)/15.0000) - 1.00000);
//real alpha_h = 170.000*exp((- V_old_ - 90.0000)/20.0000);
//real alpha_n = ( 0.100000*(- V_old_ - 50.0000))/(exp((- V_old_ - 50.0000)/10.0000) - 1.00000);
//real i_na = (g_na+140.000)*(V_old_ - E_na);
//real i_na_no_oscilation = (g_na+122.500)*(V_old_ - E_na);
//real beta_m = ( 120.000*(V_old_+8.00000))/(exp((V_old_+8.00000)/5.00000) - 1.00000);
//real beta_h = 1000.00/(1.00000+exp((- V_old_ - 42.0000)/10.0000));
//real beta_n = 2.00000*exp((- V_old_ - 90.0000)/80.0000);
//real g_K1 = 1200.00*exp((- V_old_ - 90.0000)/50.0000)+ 15.0000*exp((V_old_+90.0000)/60.0000);
//real g_K2 = 1200.00*pow(n_old_, 4.00000);
//real i_k = (g_K1+g_K2)*(V_old_+100.000);
//real i_leak = g_L*(V_old_ - E_L);
real g_na = pow(m_old_, 3.00000)*h_old_*g_na_max;
real alpha_h = ((1.7e-01*exp((((-V_old_)-9.0e+01)/2.0e+01))));
real alpha_m = (((1.0e-01*((-V_old_)-4.8e+01))/(exp((((-V_old_)-4.8e+01)/1.5e+01))-1.0e+00)));
real alpha_n = (((1.0e-04*((-V_old_)-5.0e+01))/(exp((((-V_old_)-5.0e+01)/1.0e+01))-1.0e+00)));
real i_na = (g_na+1.4e-01)*(V_old_ - E_na);
real i_na_no_oscilation = (g_na+1.2e-01)*(V_old_ - E_na);
double beta_m = (((1.2e-01*(V_old_+8.0e+00))/(exp(((V_old_+8.0e+00)/5.0e+00))-1.0e+00)));
double beta_h = ((1.0/(1.0e+00+exp((((-V_old_)-4.2e+01)/1.0e+01)))));
double beta_n = ((2.0e-03*exp((((-V_old_)-9.0e+01)/8.0e+01))));
real g_K1 = 1.2*exp((((-V_old_)-9.0e+01)/5.0e+01)) + (1.5e-02*exp(((V_old_+9.0e+01)/6.0e+01)));
real g_K2 = 1.2*pow(n_old_,4.0e+00);
real i_k = (g_K1+g_K2)*(V_old_+100.000);
real i_leak = g_L*(V_old_ - E_L);
// Rates
//rDY_[0] = (- (i_na + i_k + i_leak + calc_I_stim)/Cm) * 1.0E-03;
//rDY_[0] = (- (i_na_no_oscilation + i_k + i_leak + calc_I_stim)/Cm) * 1.0E-03;
//rDY_[1] = (alpha_m*(1.00000 - m_old_) - beta_m*m_old_) * 1.0E-03;
//rDY_[2] = (alpha_h*(1.00000 - h_old_) - beta_h*h_old_) * 1.0E-03;
//rDY_[3] = (alpha_n*(1.00000 - n_old_) - beta_n*n_old_) * 1.0E-03;
rDY_[0] = (- (i_na + i_k + i_leak + calc_I_stim)/Cm);
//rDY_[0] = (- (i_na_no_oscilation + i_k + i_leak + calc_I_stim)/Cm);
rDY_[1] = (alpha_m*(1.00000 - m_old_) - beta_m*m_old_);
rDY_[2] = (alpha_h*(1.00000 - h_old_) - beta_h*h_old_);
rDY_[3] = (alpha_n*(1.00000 - n_old_) - beta_n*n_old_);
}
|
shwater2d.c | /*
* shwater2d.c solves the two dimensional shallow water equations
* using the Lax-Friedrich's scheme
*/
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <omp.h>
#include <sys/time.h>
#define cell_size 3
#define xstart 0.0
#define ystart 0.0
#define xend 4.0
#define yend 4.0
#define Q(i, j, k) Q[((k) + n * ((j) + m * (i)))]
/* Timing function */
double gettime(void) {
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec + 1e-6*tv.tv_usec;
}
/* Check that the solution is finite */
void validate(double *Q, int m, int n) {
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
for (k = 0; k < cell_size; k++)
if (!isfinite(Q(k, j, i))) {
fprintf(stderr, "Invalid solution\n");
exit(-1);
}
}
/* Flux function in the x-direction */
/*
void fx(double *Q, double **fq, int m, int n, int j) {
int i;
const double g = 9.81;
#pragma omp for
for (i = 0; i < m; i++) {
fq[0][i] = Q(1, i, j);
fq[1][i] = (pow(Q(1, i, j), 2) / Q(0, i, j)) +
(g * pow(Q(0, i, j), 2)) / 2.0;
fq[2][i] = (Q(1, i, j) * Q(2, i, j)) / Q(0, i, j);
}
}
*/
/* Flux function in the y-direction */
/*
void fy(double *Q, double **fq, int m, int n, int i) {
int j;
const double g= 9.81;
#pragma omp for
for (j = 0; j < n; j++) {
fq[0][j] = Q(2, i, j);
fq[1][j] = (Q(1, i, j) * Q(2, i, j)) / Q(0, i, j);
fq[2][j] = (pow(Q(2, i, j), 2) / Q(0, i, j)) +
(g * pow(Q(0, i, j), 2)) / 2.0;
}
}
*/
/*
This is the Lax-Friedrich's scheme for updating volumes
Try to parallelize it in an efficient way!
*/
void laxf_scheme_2d(double *Q, double **ffx, double **ffy, double **nFx, double **nFy,
int m, int n, double dx, double dy, double dt) {
const double g = 9.81;
#pragma omp parallel
{
int i, j, k, l;
/* Calculate and update fluxes in the x-direction */
for (i = 1; i < n; i++) {
//fx(Q, ffx, m, n, i);
#pragma omp for
for (l = 0; l < m; l++) {
ffx[0][l] = Q(1, l, i);
ffx[1][l] = (pow(Q(1, l, i), 2) / Q(0, l, i)) +
(g * pow(Q(0, l, i), 2)) / 2.0;
ffx[2][l] = (Q(1, l, i) * Q(2, l, i)) / Q(0, l, i);
}
#pragma omp for
for (j = 1; j < m; j++)
for (k = 0; k < cell_size; k++)
nFx[k][j] = 0.5 * ((ffx[k][j-1] + ffx[k][j]) -
dx/dt * (Q(k, j, i) - Q(k, j-1, i)));
#pragma omp for
for (j = 1; j < m-1; j++)
for (k = 0; k < cell_size; k++)
Q(k, j, i) = Q(k, j, i) - dt/dx * ((nFx[k][j+1] - nFx[k][j]));
}
/* Calculate and update fluxes in the y-direction */
for (i = 1; i < m; i++) {
//fy(Q, ffy, m, n, i);
#pragma omp for
for (j = 0; j < n; j++) {
ffy[0][j] = Q(2, i, j);
ffy[1][j] = (Q(1, i, j) * Q(2, i, j)) / Q(0, i, j);
ffy[2][j] = (pow(Q(2, i, j), 2) / Q(0, i, j)) +
(g * pow(Q(0, i, j), 2)) / 2.0;
}
#pragma omp for
for (j = 1; j < n; j++)
for (k = 0; k < cell_size; k++)
nFy[k][j] = 0.5 * ((ffy[k][j-1] + ffy[k][j]) -
dy/dt * (Q(k, i, j) - Q(k, i, j -1)));
#pragma omp for
for (j = 1; j < n-1; j++)
for (k = 0; k < cell_size; k++)
Q(k,i,j) = Q(k,i,j) - dt/dy * ((nFy[k][j+1] - nFy[k][j]));
}
}
}
/*
This is the main solver routine, parallelize this.
But don't forget the subroutine laxf_scheme_2d
*/
void solver(double *Q, double **ffx, double **ffy, double **nFx, double **nFy,
int m, int n, double tend, double dx, double dy, double dt) {
double bc_mask[3] = {1.0, -1.0, -1.0};
double time;
int i, j, k, steps;
steps = ceil(tend / dt);
for (i = 0, time = 0.0; i < steps; i++, time += dt) {
/* Apply boundary condition */
for (j = 1; j < n - 1; j++) {
for (k = 0; k < cell_size; k++) {
Q(k, 0, j) = bc_mask[k] * Q(k, 1, j);
Q(k, m-1, j) = bc_mask[k] * Q(k, m-2, j);
}
}
for (j = 0; j < m; j++) {
for (k = 0; k < cell_size; k++) {
Q(k, j, 0) = bc_mask[k] * Q(k, j, 1);
Q(k, j, n-1) = bc_mask[k] * Q(k, j, n-2);
}
}
/* Update all volumes with the Lax-Friedrich's scheme */
laxf_scheme_2d(Q, ffx, ffy, nFx, nFy, m, n, dx, dy, dt);
}
}
void save_vtk(double *Q, double *x, double *y, int m, int n) {
int i, j;
FILE *fp = fopen("result.vtk", "w");
/* Write vtk Datafile header */
fprintf(fp, "# vtk DataFile Version 2.0\n");
fprintf(fp, "VTK\nASCII\nDATASET POLYDATA\n");
/* Store water height as polydata */
fprintf(fp, "\nPOINTS %d double\n", m*n);
for (j = 0; j < n; j++)
for (i = 0; i < m; i++)
fprintf(fp, "%e %e %e\n", x[i], y[j], Q(0, i, j));
fprintf(fp,"\nVERTICES %d %d\n", n, n *(m+1));
for (j = 0; j < n; j++) {
fprintf(fp, "%d ", m);
for (i = 0; i < m; i++)
fprintf(fp, "%d ", i+j*m);
fprintf(fp,"\n");
}
/* Store lookup table */
fprintf(fp,
"POINT_DATA %d\nSCALARS height double 1\nLOOKUP_TABLE default\n",m*n);
for (j = 0; j < n; j++)
for (i = 0; i < m; i++)
fprintf(fp, "%e\n", Q(0, i, j));
fclose(fp);
}
/*
This is the main routine of the program, which allocates memory
and setup all parameters for the problem.
You don't need to parallelize anything here!
However, it might be useful to change the m and n parameters
during debugging
*/
int main(int argc, char **argv) {
int i, j, m, n;
double *Q;
double *x, *y;
double **ffx, **nFx, **ffy, **nFy;
double dx, dt, epsi, delta, dy, tend, tmp, stime, etime;
/* Use m volumes in the x-direction and n volumes in the y-direction */
m = 1000;
n = 1000;
/*
epsi Parameter used for initial condition
delta Parameter used for initial condition
dx Distance between two volumes (x-direction)
dy Distance between two volumes (y-direction)
dt Time step
tend End time
*/
epsi = 2.0;
delta = 0.5;
dx = (xend - xstart) / (double) m;
dy = (yend - ystart) / (double) n;
dt = dx / sqrt( 9.81 * 5.0);
tend = 0.1;
/* Add two ghost volumes at each side of the domain */
m = m + 2;
n = n + 2;
/* Allocate memory for the domain */
Q = (double *) malloc(m * n * cell_size * sizeof(double));
x = (double *) malloc(m * sizeof(double));
y = (double *) malloc(n * sizeof(double));
/* Allocate memory for fluxes */
ffx = (double **) malloc(cell_size * sizeof(double *));
ffy = (double **) malloc(cell_size * sizeof(double *));
nFx = (double **) malloc(cell_size * sizeof(double *));
nFy = (double **) malloc(cell_size * sizeof(double *));
ffx[0] = (double *) malloc(cell_size * m * sizeof(double));
ffy[0] = (double *) malloc(cell_size * n * sizeof(double));
nFx[0] = (double *) malloc(cell_size * m * sizeof(double));
nFy[0] = (double *) malloc(cell_size * n * sizeof(double));
for (i = 0; i < cell_size; i++) {
ffx[i] = ffx[0] + i * m;
nFx[i] = nFx[0] + i * m;
ffy[i] = ffy[0] + i * n;
nFy[i] = nFy[0] + i * n;
}
for (i = 0,tmp= -dx/2 + xstart; i < m; i++, tmp += dx)
x[i] = tmp;
for (i = 0,tmp= -dy/2 + ystart; i < n; i++, tmp += dy)
y[i] = tmp;
/* Set initial Gauss hump */
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
Q(0, i, j) = 4.0;
Q(1, i, j) = 0.0;
Q(2, i, j) = 0.0;
}
}
for (i = 1; i < m-1; i++) {
for (j = 1; j < n-1; j++) {
Q(0, i, j) = 4.0 + epsi * exp(-(pow(x[i] - xend / 4.0, 2) + pow(y[j] - yend / 4.0, 2)) /
(pow(delta, 2)));
}
}
stime = gettime();
solver(Q, ffx, ffy, nFx, nFy, m, n, tend, dx, dy, dt);
etime = gettime();
validate(Q, m, n);
printf("Solver took %g seconds\n", etime - stime);
/* Uncomment this line if you want visualize the result in ParaView */
//save_vtk(Q, x, y, m, n);
free(Q);
free(x);
free(y);
free(ffx[0]);
free(ffy[0]);
free(nFx[0]);
free(nFy[0]);
free(ffx);
free(ffy);
free(nFx);
free(nFy);
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 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
auto* input = ctx.Input<Tensor>("X");
auto* output = ctx.Output<Tensor>("Out");
auto* indices = ctx.Output<Tensor>("Indices");
size_t k = static_cast<int>(ctx.Attr<int>("k"));
auto* k_t = ctx.Input<Tensor>("K");
if (k_t) {
k = k_t->data<int>()[0];
framework::DDim output_dims = output->dims();
output_dims[output_dims.size() - 1] = k;
output->Resize(output_dims);
indices->Resize(output_dims);
}
T* output_data = output->mutable_data<T>(ctx.GetPlace());
int64_t* indices_data = indices->mutable_data<int64_t>(ctx.GetPlace());
// reshape input to a flattern matrix(like flat_inner_dims)
framework::DDim inputdims = input->dims();
const size_t row =
phi::product(phi::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.
#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;
vec.reserve(col);
// 1D vector
if (inputdims.size() == 1) {
auto eg_input = framework::EigenVector<T>::Flatten(*input);
for (size_t j = 0; j < col; j++) {
vec.push_back(std::pair<T, size_t>(eg_input(j), j));
}
} else {
auto eg_input =
framework::EigenMatrix<T>::Reshape(*input, inputdims.size() - 1);
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);
}
}
}
};
template <typename DeviceContext, typename T>
class TopkGradKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& context) const override {
auto* x = context.Input<Tensor>("X");
auto* out_grad = context.Input<Tensor>(framework::GradVarName("Out"));
auto* indices = context.Input<Tensor>("Indices");
auto* x_grad = context.Output<Tensor>(framework::GradVarName("X"));
T* x_grad_data = x_grad->mutable_data<T>(context.GetPlace());
const T* out_grad_data = out_grad->data<T>();
const int64_t* indices_data = indices->data<int64_t>();
size_t k = indices->dims()[indices->dims().size() - 1];
framework::DDim xdims = x->dims();
const size_t row =
phi::product(phi::slice_ddim(xdims, 0, xdims.size() - 1));
const size_t col = xdims[xdims.size() - 1];
memset(x_grad_data, 0, row * col * sizeof(T));
for (size_t i = 0; i < row; ++i) {
for (size_t j = 0; j < k; ++j) {
size_t idx = indices_data[i * k + j];
x_grad_data[i * col + idx] = out_grad_data[i * k + j];
}
}
}
};
} // namespace operators
} // namespace paddle
|
znormx.c | #include "znormx.h"
#include "dznrmx.h"
double znormx_(const fnat m[static restrict 1], const fnat n[static restrict 1], const double Ar[static restrict VDL], const fnat ldAr[static restrict 1], const double Ai[static restrict VDL], const fnat ldAi[static restrict 1])
{
#ifndef NDEBUG
if (IS_NOT_VFPENV)
return -7.0;
if (*m & VDL_1)
return -1.0;
if (IS_NOT_ALIGNED(Ar))
return -3.0;
if (*ldAr < *m)
return -4.0;
if (*ldAr & VDL_1)
return -4.5;
if (IS_NOT_ALIGNED(Ai))
return -5.0;
if (*ldAi < *m)
return -6.0;
if (*ldAi & VDL_1)
return -6.5;
#endif /* !NDEBUG */
#ifdef _OPENMP
double y = 0.0;
#pragma omp parallel for default(none) shared(m,n,Ar,ldAr) reduction(max:y)
DZNRMX_LOOP(Ar,ldAr);
#pragma omp parallel for default(none) shared(m,n,Ai,ldAi) reduction(max:y)
DZNRMX_LOOP(Ai,ldAi);
return y;
#else /* !_OPENMP */
register const VD _zero = _mm512_set1_pd(-0.0);
register const VD inf = _mm512_set1_pd(HUGE_VAL);
register VD x = _mm512_setzero_pd();
DZNRMX_LOOP(Ar,ldAr);
DZNRMX_LOOP(Ai,ldAi);
return _mm512_reduce_max_pd(x);
#endif /* ?_OPENMP */
}
|
SwathFileConsumer.h | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
// Datastructures
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
// Consumers
#include <OpenMS/FORMAT/DATAACCESS/MSDataCachedConsumer.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h>
// Helpers
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace OpenMS
{
/**
* @brief Abstract base class which can consume spectra coming from SWATH experiment stored in a single file.
*
* The class consumes spectra which are coming from a complete SWATH
* experiment. It will group MS2 spectra by their precursor m/z, assuming
* that they correspond to the same SWATH window. For example, the spectra
* could be arranged in the following fashion:
*
* - MS1 Spectrum (no precursor)
* - MS2 Spectrum (precursor = [400,425])
* - MS2 Spectrum (precursor = [425,450])
* - [...]
* - MS2 Spectrum (precursor = [1175,1200])
* - MS1 Spectrum (no precursor)
* - MS2 Spectrum (precursor = [400,425])
* - MS2 Spectrum (precursor = [425,450])
* - [...]
*
* Base classes are expected to implement functions consuming a spectrum coming
* from a specific SWATH or an MS1 spectrum and a final function
* ensureMapsAreFilled_ after which the swath_maps_ vector needs to contain
* valid pointers to MSExperiment.
*
* In addition it is possible to provide the swath boundaries and the read in
* spectra will be matched by their precursor m/z to the "center" attribute
* of the provided Swath maps.
*
* Usage:
*
* @code
* FullSwathFileConsumer * dataConsumer;
* // assign dataConsumer to an implementation of FullSwathFileConsumer
* MzMLFile().transform(file, dataConsumer);
* dataConsumer->retrieveSwathMaps(maps);
* @endcode
*
*/
class OPENMS_DLLAPI FullSwathFileConsumer :
public Interfaces::IMSDataConsumer
{
public:
typedef PeakMap MapType;
typedef MapType::SpectrumType SpectrumType;
typedef MapType::ChromatogramType ChromatogramType;
FullSwathFileConsumer() :
ms1_map_(), // initialize to null
consuming_possible_(true),
use_external_boundaries_(false),
correct_window_counter_(0)
{
use_external_boundaries_ = !swath_map_boundaries_.empty();
}
/**
* @brief Constructor
*
* @param swath_boundaries A vector of SwathMaps of which only the center,
* lower and upper attributes will be used to infer the expected Swath maps.
*
*/
FullSwathFileConsumer(std::vector<OpenSwath::SwathMap> swath_boundaries) :
swath_map_boundaries_(swath_boundaries),
ms1_map_(), // initialize to null
consuming_possible_(true),
use_external_boundaries_(false),
correct_window_counter_(0)
{
use_external_boundaries_ = !swath_map_boundaries_.empty();
}
~FullSwathFileConsumer() override {}
void setExpectedSize(Size, Size) override {}
void setExperimentalSettings(const ExperimentalSettings& exp) override {settings_ = exp; }
/**
* @brief Populate the vector of swath maps after consuming all spectra.
*
* Will populate the input vector with SwathMap objects which correspond to
* the MS1 map (if present) and the MS2 maps (SWATH maps). This should be
* called after all spectra are consumed.
*
* @note It is not possible to consume any more spectra after calling this
* function (it contains finalization code and may close file streams).
*
*/
void retrieveSwathMaps(std::vector<OpenSwath::SwathMap>& maps)
{
consuming_possible_ = false; // make consumption of further spectra / chromatograms impossible
ensureMapsAreFilled_();
if (ms1_map_)
{
OpenSwath::SwathMap map;
map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(ms1_map_);
map.lower = -1;
map.upper = -1;
map.center = -1;
map.imLower = -1;
map.imUpper = -1;
map.ms1 = true;
maps.push_back(map);
}
// Print warning if the lower/upper window could not be determined and we
// required manual determination of the boundaries.
if (!use_external_boundaries_ && correct_window_counter_ != swath_maps_.size())
{
std::cout << "WARNING: Could not correctly read the upper/lower limits of the SWATH windows from your input file. Read " <<
correct_window_counter_ << " correct (non-zero) window limits (expected " << swath_maps_.size() << " windows)." << std::endl;
}
size_t nonempty_maps = 0;
for (Size i = 0; i < swath_maps_.size(); i++)
{
OpenSwath::SwathMap map;
map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_maps_[i]);
map.lower = swath_map_boundaries_[i].lower;
map.upper = swath_map_boundaries_[i].upper;
map.center = swath_map_boundaries_[i].center;
map.imLower = swath_map_boundaries_[i].imLower;
map.imUpper = swath_map_boundaries_[i].imUpper;
map.ms1 = false;
maps.push_back(map);
if (map.sptr->getNrSpectra() > 0) {nonempty_maps++;}
}
if (nonempty_maps != swath_map_boundaries_.size())
{
std::cout << "WARNING: The number nonempty maps found in the input file (" << nonempty_maps << ") is not equal to the number of provided swath window boundaries (" <<
swath_map_boundaries_.size() << "). Please check your input." << std::endl;
}
}
/// Consume a chromatogram -> should not happen when dealing with SWATH maps
void consumeChromatogram(MapType::ChromatogramType&) override
{
std::cerr << "Read chromatogram while reading SWATH files, did not expect that!" << std::endl;
}
/**
* @brief * Consume a spectrum which may belong either to an MS1 scan or
* one of n MS2 (SWATH) scans
*
*/
void consumeSpectrum(MapType::SpectrumType& s) override
{
if (!consuming_possible_)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"FullSwathFileConsumer cannot consume any more spectra after retrieveSwathMaps has been called already");
}
if (s.getMSLevel() == 1)
{
consumeMS1Spectrum_(s);
}
else
{
if (s.getPrecursors().empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Swath scan does not provide a precursor.");
}
const std::vector<Precursor> prec = s.getPrecursors();
double center = prec[0].getMZ();
double lower = prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset();
double upper = prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset();
double lowerIm = -1; // these initial values assume IM is not present
double upperIm = -1;
// add IM if present
if (s.metaValueExists("ion mobility lower limit"))
{
lowerIm = s.getMetaValue("ion mobility lower limit"); // want this to be -1 if no ion mobility
upperIm = s.getMetaValue("ion mobility upper limit");
}
bool found = false;
// Check if enough information is present to infer the swath
if (center <= 0.0)
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Swath scan does not provide any precursor isolation information.");
}
// try to match the current scan to one of the already known windows
for (Size i = 0; i < swath_map_boundaries_.size(); i++)
{
// We group by the precursor mz (center of the window) since this
// should be present in all SWATH scans.
// also specify ion mobility, if ion mobility not present will just be -1
if ( (std::fabs(center - swath_map_boundaries_[i].center) < 1e-6) && (std::fabs(lowerIm - swath_map_boundaries_[i].imLower) < 1e-6) && ( std::fabs(upperIm - swath_map_boundaries_[i].imUpper) < 1e-6))
{
found = true;
consumeSwathSpectrum_(s, i);
break;
}
}
if (!found)
{
if (use_external_boundaries_)
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Encountered SWATH scan with boundary ") + center + " m/z which was not present in the provided windows.");
}
else
{
consumeSwathSpectrum_(s, swath_map_boundaries_.size());
// we found a new SWATH window
if (lower > 0.0 && upper > 0.0)
{correct_window_counter_++;}
OpenSwath::SwathMap boundary;
boundary.lower = lower;
boundary.upper = upper;
boundary.center = center;
boundary.imLower = lowerIm;
boundary.imUpper = upperIm;
swath_map_boundaries_.push_back(boundary);
OPENMS_LOG_DEBUG << "Adding Swath centered at " << center
<< " m/z with an isolation window of " << lower << " to " << upper
<< " m/z and IM lower limit of " << lowerIm << " and upper limit of " << upperIm << std::endl;
}
}
}
}
protected:
/**
* @brief Consume an MS2 spectrum belonging to SWATH "swath_nr"
*
* This function should handle a spectrum belonging to a specific SWATH
* (indicated by swath_nr).
*
*/
virtual void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) = 0;
/**
* @brief Consume an MS1 spectrum
*
* This function should handle an MS1 spectrum.
*
*/
virtual void consumeMS1Spectrum_(MapType::SpectrumType& s) = 0;
/**
* @brief Callback function after the reading is complete
*
* Has to ensure that swath_maps_ and ms1_map_ are correctly populated.
*/
virtual void ensureMapsAreFilled_() = 0;
/// A list of Swath map identifiers (lower/upper boundary and center)
std::vector<OpenSwath::SwathMap> swath_map_boundaries_;
/// A list of SWATH maps and the MS1 map
std::vector<boost::shared_ptr<PeakMap > > swath_maps_;
boost::shared_ptr<PeakMap > ms1_map_;
/// The Experimental settings
// (MSExperiment has no constructor using ExperimentalSettings)
PeakMap settings_;
/// Whether further spectra can still be consumed
bool consuming_possible_;
/// Whether to use external input for SWATH boundaries
bool use_external_boundaries_;
/// How many windows were correctly annotated (non-zero window limits)
size_t correct_window_counter_;
};
/**
* @brief In-memory implementation of FullSwathFileConsumer
*
* Keeps all the spectra in memory by just appending them to an MSExperiment.
*
*/
class OPENMS_DLLAPI RegularSwathFileConsumer :
public FullSwathFileConsumer
{
public:
typedef PeakMap MapType;
typedef MapType::SpectrumType SpectrumType;
typedef MapType::ChromatogramType ChromatogramType;
RegularSwathFileConsumer() {}
RegularSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries) :
FullSwathFileConsumer(known_window_boundaries) {}
protected:
void addNewSwathMap_()
{
boost::shared_ptr<PeakMap > exp(new PeakMap(settings_));
swath_maps_.push_back(exp);
}
void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override
{
while (swath_maps_.size() <= swath_nr)
{
addNewSwathMap_();
}
swath_maps_[swath_nr]->addSpectrum(s);
}
void addMS1Map_()
{
boost::shared_ptr<PeakMap > exp(new PeakMap(settings_));
ms1_map_ = exp;
}
void consumeMS1Spectrum_(MapType::SpectrumType& s) override
{
if (!ms1_map_)
{
addMS1Map_();
}
ms1_map_->addSpectrum(s);
}
void ensureMapsAreFilled_() override {}
};
/**
* @brief On-disk cached implementation of FullSwathFileConsumer
*
* Writes all spectra immediately to disk in a user-specified caching
* location using the MSDataCachedConsumer. Internally, it handles
* n+1 (n SWATH + 1 MS1 map) objects of MSDataCachedConsumer which can consume the
* spectra and write them to disk immediately.
*
*/
class OPENMS_DLLAPI CachedSwathFileConsumer :
public FullSwathFileConsumer
{
public:
typedef PeakMap MapType;
typedef MapType::SpectrumType SpectrumType;
typedef MapType::ChromatogramType ChromatogramType;
CachedSwathFileConsumer(String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) :
ms1_consumer_(nullptr),
swath_consumers_(),
cachedir_(cachedir),
basename_(basename),
nr_ms1_spectra_(nr_ms1_spectra),
nr_ms2_spectra_(nr_ms2_spectra)
{}
CachedSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries,
String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) :
FullSwathFileConsumer(known_window_boundaries),
ms1_consumer_(nullptr),
swath_consumers_(),
cachedir_(cachedir),
basename_(basename),
nr_ms1_spectra_(nr_ms1_spectra),
nr_ms2_spectra_(nr_ms2_spectra)
{}
~CachedSwathFileConsumer() override
{
// Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream
while (!swath_consumers_.empty())
{
delete swath_consumers_.back();
swath_consumers_.pop_back();
}
if (ms1_consumer_ != nullptr)
{
delete ms1_consumer_;
ms1_consumer_ = nullptr;
}
}
protected:
void addNewSwathMap_()
{
String meta_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML";
String cached_file = meta_file + ".cached";
MSDataCachedConsumer* consumer = new MSDataCachedConsumer(cached_file, true);
consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0);
swath_consumers_.push_back(consumer);
// maps for meta data
boost::shared_ptr<PeakMap > exp(new PeakMap(settings_));
swath_maps_.push_back(exp);
}
void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override
{
while (swath_maps_.size() <= swath_nr)
{
addNewSwathMap_();
}
swath_consumers_[swath_nr]->consumeSpectrum(s); // write data to cached file; clear data from spectrum s
swath_maps_[swath_nr]->addSpectrum(s); // append for the metadata (actual data was deleted)
}
void addMS1Map_()
{
String meta_file = cachedir_ + basename_ + "_ms1.mzML";
String cached_file = meta_file + ".cached";
ms1_consumer_ = new MSDataCachedConsumer(cached_file, true);
ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0);
boost::shared_ptr<PeakMap > exp(new PeakMap(settings_));
ms1_map_ = exp;
}
void consumeMS1Spectrum_(MapType::SpectrumType& s) override
{
if (ms1_consumer_ == nullptr)
{
addMS1Map_();
}
ms1_consumer_->consumeSpectrum(s);
ms1_map_->addSpectrum(s); // append for the metadata (actual data is deleted)
}
void ensureMapsAreFilled_() override
{
size_t swath_consumers_size = swath_consumers_.size();
bool have_ms1 = (ms1_consumer_ != nullptr);
// Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream
// The file streams to the cached data on disc can and should be closed
// here safely. Since ensureMapsAreFilled_ is called after consuming all
// the spectra, there will be no more spectra to append but the client
// might already want to read after this call, so all data needs to be
// present on disc and the file streams closed.
//
// TODO merge with destructor code into own function!
while (!swath_consumers_.empty())
{
delete swath_consumers_.back();
swath_consumers_.pop_back();
}
if (ms1_consumer_ != nullptr)
{
delete ms1_consumer_;
ms1_consumer_ = nullptr;
}
if (have_ms1)
{
boost::shared_ptr<PeakMap > exp(new PeakMap);
String meta_file = cachedir_ + basename_ + "_ms1.mzML";
// write metadata to disk and store the correct data processing tag
Internal::CachedMzMLHandler().writeMetadata(*ms1_map_, meta_file, true);
MzMLFile().load(meta_file, *exp.get());
ms1_map_ = exp;
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(swath_consumers_size); i++)
{
boost::shared_ptr<PeakMap > exp(new PeakMap);
String meta_file = cachedir_ + basename_ + "_" + String(i) + ".mzML";
// write metadata to disk and store the correct data processing tag
Internal::CachedMzMLHandler().writeMetadata(*swath_maps_[i], meta_file, true);
MzMLFile().load(meta_file, *exp.get());
swath_maps_[i] = exp;
}
}
MSDataCachedConsumer* ms1_consumer_;
std::vector<MSDataCachedConsumer*> swath_consumers_;
String cachedir_;
String basename_;
int nr_ms1_spectra_;
std::vector<int> nr_ms2_spectra_;
};
/**
* @brief On-disk mzML implementation of FullSwathFileConsumer
*
* Writes all spectra immediately to disk to an mzML file location using the
* PlainMSDataWritingConsumer. Internally, it handles n+1 (n SWATH + 1 MS1
* map) objects of MSDataCachedConsumer which can consume the spectra and
* write them to disk immediately.
*
* Warning: no swathmaps (MS1 nor MS2) will be available when calling retrieveSwathMaps()
* for downstream use.
*
*/
class OPENMS_DLLAPI MzMLSwathFileConsumer :
public FullSwathFileConsumer
{
public:
typedef PeakMap MapType;
typedef MapType::SpectrumType SpectrumType;
typedef MapType::ChromatogramType ChromatogramType;
MzMLSwathFileConsumer(const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) :
ms1_consumer_(nullptr),
swath_consumers_(),
cachedir_(cachedir),
basename_(basename),
nr_ms1_spectra_(nr_ms1_spectra),
nr_ms2_spectra_(nr_ms2_spectra)
{}
MzMLSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries,
const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) :
FullSwathFileConsumer(known_window_boundaries),
ms1_consumer_(nullptr),
swath_consumers_(),
cachedir_(cachedir),
basename_(basename),
nr_ms1_spectra_(nr_ms1_spectra),
nr_ms2_spectra_(nr_ms2_spectra)
{}
~MzMLSwathFileConsumer() override
{
deleteSetNull_();
}
protected:
void deleteSetNull_()
{
// Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream
while (!swath_consumers_.empty())
{
delete swath_consumers_.back();
swath_consumers_.pop_back();
}
if (ms1_consumer_ != nullptr)
{
delete ms1_consumer_;
ms1_consumer_ = nullptr;
}
}
void addNewSwathMap_()
{
String mzml_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML";
PlainMSDataWritingConsumer* consumer = new PlainMSDataWritingConsumer(mzml_file);
consumer->getOptions().setCompression(true);
consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0);
swath_consumers_.push_back(consumer);
}
void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override
{
// only use swath_consumers_ to count how many we have already added
while (swath_consumers_.size() <= swath_nr)
{
addNewSwathMap_();
}
swath_consumers_[swath_nr]->consumeSpectrum(s);
s.clear(false);
}
void addMS1Map_()
{
String mzml_file = cachedir_ + basename_ + "_ms1.mzML";
ms1_consumer_ = new PlainMSDataWritingConsumer(mzml_file);
ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0);
ms1_consumer_->getOptions().setCompression(true);
}
void consumeMS1Spectrum_(MapType::SpectrumType& s) override
{
if (ms1_consumer_ == nullptr)
{
addMS1Map_();
}
ms1_consumer_->consumeSpectrum(s);
}
void ensureMapsAreFilled_() override
{
deleteSetNull_();
}
PlainMSDataWritingConsumer* ms1_consumer_;
std::vector<PlainMSDataWritingConsumer*> swath_consumers_;
String cachedir_;
String basename_;
int nr_ms1_spectra_;
std::vector<int> nr_ms2_spectra_;
};
}
|
evolve_shared_collisions.c | /*
* Reference integrators with single, global shared time step.
*/
#include <tgmath.h>
#include <stdio.h>
#include <stdlib.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "evolve.h"
#include "integrators_shared.h"
// AMUSE STOPPING CONDITIONS SUPPORT
#include <stopcond.h>
static void set_dt_levels(DOUBLE *dt_levels, DOUBLE dt){
int i;
dt_levels[0] = dt;
for (i=1; i<MAXLEVEL; i++) {
dt_levels[i] = dt_levels[i-1]/2;
}
}
static DOUBLE time_from_steps(int *steps, DOUBLE *dt_levels) {
DOUBLE time = 0.0L;
int i;
for (i=0; i<MAXLEVEL; i++) {
time += dt_levels[i] * steps[i];
}
return time;
}
static int update_steps_and_get_next_level(int *steps, int current_level) {
while (current_level > 0) {
if (steps[current_level] == 0) {
steps[current_level] = 1;
break;
} else {
steps[current_level] = 0;
current_level--;
}
}
return current_level;
}
static void detect_collisions(struct sys s) {
UINT i, j;
FLOAT dx[3], dr2, radius_sum;
struct particle *ipart, *jpart;
#pragma omp parallel for if((ULONG) s.n*s.n>MPWORKLIMIT && !omp_in_parallel()) default(none) \
private(i,j,dx,dr2,radius_sum, ipart, jpart) \
shared(s)
for (i=0; i<s.n; i++) {
ipart=GETPART(s,i);
for (j=i+1; j<s.n; j++) {
jpart=GETPART(s,j);
dx[0] = ipart->pos[0] - jpart->pos[0];
dx[1] = ipart->pos[1] - jpart->pos[1];
dx[2] = ipart->pos[2] - jpart->pos[2];
dr2 = dx[0]*dx[0] + dx[1]*dx[1] + dx[2]*dx[2];
radius_sum = ipart->radius + jpart->radius;
if (dr2 <= radius_sum*radius_sum) {
#pragma omp critical
{
int stopping_index = next_index_for_stopping_condition();
if (stopping_index >= 0) {
set_stopping_condition_info(stopping_index, COLLISION_DETECTION);
set_stopping_condition_particle_index(stopping_index, 0, ipart->id);
set_stopping_condition_particle_index(stopping_index, 1, jpart->id);
}
}
}
}
}
}
static void evolve_shared_collision_detection(struct sys s, DOUBLE dt, void (*dkd_func)(int, struct sys, DOUBLE, DOUBLE, DOUBLE)) {
FLOAT dtsys;
int next_level, current_level = 0;
DOUBLE etime, stime;
DOUBLE *dt_levels = (DOUBLE*) malloc (MAXLEVEL * sizeof(DOUBLE));
int *step_at_level = (int*) calloc (MAXLEVEL, sizeof(int));
int is_collision_detection_enabled;
if (dt == 0.0L) {
ENDRUN("timestep too small: dt=%Le\n", (long double) dt);
}
is_stopping_condition_enabled(COLLISION_DETECTION, &is_collision_detection_enabled);
set_dt_levels(dt_levels, dt);
do {
timestep(current_level, s, s, SIGN(dt));
dtsys = global_timestep(s);
while (dtsys < fabs(dt_levels[current_level])) {
current_level++;
if (current_level >= MAXLEVEL) {
stime = time_from_steps(step_at_level, dt_levels);
ENDRUN("timestep too small: stime=%Le dt=%Le clevel=%u\n",
(long double) stime, (long double) dt_levels[current_level], current_level);
}
}
diag->deepsteps++;
diag->simtime+=dt_levels[current_level];
stime = time_from_steps(step_at_level, dt_levels);
next_level = update_steps_and_get_next_level(step_at_level, current_level);
etime = time_from_steps(step_at_level, dt_levels);
dkd_func(current_level, s, stime, etime, dt_levels[current_level]);
if (is_collision_detection_enabled) {
detect_collisions(s);
if (set_conditions & enabled_conditions) break;
}
current_level = next_level;
} while (current_level > 0);
free(dt_levels);
free(step_at_level);
}
static void kdk_with_zerosys(int clevel, struct sys s, DOUBLE stime, DOUBLE etime, DOUBLE dt) {
kdk(clevel, s, zerosys, stime, etime, dt);
}
void evolve_shared2_collision_detection(struct sys s, DOUBLE dt) {
evolve_shared_collision_detection(s, dt, kdk_with_zerosys);
}
void evolve_shared4_collision_detection(struct sys s, DOUBLE dt) {
evolve_shared_collision_detection(s, dt, dkd4);
}
void evolve_shared6_collision_detection(struct sys s, DOUBLE dt) {
evolve_shared_collision_detection(s, dt, dkd6);
}
void evolve_shared8_collision_detection(struct sys s, DOUBLE dt) {
evolve_shared_collision_detection(s, dt, dkd8);
}
void evolve_shared10_collision_detection(struct sys s, DOUBLE dt) {
evolve_shared_collision_detection(s, dt, dkd10);
}
|
shallow_water_utilities.h | // | / |
// ' / __| _` | __| _ \ __|
// . \ | ( | | ( |\__ `
// _|\_\_| \__,_|\__|\___/ ____/
// Multi-Physics
//
// License: BSD License
// Kratos default license: kratos/license.txt
//
// Main authors: Miguel Maso Sotomayor
//
#ifndef KRATOS_SHALLOW_WATER_UTILITIES_H_INCLUDED
#define KRATOS_SHALLOW_WATER_UTILITIES_H_INCLUDED
// System includes
// External includes
// Project includes
#include "includes/model_part.h"
namespace Kratos
{
///@addtogroup ShallowWaterApplication
///@{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/// Short class definition.
/** Detail class definition.
*/
class KRATOS_API(SHALLOW_WATER_APPLICATION) ShallowWaterUtilities
{
public:
///@name Type Definitions
///@{
/// Pointer definition of ShallowWaterUtilities
KRATOS_CLASS_POINTER_DEFINITION(ShallowWaterUtilities);
///@}
///@name Life Cycle
///@{
/// Default constructor.
/// Destructor.
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
void ComputeFreeSurfaceElevation(ModelPart& rModelPart);
void ComputeHeightFromFreeSurface(ModelPart& rModelPart);
void ComputeVelocity(ModelPart& rModelPart);
void ComputeMomentum(ModelPart& rModelPart);
void ComputeEnergy(ModelPart& rModelPart);
void ComputeAccelerations(ModelPart& rModelPart);
void FlipScalarVariable(Variable<double>& rOriginVariable, Variable<double>& rDestinationVariable, ModelPart& rModelPart);
void IdentifySolidBoundary(ModelPart& rModelPart, double SeaWaterLevel, Flags SolidBoundaryFlag);
void IdentifyWetDomain(ModelPart& rModelPart, Flags WetFlag, double Thickness = 0.0);
void ResetDryDomain(ModelPart& rModelPart, double Thickness = 0.0);
template<class TContainerType>
void DeactivateDryEntities(TContainerType& rContainer, Flags WetFlag)
{
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rContainer.size()); ++i)
{
auto it = rContainer.begin() + i;
it->Set(ACTIVE, it->Is(WetFlag));
}
}
void NormalizeVector(ModelPart& rModelPart, Variable<array_1d<double,3>>& rVariable);
template<class TVarType>
void CopyVariableToPreviousTimeStep(ModelPart& rModelPart, const TVarType& rVariable)
{
#pragma omp parallel for
for (int i = 0; i < static_cast<int>(rModelPart.NumberOfNodes()); ++i)
{
auto const it_node = rModelPart.NodesBegin() + i;
it_node->FastGetSolutionStepValue(rVariable,1) = it_node->FastGetSolutionStepValue(rVariable);
}
}
void SetMinimumValue(ModelPart& rModelPart, const Variable<double>& rVariable, double MinValue);
/*
* @brief This method sets the z-coordinate of the mesh to zero
*/
void SetMeshZCoordinateToZero(ModelPart& rModelPart);
/*
* @brief This method moves the z-coordinate of the mesh according to a variable
*/
void SetMeshZCoordinate(ModelPart& rModelPart, const Variable<double>& rVariable);
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
}; // Class ShallowWaterUtilities
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
///@}
///@} addtogroup block
} // namespace Kratos.
#endif // KRATOS_SHALLOW_WATER_UTILITIES_H_INCLUDED defined
|
tinyexr.h | /*
Copyright (c) 2014 - 2015, Syoyo Fujita
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __TINYEXR_H__
#define __TINYEXR_H__
//
//
// Do this:
// #define TINYEXR_IMPLEMENTATION
// before you include this file in *one* C or C++ file to create the
// implementation.
//
// // i.e. it should look like this:
// #include ...
// #include ...
// #include ...
// #define TINYEXR_IMPLEMENTATION
// #include "tinyexr.h"
//
//
#include <stddef.h> // for size_t
#ifdef __cplusplus
extern "C" {
#endif
// pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2
#define TINYEXR_PIXELTYPE_UINT (0)
#define TINYEXR_PIXELTYPE_HALF (1)
#define TINYEXR_PIXELTYPE_FLOAT (2)
#define TINYEXR_MAX_ATTRIBUTES (128)
#define TINYEXR_COMPRESSIONTYPE_NONE (0)
//#define TINYEXR_COMPRESSIONTYPE_RLE (1) // not supported yet
#define TINYEXR_COMPRESSIONTYPE_ZIPS (2)
#define TINYEXR_COMPRESSIONTYPE_ZIP (3)
#define TINYEXR_COMPRESSIONTYPE_PIZ (4)
typedef struct _EXRAttribute {
char *name;
char *type;
int size;
unsigned char *value; // uint8_t*
} EXRAttribute;
typedef struct _EXRImage {
// Custom attributes(exludes required attributes(e.g. `channels`,
// `compression`, etc)
EXRAttribute custom_attributes[TINYEXR_MAX_ATTRIBUTES];
int num_custom_attributes;
int num_channels;
const char **channel_names;
unsigned char **images; // image[channels][pixels]
int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for
// each channel
int *requested_pixel_types; // Filled initially by
// ParseEXRHeaderFrom(Meomory|File), then users
// can edit it(only valid for HALF pixel type
// channel)
int width;
int height;
float pixel_aspect_ratio;
int compression; // compression type(TINYEXR_COMPRESSIONTYPE_*)
int line_order;
int data_window[4];
int display_window[4];
float screen_window_center[2];
float screen_window_width;
} EXRImage;
typedef struct _DeepImage {
int num_channels;
const char **channel_names;
float ***image; // image[channels][scanlines][samples]
int **offset_table; // offset_table[scanline][offsets]
int width;
int height;
} DeepImage;
// @deprecated { to be removed. }
// Loads single-frame OpenEXR image. Assume EXR image contains RGB(A) channels.
// Application must free image data as returned by `out_rgba`
// Result image format is: float x RGBA x width x hight
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadEXR(float **out_rgba, int *width, int *height,
const char *filename, const char **err);
// Parse single-frame OpenEXR header from a file and initialize `EXRImage`
// struct.
// Users then call LoadMultiChannelEXRFromFile to actually load image data into
// `EXRImage`
extern int ParseMultiChannelEXRHeaderFromFile(EXRImage *image,
const char *filename,
const char **err);
// Parse single-frame OpenEXR header from a memory and initialize `EXRImage`
// struct.
// Users then call LoadMultiChannelEXRFromMemory to actually load image data
// into `EXRImage`
extern int ParseMultiChannelEXRHeaderFromMemory(EXRImage *image,
const unsigned char *memory,
const char **err);
// Loads multi-channel, single-frame OpenEXR image from a file.
// Application must setup `ParseMultiChannelEXRHeaderFromFile` before calling
// `LoadMultiChannelEXRFromFile`.
// Application can free EXRImage using `FreeExrImage`
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadMultiChannelEXRFromFile(EXRImage *image, const char *filename,
const char **err);
// Loads multi-channel, single-frame OpenEXR image from a memory.
// Application must setup `EXRImage` with `ParseMultiChannelEXRHeaderFromMemory`
// before calling `LoadMultiChannelEXRFromMemory`.
// Application can free EXRImage using `FreeExrImage`
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadMultiChannelEXRFromMemory(EXRImage *image,
const unsigned char *memory,
const char **err);
// Saves floating point RGBA image as OpenEXR.
// Image is compressed using EXRImage.compression value.
// Return 0 if success
// Returns error string in `err` when there's an error
// extern int SaveEXR(const float *in_rgba, int width, int height,
// const char *filename, const char **err);
// Saves multi-channel, single-frame OpenEXR image to a file.
// `compression_type` is one of TINYEXR_COMPRESSIONTYPE_*.
// Returns 0 if success
// Returns error string in `err` when there's an error
extern int SaveMultiChannelEXRToFile(const EXRImage *image,
const char *filename, const char **err);
// Saves multi-channel, single-frame OpenEXR image to a memory.
// Image is compressed using EXRImage.compression value.
// Return the number of bytes if succes.
// Retruns 0 if success, negative number when failed.
// Returns error string in `err` when there's an error
extern size_t SaveMultiChannelEXRToMemory(const EXRImage *image,
unsigned char **memory,
const char **err);
// Loads single-frame OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// Returns 0 if success
// Returns error string in `err` when there's an error
extern int LoadDeepEXR(DeepImage *out_image, const char *filename,
const char **err);
// NOT YET IMPLEMENTED:
// Saves single-frame OpenEXR deep image.
// Return 0 if success
// Returns error string in `err` when there's an error
// extern int SaveDeepEXR(const DeepImage *in_image, const char *filename,
// const char **err);
// NOT YET IMPLEMENTED:
// Loads multi-part OpenEXR deep image.
// Application must free memory of variables in DeepImage(image, offset_table)
// extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const
// char *filename,
// const char **err);
// Initialize of EXRImage struct
extern void InitEXRImage(EXRImage *exrImage);
// Free's internal data of EXRImage struct
// Returns 0 if success.
extern int FreeEXRImage(EXRImage *exrImage);
// For emscripten.
// Parse single-frame OpenEXR header from memory.
// Return 0 if success
extern int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
int *numCustomAttributes, int *width,
int *height, const unsigned char *memory);
// For emscripten.
// Loads single-frame OpenEXR image from memory. Assume EXR image contains
// RGB(A) channels.
// `out_rgba` must have enough memory(at least sizeof(float) x 4(RGBA) x width x
// hight)
// Return 0 if success
// Returns error string in `err` when there's an error
extern int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
const char **err);
#ifdef __cplusplus
}
#endif
#ifdef TINYEXR_IMPLEMENTATION
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include "tinyexr.h"
#ifdef _OPENMP
#include <omp.h>
#endif
namespace {
namespace miniz {
/* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP
reading/writing/appending, PNG writing
See "unlicense" statement at the end of this file.
Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951:
http://www.ietf.org/rfc/rfc1951.txt
Most API's defined in miniz.c are optional. For example, to disable the
archive related functions just define
MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO
(see the list below for more macros).
* Change History
10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major
release with Zip64 support (almost there!):
- Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug
(thanks kahmyong.moon@hp.com) which could cause locate files to not find
files. This bug
would only have occured in earlier versions if you explicitly used this
flag, OR if you used mz_zip_extract_archive_file_to_heap() or
mz_zip_add_mem_to_archive_file_in_place()
(which used this flag). If you can't switch to v1.15 but want to fix
this bug, just remove the uses of this flag from both helper funcs (and of
course don't use the flag).
- Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when
pUser_read_buf is not NULL and compressed size is > uncompressed size
- Fixing mz_zip_reader_extract_*() funcs so they don't try to extract
compressed data from directory entries, to account for weird zipfiles which
contain zero-size compressed data on dir entries.
Hopefully this fix won't cause any issues on weird zip archives,
because it assumes the low 16-bits of zip external attributes are DOS
attributes (which I believe they always are in practice).
- Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the
internal attributes, just the filename and external attributes
- mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
- Added cmake support for Linux builds which builds all the examples,
tested with clang v3.3 and gcc v4.6.
- Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
- Merged MZ_FORCEINLINE fix from hdeanclark
- Fix <time.h> include before config #ifdef, thanks emil.brink
- Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping
(super useful for OpenGL apps), and explicit control over the compression
level (so you can
set it to 1 for real-time compression).
- Merged in some compiler fixes from paulharris's github repro.
- Retested this build under Windows (VS 2010, including static analysis),
tcc 0.9.26, gcc v4.6 and clang v3.3.
- Added example6.c, which dumps an image of the mandelbrot set to a PNG
file.
- Modified example2 to help test the
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
- In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix
possible src file fclose() leak if alignment bytes+local header file write
faiiled
- In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader():
Was pushing the wrong central dir header offset, appears harmless in this
release, but it became a problem in the zip64 branch
5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE,
#include <time.h> (thanks fermtect).
5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix
mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
- Temporarily/locally slammed in "typedef unsigned long mz_ulong" and
re-ran a randomized regression test on ~500k files.
- Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
- Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze
(static analysis) option and fixed all warnings (except for the silly
"Use of the comma-operator in a tested expression.." analysis warning,
which I purposely use to work around a MSVC compiler warning).
- Created 32-bit and 64-bit Codeblocks projects/workspace. Built and
tested Linux executables. The codeblocks workspace is compatible with
Linux+Win32/x64.
- Added miniz_tester solution/project, which is a useful little app
derived from LZHAM's tester app that I use as part of the regression test.
- Ran miniz.c and tinfl.c through another series of regression testing on
~500,000 files and archives.
- Modified example5.c so it purposely disables a bunch of high-level
functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the
MINIZ_NO_STDIO bug report.)
- Fix ftell() usage in examples so they exit with an error on files which
are too large (a limitation of the examples, not miniz itself).
4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple
minor level_and_flags issues in the archive API's.
level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce
Dawson <bruced@valvesoftware.com> for the feedback/bug report.
5/28/11 v1.11 - Added statement from unlicense.org
5/27/11 v1.10 - Substantial compressor optimizations:
- Level 1 is now ~4x faster than before. The L1 compressor's throughput
now varies between 70-110MB/sec. on a
- Core i7 (actual throughput varies depending on the type of data, and x64
vs. x86).
- Improved baseline L2-L9 compression perf. Also, greatly improved
compression perf. issues on some file types.
- Refactored the compression code for better readability and
maintainability.
- Added level 10 compression level (L10 has slightly better ratio than
level 9, but could have a potentially large
drop in throughput on some files).
5/15/11 v1.09 - Initial stable release.
* Low-level Deflate/Inflate implementation notes:
Compression: Use the "tdefl" API's. The compressor supports raw, static,
and dynamic blocks, lazy or
greedy parsing, match length filtering, RLE-only, and Huffman-only streams.
It performs and compresses
approximately as well as zlib.
Decompression: Use the "tinfl" API's. The entire decompressor is
implemented as a single function
coroutine: see tinfl_decompress(). It supports decompression into a 32KB
(or larger power of 2) wrapping buffer, or into a memory
block large enough to hold the entire file.
The low-level tdefl/tinfl API's do not make any use of dynamic memory
allocation.
* zlib-style API notes:
miniz.c implements a fairly large subset of zlib. There's enough
functionality present for it to be a drop-in
zlib replacement in many apps:
The z_stream struct, optional memory allocation callbacks
deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
inflateInit/inflateInit2/inflate/inflateEnd
compress, compress2, compressBound, uncompress
CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly
routines.
Supports raw deflate streams or standard zlib streams with adler-32
checking.
Limitations:
The callback API's are not implemented yet. No support for gzip headers or
zlib static dictionaries.
I've tried to closely emulate zlib's various flavors of stream flushing
and return status codes, but
there are no guarantees that miniz.c pulls this off perfectly.
* PNG writing: See the tdefl_write_image_to_png_file_in_memory() function,
originally written by
Alex Evans. Supports 1-4 bytes/pixel images.
* ZIP archive API notes:
The ZIP archive API's where designed with simplicity and efficiency in
mind, with just enough abstraction to
get the job done with minimal fuss. There are simple API's to retrieve file
information, read files from
existing archives, create new archives, append new files to existing
archives, or clone archive data from
one archive to another. It supports archives located in memory or the heap,
on disk (using stdio.h),
or you can specify custom file read/write callbacks.
- Archive reading: Just call this function to read a single file from a
disk archive:
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const
char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
For more complex cases, use the "mz_zip_reader" functions. Upon opening an
archive, the entire central
directory is located and read as-is into memory, and subsequent file access
only occurs when reading individual files.
- Archives file scanning: The simple way is to use this function to scan a
loaded archive for a specific file:
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
The locate operation can optionally check file comments too, which (as one
example) can be used to identify
multiple versions of the same file in an archive. This function uses a
simple linear search through the central
directory, so it's not very fast.
Alternately, you can iterate through all the files in an archive (using
mz_zip_reader_get_num_files()) and
retrieve detailed info on each file by calling mz_zip_reader_file_stat().
- Archive creation: Use the "mz_zip_writer" functions. The ZIP writer
immediately writes compressed file data
to disk and builds an exact image of the central directory in memory. The
central directory image is written
all at once at the end of the archive file when the archive is finalized.
The archive writer can optionally align each file's local header and file
data to any power of 2 alignment,
which can be useful when the archive will be read from optical media. Also,
the writer supports placing
arbitrary data blobs at the very beginning of ZIP archives. Archives
written using either feature are still
readable by any ZIP tool.
- Archive appending: The simple way to add a single file to an archive is
to call this function:
mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename,
const char *pArchive_name,
const void *pBuf, size_t buf_size, const void *pComment, mz_uint16
comment_size, mz_uint level_and_flags);
The archive will be created if it doesn't already exist, otherwise it'll be
appended to.
Note the appending is done in-place and is not an atomic operation, so if
something goes wrong
during the operation it's possible the archive could be left without a
central directory (although the local
file headers and file data will be fine, so the archive will be
recoverable).
For more complex archive modification scenarios:
1. The safest way is to use a mz_zip_reader to read the existing archive,
cloning only those bits you want to
preserve into a new archive using using the
mz_zip_writer_add_from_zip_reader() function (which compiles the
compressed file data as-is). When you're done, delete the old archive and
rename the newly written archive, and
you're done. This is safe but requires a bunch of temporary disk space or
heap memory.
2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using
mz_zip_writer_init_from_reader(),
append new files as needed, then finalize the archive which will write an
updated central directory to the
original archive. (This is basically what
mz_zip_add_mem_to_archive_file_in_place() does.) There's a
possibility that the archive's central directory could be lost with this
method if anything goes wrong, though.
- ZIP archive support limitations:
No zip64 or spanning support. Extraction functions can only handle
unencrypted, stored or deflated files.
Requires streams capable of seeking.
* This is a header file library, like stb_image.c. To get only a header file,
either cut and paste the
below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then
include miniz.c from it.
* Important: For best perf. be sure to customize the below macros for your
target platform:
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_LITTLE_ENDIAN 1
#define MINIZ_HAS_64BIT_REGISTERS 1
* On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before
including miniz.c to ensure miniz
uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be
able to process large files
(i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
*/
#ifndef MINIZ_HEADER_INCLUDED
#define MINIZ_HEADER_INCLUDED
#include <stdlib.h>
// Defines to completely disable specific portions of miniz.c:
// If all macros here are defined the only functionality remaining will be
// CRC-32, adler-32, tinfl, and tdefl.
// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on
// stdio for file I/O.
//#define MINIZ_NO_STDIO
// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able
// to get the current time, or
// get/set file times, and the C run-time funcs that get/set times won't be
// called.
// The current downside is the times written to your archives will be from 1979.
//#define MINIZ_NO_TIME
// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
//#define MINIZ_NO_ARCHIVE_APIS
// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive
// API's.
//#define MINIZ_NO_ARCHIVE_WRITING_APIS
// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression
// API's.
//#define MINIZ_NO_ZLIB_APIS
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent
// conflicts against stock zlib.
//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom
// user alloc/free/realloc
// callbacks to the zlib and archive API's, and a few stand-alone helper API's
// which don't provide custom user
// functions (such as tdefl_compress_mem_to_heap() and
// tinfl_decompress_mem_to_heap()) won't work.
//#define MINIZ_NO_MALLOC
#if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
// TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc
// on Linux
#define MINIZ_NO_TIME
#endif
#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
#include <time.h>
#endif
#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__i386) || defined(__i486__) || defined(__i486) || \
defined(i386) || defined(__ia64__) || defined(__x86_64__)
// MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
#define MINIZ_X86_OR_X64_CPU 1
#endif
#if defined(__sparcv9)
// Big endian
#else
#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
#define MINIZ_LITTLE_ENDIAN 1
#endif
#endif
#if MINIZ_X86_OR_X64_CPU
// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient
// integer loads and stores from unaligned addresses.
//#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \
0 // disable to suppress compiler warnings
#endif
#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \
defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \
defined(__x86_64__)
// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are
// reasonably fast (and don't involve compiler generated calls to helper
// functions).
#define MINIZ_HAS_64BIT_REGISTERS 1
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API Definitions.
// For more compatibility with zlib, miniz.c uses unsigned long for some
// parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
typedef unsigned long mz_ulong;
// mz_free() internally uses the MZ_FREE() macro (which by default calls free()
// unless you've modified the MZ_MALLOC macro) to release a block allocated from
// the heap.
void mz_free(void *p);
#define MZ_ADLER32_INIT (1)
// mz_adler32() returns the initial adler-32 value to use when called with
// ptr==NULL.
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
#define MZ_CRC32_INIT (0)
// mz_crc32() returns the initial CRC-32 value to use when called with
// ptr==NULL.
mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
// Compression strategies.
enum {
MZ_DEFAULT_STRATEGY = 0,
MZ_FILTERED = 1,
MZ_HUFFMAN_ONLY = 2,
MZ_RLE = 3,
MZ_FIXED = 4
};
// Method
#define MZ_DEFLATED 8
#ifndef MINIZ_NO_ZLIB_APIS
// Heap allocation callbacks.
// Note that mz_alloc_func parameter types purpsosely differ from zlib's:
// items/size is size_t, not unsigned long.
typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
typedef void (*mz_free_func)(void *opaque, void *address);
typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items,
size_t size);
#define MZ_VERSION "9.1.15"
#define MZ_VERNUM 0x91F0
#define MZ_VER_MAJOR 9
#define MZ_VER_MINOR 1
#define MZ_VER_REVISION 15
#define MZ_VER_SUBREVISION 0
// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The
// other values are for advanced use (refer to the zlib docs).
enum {
MZ_NO_FLUSH = 0,
MZ_PARTIAL_FLUSH = 1,
MZ_SYNC_FLUSH = 2,
MZ_FULL_FLUSH = 3,
MZ_FINISH = 4,
MZ_BLOCK = 5
};
// Return status codes. MZ_PARAM_ERROR is non-standard.
enum {
MZ_OK = 0,
MZ_STREAM_END = 1,
MZ_NEED_DICT = 2,
MZ_ERRNO = -1,
MZ_STREAM_ERROR = -2,
MZ_DATA_ERROR = -3,
MZ_MEM_ERROR = -4,
MZ_BUF_ERROR = -5,
MZ_VERSION_ERROR = -6,
MZ_PARAM_ERROR = -10000
};
// Compression levels: 0-9 are the standard zlib-style levels, 10 is best
// possible compression (not zlib compatible, and may be very slow),
// MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
enum {
MZ_NO_COMPRESSION = 0,
MZ_BEST_SPEED = 1,
MZ_BEST_COMPRESSION = 9,
MZ_UBER_COMPRESSION = 10,
MZ_DEFAULT_LEVEL = 6,
MZ_DEFAULT_COMPRESSION = -1
};
// Window bits
#define MZ_DEFAULT_WINDOW_BITS 15
struct mz_internal_state;
// Compression/decompression stream struct.
typedef struct mz_stream_s {
const unsigned char *next_in; // pointer to next byte to read
unsigned int avail_in; // number of bytes available at next_in
mz_ulong total_in; // total number of bytes consumed so far
unsigned char *next_out; // pointer to next byte to write
unsigned int avail_out; // number of bytes that can be written to next_out
mz_ulong total_out; // total number of bytes produced so far
char *msg; // error msg (unused)
struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
mz_alloc_func
zalloc; // optional heap allocation function (defaults to malloc)
mz_free_func zfree; // optional heap free function (defaults to free)
void *opaque; // heap alloc function user pointer
int data_type; // data_type (unused)
mz_ulong adler; // adler32 of the source or uncompressed data
mz_ulong reserved; // not used
} mz_stream;
typedef mz_stream *mz_streamp;
// Returns the version string of miniz.c.
const char *mz_version(void);
// mz_deflateInit() initializes a compressor with default options:
// Parameters:
// pStream must point to an initialized mz_stream struct.
// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
// level 1 enables a specially optimized compression function that's been
// optimized purely for performance, not ratio.
// (This special func. is currently only enabled when
// MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if the input parameters are bogus.
// MZ_MEM_ERROR on out of memory.
int mz_deflateInit(mz_streamp pStream, int level);
// mz_deflateInit2() is like mz_deflate(), except with more control:
// Additional parameters:
// method must be MZ_DEFLATED
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with
// zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no
// header or footer)
// mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy);
// Quickly resets a compressor without having to reallocate anything. Same as
// calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
int mz_deflateReset(mz_streamp pStream);
// mz_deflate() compresses the input to output, consuming as much of the input
// and producing as much output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or
// MZ_FINISH.
// Return values:
// MZ_OK on success (when flushing, or if more input is needed but not
// available, and/or there's more output to be written but the output buffer
// is full).
// MZ_STREAM_END if all input has been consumed and all output bytes have been
// written. Don't call mz_deflate() on the stream anymore.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input and/or
// output buffers are empty. (Fill up the input buffer or free up some output
// space and try again.)
int mz_deflate(mz_streamp pStream, int flush);
// mz_deflateEnd() deinitializes a compressor:
// Return values:
// MZ_OK on success.
// MZ_STREAM_ERROR if the stream is bogus.
int mz_deflateEnd(mz_streamp pStream);
// mz_deflateBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by deflate(), assuming flush is set to only
// MZ_NO_FLUSH or MZ_FINISH.
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
// Single-call compression functions mz_compress() and mz_compress2():
// Returns MZ_OK on success, or one of the error codes from mz_deflate() on
// failure.
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level);
// mz_compressBound() returns a (very) conservative upper bound on the amount of
// data that could be generated by calling mz_compress().
mz_ulong mz_compressBound(mz_ulong source_len);
// Initializes a decompressor.
int mz_inflateInit(mz_streamp pStream);
// mz_inflateInit2() is like mz_inflateInit() with an additional option that
// controls the window size and whether or not the stream has been wrapped with
// a zlib header/footer:
// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or
// -MZ_DEFAULT_WINDOW_BITS (raw deflate).
int mz_inflateInit2(mz_streamp pStream, int window_bits);
// Decompresses the input stream to the output, consuming only as much of the
// input as needed, and writing as much to the output as possible.
// Parameters:
// pStream is the stream to read from and write to. You must initialize/update
// the next_in, avail_in, next_out, and avail_out members.
// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
// On the first call, if flush is MZ_FINISH it's assumed the input and output
// buffers are both sized large enough to decompress the entire stream in a
// single call (this is slightly faster).
// MZ_FINISH implies that there are no more source bytes available beside
// what's already in the input buffer, and that the output buffer is large
// enough to hold the rest of the decompressed data.
// Return values:
// MZ_OK on success. Either more input is needed but not available, and/or
// there's more output to be written but the output buffer is full.
// MZ_STREAM_END if all needed input has been consumed and all output bytes
// have been written. For zlib streams, the adler-32 of the decompressed data
// has also been verified.
// MZ_STREAM_ERROR if the stream is bogus.
// MZ_DATA_ERROR if the deflate stream is invalid.
// MZ_PARAM_ERROR if one of the parameters is invalid.
// MZ_BUF_ERROR if no forward progress is possible because the input buffer is
// empty but the inflater needs more input to continue, or if the output
// buffer is not large enough. Call mz_inflate() again
// with more input data, or with more room in the output buffer (except when
// using single call decompression, described above).
int mz_inflate(mz_streamp pStream, int flush);
// Deinitializes a decompressor.
int mz_inflateEnd(mz_streamp pStream);
// Single-call decompression.
// Returns MZ_OK on success, or one of the error codes from mz_inflate() on
// failure.
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len);
// Returns a string description of the specified error code, or NULL if the
// error code is invalid.
const char *mz_error(int err);
// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used
// as a drop-in replacement for the subset of zlib that miniz.c supports.
// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you
// use zlib in the same project.
#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
typedef unsigned char Byte;
typedef unsigned int uInt;
typedef mz_ulong uLong;
typedef Byte Bytef;
typedef uInt uIntf;
typedef char charf;
typedef int intf;
typedef void *voidpf;
typedef uLong uLongf;
typedef void *voidp;
typedef void *const voidpc;
#define Z_NULL 0
#define Z_NO_FLUSH MZ_NO_FLUSH
#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
#define Z_SYNC_FLUSH MZ_SYNC_FLUSH
#define Z_FULL_FLUSH MZ_FULL_FLUSH
#define Z_FINISH MZ_FINISH
#define Z_BLOCK MZ_BLOCK
#define Z_OK MZ_OK
#define Z_STREAM_END MZ_STREAM_END
#define Z_NEED_DICT MZ_NEED_DICT
#define Z_ERRNO MZ_ERRNO
#define Z_STREAM_ERROR MZ_STREAM_ERROR
#define Z_DATA_ERROR MZ_DATA_ERROR
#define Z_MEM_ERROR MZ_MEM_ERROR
#define Z_BUF_ERROR MZ_BUF_ERROR
#define Z_VERSION_ERROR MZ_VERSION_ERROR
#define Z_PARAM_ERROR MZ_PARAM_ERROR
#define Z_NO_COMPRESSION MZ_NO_COMPRESSION
#define Z_BEST_SPEED MZ_BEST_SPEED
#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
#define Z_FILTERED MZ_FILTERED
#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
#define Z_RLE MZ_RLE
#define Z_FIXED MZ_FIXED
#define Z_DEFLATED MZ_DEFLATED
#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
#define alloc_func mz_alloc_func
#define free_func mz_free_func
#define internal_state mz_internal_state
#define z_stream mz_stream
#define deflateInit mz_deflateInit
#define deflateInit2 mz_deflateInit2
#define deflateReset mz_deflateReset
#define deflate mz_deflate
#define deflateEnd mz_deflateEnd
#define deflateBound mz_deflateBound
#define compress mz_compress
#define compress2 mz_compress2
#define compressBound mz_compressBound
#define inflateInit mz_inflateInit
#define inflateInit2 mz_inflateInit2
#define inflate mz_inflate
#define inflateEnd mz_inflateEnd
#define uncompress mz_uncompress
#define crc32 mz_crc32
#define adler32 mz_adler32
#define MAX_WBITS 15
#define MAX_MEM_LEVEL 9
#define zError mz_error
#define ZLIB_VERSION MZ_VERSION
#define ZLIB_VERNUM MZ_VERNUM
#define ZLIB_VER_MAJOR MZ_VER_MAJOR
#define ZLIB_VER_MINOR MZ_VER_MINOR
#define ZLIB_VER_REVISION MZ_VER_REVISION
#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
#define zlibVersion mz_version
#define zlib_version mz_version()
#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Types and macros
typedef unsigned char mz_uint8;
typedef signed short mz_int16;
typedef unsigned short mz_uint16;
typedef unsigned int mz_uint32;
typedef unsigned int mz_uint;
typedef long long mz_int64;
typedef unsigned long long mz_uint64;
typedef int mz_bool;
#define MZ_FALSE (0)
#define MZ_TRUE (1)
// An attempt to work around MSVC's spammy "warning C4127: conditional
// expression is constant" message.
#ifdef _MSC_VER
#define MZ_MACRO_END while (0, 0)
#else
#define MZ_MACRO_END while (0)
#endif
// ------------------- ZIP archive reading/writing
#ifndef MINIZ_NO_ARCHIVE_APIS
enum {
MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024,
MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
};
typedef struct {
mz_uint32 m_file_index;
mz_uint32 m_central_dir_ofs;
mz_uint16 m_version_made_by;
mz_uint16 m_version_needed;
mz_uint16 m_bit_flag;
mz_uint16 m_method;
#ifndef MINIZ_NO_TIME
time_t m_time;
#endif
mz_uint32 m_crc32;
mz_uint64 m_comp_size;
mz_uint64 m_uncomp_size;
mz_uint16 m_internal_attr;
mz_uint32 m_external_attr;
mz_uint64 m_local_header_ofs;
mz_uint32 m_comment_size;
char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
} mz_zip_archive_file_stat;
typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n);
typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n);
struct mz_zip_internal_state_tag;
typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
typedef enum {
MZ_ZIP_MODE_INVALID = 0,
MZ_ZIP_MODE_READING = 1,
MZ_ZIP_MODE_WRITING = 2,
MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
} mz_zip_mode;
typedef struct mz_zip_archive_tag {
mz_uint64 m_archive_size;
mz_uint64 m_central_directory_file_ofs;
mz_uint m_total_files;
mz_zip_mode m_zip_mode;
mz_uint m_file_offset_alignment;
mz_alloc_func m_pAlloc;
mz_free_func m_pFree;
mz_realloc_func m_pRealloc;
void *m_pAlloc_opaque;
mz_file_read_func m_pRead;
mz_file_write_func m_pWrite;
void *m_pIO_opaque;
mz_zip_internal_state *m_pState;
} mz_zip_archive;
typedef enum {
MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
} mz_zip_flags;
// ZIP archive reading
// Inits a ZIP archive reader.
// These functions read and validate the archive's central directory.
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags);
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags);
#endif
// Returns the total number of files in the archive.
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
// Returns detailed information about an archive file entry.
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat);
// Determines if an archive file entry is a directory entry.
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index);
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index);
// Retrieves the filename of an archive file entry.
// Returns the number of bytes written to pFilename, or if filename_buf_size is
// 0 this function returns the number of bytes needed to fully store the
// filename.
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size);
// Attempts to locates a file in the archive's central directory.
// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
// Returns -1 if the file cannot be found.
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags);
// Extracts a archive file to a memory buffer using no memory allocation.
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size);
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
// Extracts a archive file to a memory buffer.
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags);
// Extracts a archive file to a dynamically allocated heap buffer.
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags);
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags);
// Extracts a archive file using a callback function to output the file's data.
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags);
#ifndef MINIZ_NO_STDIO
// Extracts a archive file to a disk file and sets its last accessed and
// modified times.
// This function only extracts files, not archive directory records.
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename, mz_uint flags);
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags);
#endif
// Ends archive reading, freeing all allocations, and closing the input archive
// file if mz_zip_reader_init_file() was used.
mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
// ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
// Inits a ZIP archive writer.
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size);
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning);
#endif
// Converts a ZIP archive reader object into a writer object, to allow efficient
// in-place file appends to occur on an existing archive.
// For archives opened using mz_zip_reader_init_file, pFilename must be the
// archive's filename so it can be reopened for writing. If the file can't be
// reopened, mz_zip_reader_end() will be called.
// For archives opened using mz_zip_reader_init_mem, the memory block must be
// growable using the realloc callback (which defaults to realloc unless you've
// overridden it).
// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's
// user provided m_pWrite function cannot be NULL.
// Note: In-place archive modification is not recommended unless you know what
// you're doing, because if execution stops or something goes wrong before
// the archive is finalized the file's central directory will be hosed.
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename);
// Adds the contents of a memory buffer to an archive. These functions record
// the current local time into the archive.
// To add a directory entry, call this method with an archive name ending in a
// forwardslash with empty buffer.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags);
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32);
#ifndef MINIZ_NO_STDIO
// Adds the contents of a disk file to an archive. This function also records
// the disk file's modified time into the archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size, mz_uint level_and_flags);
#endif
// Adds a file to an archive by fully cloning the data from another archive.
// This function fully clones the source file's compressed data (no
// recompression), along with its full filename, extra data, and comment fields.
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index);
// Finalizes the archive by writing the central directory records followed by
// the end of central directory record.
// After an archive is finalized, the only valid call on the mz_zip_archive
// struct is mz_zip_writer_end().
// An archive must be manually finalized by calling this function for it to be
// valid.
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize);
// Ends archive writing, freeing all allocations, and closing the output file if
// mz_zip_writer_init_file() was used.
// Note for the archive to be valid, it must have been finalized before ending.
mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
// Misc. high-level helper functions:
// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically)
// appends a memory blob to a ZIP archive.
// level_and_flags - compression level (0-10, see MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or
// just set to MZ_DEFAULT_COMPRESSION.
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags);
// Reads a single file from an archive into a heap block.
// Returns NULL on failure.
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint zip_flags);
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
// ------------------- Low-level Decompression API Definitions
// Decompression flags used by tinfl_decompress().
// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and
// ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the
// input is a raw deflate stream.
// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available
// beyond the end of the supplied input buffer. If clear, the input buffer
// contains all remaining input.
// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large
// enough to hold the entire decompressed stream. If clear, the output buffer is
// at least the size of the dictionary (typically 32KB).
// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the
// decompressed bytes.
enum {
TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
TINFL_FLAG_HAS_MORE_INPUT = 2,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
TINFL_FLAG_COMPUTE_ADLER32 = 8
};
// High level decompression functions:
// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data
// to decompress.
// On return:
// Function returns a pointer to the decompressed data, or NULL on failure.
// *pOut_len will be set to the decompressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must call mz_free() on the returned block when it's no longer
// needed.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block
// in memory.
// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes
// written on success.
#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// tinfl_decompress_mem_to_callback() decompresses a block in memory to an
// internal 32KB buffer, and a user provided callback function will be called to
// flush the buffer.
// Returns 1 on success or 0 on failure.
typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser);
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
struct tinfl_decompressor_tag;
typedef struct tinfl_decompressor_tag tinfl_decompressor;
// Max size of LZ dictionary.
#define TINFL_LZ_DICT_SIZE 32768
// Return status.
typedef enum {
TINFL_STATUS_BAD_PARAM = -3,
TINFL_STATUS_ADLER32_MISMATCH = -2,
TINFL_STATUS_FAILED = -1,
TINFL_STATUS_DONE = 0,
TINFL_STATUS_NEEDS_MORE_INPUT = 1,
TINFL_STATUS_HAS_MORE_OUTPUT = 2
} tinfl_status;
// Initializes the decompressor to its initial state.
#define tinfl_init(r) \
do { \
(r)->m_state = 0; \
} \
MZ_MACRO_END
#define tinfl_get_adler32(r) (r)->m_check_adler32
// Main low-level decompressor coroutine function. This is the only function
// actually needed for decompression. All the other functions are just
// high-level helpers for improved usability.
// This is a universal API, i.e. it can be used as a building block to build any
// desired higher level decompression API. In the limit case, it can be called
// once per every byte input or output.
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags);
// Internal/private bits follow.
enum {
TINFL_MAX_HUFF_TABLES = 3,
TINFL_MAX_HUFF_SYMBOLS_0 = 288,
TINFL_MAX_HUFF_SYMBOLS_1 = 32,
TINFL_MAX_HUFF_SYMBOLS_2 = 19,
TINFL_FAST_LOOKUP_BITS = 10,
TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
};
typedef struct {
mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE],
m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
} tinfl_huff_table;
#ifndef MINIZ_HAS_64BIT_REGISTERS
# define MINIZ_HAS_64BIT_REGISTERS 0
#endif
#ifndef TINFL_USE_64BIT_BITBUF
# if MINIZ_HAS_64BIT_REGISTERS
# define TINFL_USE_64BIT_BITBUF 1
# else
# define TINFL_USE_64BIT_BITBUF 0
# endif
#endif
#if TINFL_USE_64BIT_BITBUF
typedef mz_uint64 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (64)
#else
typedef mz_uint32 tinfl_bit_buf_t;
#define TINFL_BITBUF_SIZE (32)
#endif
struct tinfl_decompressor_tag {
mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type,
m_check_adler32, m_dist, m_counter, m_num_extra,
m_table_sizes[TINFL_MAX_HUFF_TABLES];
tinfl_bit_buf_t m_bit_buf;
size_t m_dist_from_out_buf_start;
tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
mz_uint8 m_raw_header[4],
m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
};
// ------------------- Low-level Compression API Definitions
// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly
// slower, and raw/dynamic blocks will be output more frequently).
#define TDEFL_LESS_MEMORY 0
// tdefl_init() compression flags logically OR'd together (low 12 bits contain
// the max. number of probes per dictionary search):
// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes
// per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap
// compression), 4095=Huffman+LZ (slowest/best compression).
enum {
TDEFL_HUFFMAN_ONLY = 0,
TDEFL_DEFAULT_MAX_PROBES = 128,
TDEFL_MAX_PROBES_MASK = 0xFFF
};
// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before
// the deflate data, and the Adler-32 of the source data at the end. Otherwise,
// you'll get raw deflate data.
// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even
// when not writing zlib headers).
// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more
// efficient lazy parsing.
// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's
// initialization time to the minimum, but the output may vary from run to run
// given the same input (depending on the contents of memory).
// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
// The low 12 bits are reserved to control the max # of hash probes per
// dictionary lookup (see TDEFL_MAX_PROBES_MASK).
enum {
TDEFL_WRITE_ZLIB_HEADER = 0x01000,
TDEFL_COMPUTE_ADLER32 = 0x02000,
TDEFL_GREEDY_PARSING_FLAG = 0x04000,
TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
TDEFL_RLE_MATCHES = 0x10000,
TDEFL_FILTER_MATCHES = 0x20000,
TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
};
// High level compression functions:
// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block
// allocated via malloc().
// On entry:
// pSrc_buf, src_buf_len: Pointer and size of source block to compress.
// flags: The max match finder probes (default is 128) logically OR'd against
// the above flags. Higher probes are slower but improve compression.
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pOut_len will be set to the compressed data's size, which could be larger
// than src_buf_len on uncompressible data.
// The caller must free() the returned block when it's no longer needed.
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags);
// tdefl_compress_mem_to_mem() compresses a block in memory to another block in
// memory.
// Returns 0 on failure.
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags);
// Compresses an image to a compressed PNG file in memory.
// On entry:
// pImage, w, h, and num_chans describe the image to compress. num_chans may be
// 1, 2, 3, or 4.
// The image pitch in bytes per scanline will be w*num_chans. The leftmost
// pixel on the top scanline is stored first in memory.
// level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED,
// MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
// If flip is true, the image will be flipped on the Y axis (useful for OpenGL
// apps).
// On return:
// Function returns a pointer to the compressed data, or NULL on failure.
// *pLen_out will be set to the size of the PNG image file.
// The caller must mz_free() the returned heap block (which will typically be
// larger than *pLen_out) when it's no longer needed.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip);
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out);
// Output stream interface. The compressor uses this interface to write
// compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len,
void *pUser);
// tdefl_compress_mem_to_output() compresses a block to an output stream. The
// above helpers use this function internally.
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
enum {
TDEFL_MAX_HUFF_TABLES = 3,
TDEFL_MAX_HUFF_SYMBOLS_0 = 288,
TDEFL_MAX_HUFF_SYMBOLS_1 = 32,
TDEFL_MAX_HUFF_SYMBOLS_2 = 19,
TDEFL_LZ_DICT_SIZE = 32768,
TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1,
TDEFL_MIN_MATCH_LEN = 3,
TDEFL_MAX_MATCH_LEN = 258
};
// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed
// output block (using static/fixed Huffman codes).
#if TDEFL_LESS_MEMORY
enum {
TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 12,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#else
enum {
TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024,
TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10,
TDEFL_MAX_HUFF_SYMBOLS = 288,
TDEFL_LZ_HASH_BITS = 15,
TDEFL_LEVEL1_HASH_SIZE_MASK = 4095,
TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3,
TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS
};
#endif
// The low-level tdefl functions below may be used directly if the above helper
// functions aren't flexible enough. The low-level functions don't make any heap
// allocations, unlike the above helper functions.
typedef enum {
TDEFL_STATUS_BAD_PARAM = -2,
TDEFL_STATUS_PUT_BUF_FAILED = -1,
TDEFL_STATUS_OKAY = 0,
TDEFL_STATUS_DONE = 1,
} tdefl_status;
// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
typedef enum {
TDEFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4
} tdefl_flush;
// tdefl's compression state structure.
typedef struct {
tdefl_put_buf_func_ptr m_pPut_buf_func;
void *m_pPut_buf_user;
mz_uint m_flags, m_max_probes[2];
int m_greedy_parsing;
mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in,
m_bit_buffer;
mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit,
m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index,
m_wants_to_finish;
tdefl_status m_prev_return_status;
const void *m_pIn_buf;
void *m_pOut_buf;
size_t *m_pIn_buf_size, *m_pOut_buf_size;
tdefl_flush m_flush;
const mz_uint8 *m_pSrc;
size_t m_src_buf_left, m_out_buf_ofs;
mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
} tdefl_compressor;
// Initializes the compressor.
// There is no corresponding deinit() function because the tdefl API's do not
// dynamically allocate memory.
// pBut_buf_func: If NULL, output data will be supplied to the specified
// callback. In this case, the user should call the tdefl_compress_buffer() API
// for compression.
// If pBut_buf_func is NULL the user should always call the tdefl_compress()
// API.
// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER,
// etc.)
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags);
// Compresses a block of data, consuming as much of the specified input buffer
// as possible, and writing as much compressed data to the specified output
// buffer as possible.
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush);
// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a
// non-NULL tdefl_put_buf_func_ptr.
// tdefl_compress_buffer() always consumes the entire input buffer.
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush);
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't
// defined, because it uses some of its macros.
#ifndef MINIZ_NO_ZLIB_APIS
// Create tdefl_compress() flags given zlib-style compression parameters.
// level may range from [0,10] (where 10 is absolute max compression, but may be
// much slower on some files)
// window_bits may be -15 (raw deflate) or 15 (zlib)
// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY,
// MZ_RLE, or MZ_FIXED
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy);
#endif // #ifndef MINIZ_NO_ZLIB_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_INCLUDED
// ------------------- End of Header: Implementation follows. (If you only want
// the header, define MINIZ_HEADER_FILE_ONLY.)
#ifndef MINIZ_HEADER_FILE_ONLY
typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1];
typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1];
typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1];
#include <string.h>
#include <assert.h>
#define MZ_ASSERT(x) assert(x)
#ifdef MINIZ_NO_MALLOC
#define MZ_MALLOC(x) NULL
#define MZ_FREE(x) (void) x, ((void)0)
#define MZ_REALLOC(p, x) NULL
#else
#define MZ_MALLOC(x) malloc(x)
#define MZ_FREE(x) free(x)
#define MZ_REALLOC(p, x) realloc(p, x)
#endif
#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b))
#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b))
#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
#define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
#define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
#else
#define MZ_READ_LE16(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
#define MZ_READ_LE32(p) \
((mz_uint32)(((const mz_uint8 *)(p))[0]) | \
((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \
((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \
((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
#endif
#ifdef _MSC_VER
#define MZ_FORCEINLINE __forceinline
#elif defined(__GNUC__)
#define MZ_FORCEINLINE inline __attribute__((__always_inline__))
#else
#define MZ_FORCEINLINE inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ------------------- zlib-style API's
mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) {
mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16);
size_t block_len = buf_len % 5552;
if (!ptr)
return MZ_ADLER32_INIT;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
return (s2 << 16) + s1;
}
// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C
// implementation that balances processor cache usage against speed":
// http://www.geocities.com/malbrain/
mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) {
static const mz_uint32 s_crc32[16] = {
0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4,
0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c,
0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c};
mz_uint32 crcu32 = (mz_uint32)crc;
if (!ptr)
return MZ_CRC32_INIT;
crcu32 = ~crcu32;
while (buf_len--) {
mz_uint8 b = *ptr++;
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)];
crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)];
}
return ~crcu32;
}
void mz_free(void *p) { MZ_FREE(p); }
#ifndef MINIZ_NO_ZLIB_APIS
static void *def_alloc_func(void *opaque, size_t items, size_t size) {
(void)opaque, (void)items, (void)size;
return MZ_MALLOC(items * size);
}
static void def_free_func(void *opaque, void *address) {
(void)opaque, (void)address;
MZ_FREE(address);
}
static void *def_realloc_func(void *opaque, void *address, size_t items,
size_t size) {
(void)opaque, (void)address, (void)items, (void)size;
return MZ_REALLOC(address, items * size);
}
const char *mz_version(void) { return MZ_VERSION; }
int mz_deflateInit(mz_streamp pStream, int level) {
return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9,
MZ_DEFAULT_STRATEGY);
}
int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits,
int mem_level, int strategy) {
tdefl_compressor *pComp;
mz_uint comp_flags =
TDEFL_COMPUTE_ADLER32 |
tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
if (!pStream)
return MZ_STREAM_ERROR;
if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) ||
((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS)))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = MZ_ADLER32_INIT;
pStream->msg = NULL;
pStream->reserved = 0;
pStream->total_in = 0;
pStream->total_out = 0;
if (!pStream->zalloc)
pStream->zalloc = def_alloc_func;
if (!pStream->zfree)
pStream->zfree = def_free_func;
pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1,
sizeof(tdefl_compressor));
if (!pComp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pComp;
if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) {
mz_deflateEnd(pStream);
return MZ_PARAM_ERROR;
}
return MZ_OK;
}
int mz_deflateReset(mz_streamp pStream) {
if ((!pStream) || (!pStream->state) || (!pStream->zalloc) ||
(!pStream->zfree))
return MZ_STREAM_ERROR;
pStream->total_in = pStream->total_out = 0;
tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL,
((tdefl_compressor *)pStream->state)->m_flags);
return MZ_OK;
}
int mz_deflate(mz_streamp pStream, int flush) {
size_t in_bytes, out_bytes;
mz_ulong orig_total_in, orig_total_out;
int mz_status = MZ_OK;
if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) ||
(!pStream->next_out))
return MZ_STREAM_ERROR;
if (!pStream->avail_out)
return MZ_BUF_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if (((tdefl_compressor *)pStream->state)->m_prev_return_status ==
TDEFL_STATUS_DONE)
return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
orig_total_in = pStream->total_in;
orig_total_out = pStream->total_out;
for (;;) {
tdefl_status defl_status;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
defl_status = tdefl_compress((tdefl_compressor *)pStream->state,
pStream->next_in, &in_bytes, pStream->next_out,
&out_bytes, (tdefl_flush)flush);
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (defl_status < 0) {
mz_status = MZ_STREAM_ERROR;
break;
} else if (defl_status == TDEFL_STATUS_DONE) {
mz_status = MZ_STREAM_END;
break;
} else if (!pStream->avail_out)
break;
else if ((!pStream->avail_in) && (flush != MZ_FINISH)) {
if ((flush) || (pStream->total_in != orig_total_in) ||
(pStream->total_out != orig_total_out))
break;
return MZ_BUF_ERROR; // Can't make forward progress without some input.
}
}
return mz_status;
}
int mz_deflateEnd(mz_streamp pStream) {
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) {
(void)pStream;
// This is really over conservative. (And lame, but it's actually pretty
// tricky to compute a true upper bound given the way tdefl's blocking works.)
return MZ_MAX(128 + (source_len * 110) / 100,
128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
}
int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len, int level) {
int status;
mz_stream stream;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_deflateInit(&stream, level);
if (status != MZ_OK)
return status;
status = mz_deflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_deflateEnd(&stream);
return (status == MZ_OK) ? MZ_BUF_ERROR : status;
}
*pDest_len = stream.total_out;
return mz_deflateEnd(&stream);
}
int mz_compress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
return mz_compress2(pDest, pDest_len, pSource, source_len,
MZ_DEFAULT_COMPRESSION);
}
mz_ulong mz_compressBound(mz_ulong source_len) {
return mz_deflateBound(NULL, source_len);
}
typedef struct {
tinfl_decompressor m_decomp;
mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed;
int m_window_bits;
mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
tinfl_status m_last_status;
} inflate_state;
int mz_inflateInit2(mz_streamp pStream, int window_bits) {
inflate_state *pDecomp;
if (!pStream)
return MZ_STREAM_ERROR;
if ((window_bits != MZ_DEFAULT_WINDOW_BITS) &&
(-window_bits != MZ_DEFAULT_WINDOW_BITS))
return MZ_PARAM_ERROR;
pStream->data_type = 0;
pStream->adler = 0;
pStream->msg = NULL;
pStream->total_in = 0;
pStream->total_out = 0;
pStream->reserved = 0;
if (!pStream->zalloc)
pStream->zalloc = def_alloc_func;
if (!pStream->zfree)
pStream->zfree = def_free_func;
pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1,
sizeof(inflate_state));
if (!pDecomp)
return MZ_MEM_ERROR;
pStream->state = (struct mz_internal_state *)pDecomp;
tinfl_init(&pDecomp->m_decomp);
pDecomp->m_dict_ofs = 0;
pDecomp->m_dict_avail = 0;
pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
pDecomp->m_first_call = 1;
pDecomp->m_has_flushed = 0;
pDecomp->m_window_bits = window_bits;
return MZ_OK;
}
int mz_inflateInit(mz_streamp pStream) {
return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
}
int mz_inflate(mz_streamp pStream, int flush) {
inflate_state *pState;
mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
size_t in_bytes, out_bytes, orig_avail_in;
tinfl_status status;
if ((!pStream) || (!pStream->state))
return MZ_STREAM_ERROR;
if (flush == MZ_PARTIAL_FLUSH)
flush = MZ_SYNC_FLUSH;
if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState = (inflate_state *)pStream->state;
if (pState->m_window_bits > 0)
decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
orig_avail_in = pStream->avail_in;
first_call = pState->m_first_call;
pState->m_first_call = 0;
if (pState->m_last_status < 0)
return MZ_DATA_ERROR;
if (pState->m_has_flushed && (flush != MZ_FINISH))
return MZ_STREAM_ERROR;
pState->m_has_flushed |= (flush == MZ_FINISH);
if ((flush == MZ_FINISH) && (first_call)) {
// MZ_FINISH on the first call implies that the input and output buffers are
// large enough to hold the entire compressed/decompressed file.
decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
in_bytes = pStream->avail_in;
out_bytes = pStream->avail_out;
status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes,
pStream->next_out, pStream->next_out, &out_bytes,
decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pStream->next_out += (mz_uint)out_bytes;
pStream->avail_out -= (mz_uint)out_bytes;
pStream->total_out += (mz_uint)out_bytes;
if (status < 0)
return MZ_DATA_ERROR;
else if (status != TINFL_STATUS_DONE) {
pState->m_last_status = TINFL_STATUS_FAILED;
return MZ_BUF_ERROR;
}
return MZ_STREAM_END;
}
// flush != MZ_FINISH then we must assume there's more input.
if (flush != MZ_FINISH)
decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
if (pState->m_dict_avail) {
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
return ((pState->m_last_status == TINFL_STATUS_DONE) &&
(!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
for (;;) {
in_bytes = pStream->avail_in;
out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
status = tinfl_decompress(
&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict,
pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
pState->m_last_status = status;
pStream->next_in += (mz_uint)in_bytes;
pStream->avail_in -= (mz_uint)in_bytes;
pStream->total_in += (mz_uint)in_bytes;
pStream->adler = tinfl_get_adler32(&pState->m_decomp);
pState->m_dict_avail = (mz_uint)out_bytes;
n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
pStream->next_out += n;
pStream->avail_out -= n;
pStream->total_out += n;
pState->m_dict_avail -= n;
pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
if (status < 0)
return MZ_DATA_ERROR; // Stream is corrupted (there could be some
// uncompressed data left in the output dictionary -
// oh well).
else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
return MZ_BUF_ERROR; // Signal caller that we can't make forward progress
// without supplying more input or by setting flush
// to MZ_FINISH.
else if (flush == MZ_FINISH) {
// The output buffer MUST be large to hold the remaining uncompressed data
// when flush==MZ_FINISH.
if (status == TINFL_STATUS_DONE)
return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
// status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's
// at least 1 more byte on the way. If there's no more room left in the
// output buffer then something is wrong.
else if (!pStream->avail_out)
return MZ_BUF_ERROR;
} else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) ||
(!pStream->avail_out) || (pState->m_dict_avail))
break;
}
return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail))
? MZ_STREAM_END
: MZ_OK;
}
int mz_inflateEnd(mz_streamp pStream) {
if (!pStream)
return MZ_STREAM_ERROR;
if (pStream->state) {
pStream->zfree(pStream->opaque, pStream->state);
pStream->state = NULL;
}
return MZ_OK;
}
int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len,
const unsigned char *pSource, mz_ulong source_len) {
mz_stream stream;
int status;
memset(&stream, 0, sizeof(stream));
// In case mz_ulong is 64-bits (argh I hate longs).
if ((source_len | *pDest_len) > 0xFFFFFFFFU)
return MZ_PARAM_ERROR;
stream.next_in = pSource;
stream.avail_in = (mz_uint32)source_len;
stream.next_out = pDest;
stream.avail_out = (mz_uint32)*pDest_len;
status = mz_inflateInit(&stream);
if (status != MZ_OK)
return status;
status = mz_inflate(&stream, MZ_FINISH);
if (status != MZ_STREAM_END) {
mz_inflateEnd(&stream);
return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR
: status;
}
*pDest_len = stream.total_out;
return mz_inflateEnd(&stream);
}
const char *mz_error(int err) {
static struct {
int m_err;
const char *m_pDesc;
} s_error_descs[] = {{MZ_OK, ""},
{MZ_STREAM_END, "stream end"},
{MZ_NEED_DICT, "need dictionary"},
{MZ_ERRNO, "file error"},
{MZ_STREAM_ERROR, "stream error"},
{MZ_DATA_ERROR, "data error"},
{MZ_MEM_ERROR, "out of memory"},
{MZ_BUF_ERROR, "buf error"},
{MZ_VERSION_ERROR, "version error"},
{MZ_PARAM_ERROR, "parameter error"}};
mz_uint i;
for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i)
if (s_error_descs[i].m_err == err)
return s_error_descs[i].m_pDesc;
return NULL;
}
#endif // MINIZ_NO_ZLIB_APIS
// ------------------- Low-level Decompression (completely independent from all
// compression API's)
#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
#define TINFL_MEMSET(p, c, l) memset(p, c, l)
#define TINFL_CR_BEGIN \
switch (r->m_state) { \
case 0:
#define TINFL_CR_RETURN(state_index, result) \
do { \
status = result; \
r->m_state = state_index; \
goto common_exit; \
case state_index: \
; \
} \
MZ_MACRO_END
#define TINFL_CR_RETURN_FOREVER(state_index, result) \
do { \
for (;;) { \
TINFL_CR_RETURN(state_index, result); \
} \
} \
MZ_MACRO_END
#define TINFL_CR_FINISH }
// TODO: If the caller has indicated that there's no more input, and we attempt
// to read beyond the input buf, then something is wrong with the input because
// the inflator never
// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of
// the stream with 0's in this scenario.
#define TINFL_GET_BYTE(state_index, c) \
do { \
if (pIn_buf_cur >= pIn_buf_end) { \
for (;;) { \
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
if (pIn_buf_cur < pIn_buf_end) { \
c = *pIn_buf_cur++; \
break; \
} \
} else { \
c = 0; \
break; \
} \
} \
} else \
c = *pIn_buf_cur++; \
} \
MZ_MACRO_END
#define TINFL_NEED_BITS(state_index, n) \
do { \
mz_uint c; \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < (mz_uint)(n))
#define TINFL_SKIP_BITS(state_index, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
#define TINFL_GET_BITS(state_index, b, n) \
do { \
if (num_bits < (mz_uint)(n)) { \
TINFL_NEED_BITS(state_index, n); \
} \
b = bit_buf & ((1 << (n)) - 1); \
bit_buf >>= (n); \
num_bits -= (n); \
} \
MZ_MACRO_END
// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes
// remaining in the input buffer falls below 2.
// It reads just enough bytes from the input stream that are needed to decode
// the next Huffman code (and absolutely no more). It works by trying to fully
// decode a
// Huffman code by using whatever bits are currently present in the bit buffer.
// If this fails, it reads another byte, and tries again until it succeeds or
// until the
// bit buffer contains >=15 bits (deflate's max. Huffman code size).
#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
do { \
temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
if (temp >= 0) { \
code_len = temp >> 9; \
if ((code_len) && (num_bits >= code_len)) \
break; \
} else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while ((temp < 0) && (num_bits >= (code_len + 1))); \
if (temp >= 0) \
break; \
} \
TINFL_GET_BYTE(state_index, c); \
bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
num_bits += 8; \
} while (num_bits < 15);
// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex
// than you would initially expect because the zlib API expects the decompressor
// to never read
// beyond the final byte of the deflate stream. (In other words, when this macro
// wants to read another byte from the input, it REALLY needs another byte in
// order to fully
// decode the next Huffman code.) Handling this properly is particularly
// important on raw deflate (non-zlib) streams, which aren't followed by a byte
// aligned adler-32.
// The slow path is only executed at the very end of the input buffer.
#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \
do { \
int temp; \
mz_uint code_len, c; \
if (num_bits < 15) { \
if ((pIn_buf_end - pIn_buf_cur) < 2) { \
TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
} else { \
bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \
(((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \
pIn_buf_cur += 2; \
num_bits += 16; \
} \
} \
if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \
0) \
code_len = temp >> 9, temp &= 511; \
else { \
code_len = TINFL_FAST_LOOKUP_BITS; \
do { \
temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
} while (temp < 0); \
} \
sym = temp; \
bit_buf >>= code_len; \
num_bits -= code_len; \
} \
MZ_MACRO_END
tinfl_status tinfl_decompress(tinfl_decompressor *r,
const mz_uint8 *pIn_buf_next,
size_t *pIn_buf_size, mz_uint8 *pOut_buf_start,
mz_uint8 *pOut_buf_next, size_t *pOut_buf_size,
const mz_uint32 decomp_flags) {
static const int s_length_base[31] = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
4, 4, 5, 5, 5, 5, 0, 0, 0};
static const int s_dist_base[32] = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33,
49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0};
static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
static const mz_uint8 s_length_dezigzag[19] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static const int s_min_table_sizes[3] = {257, 1, 4};
tinfl_status status = TINFL_STATUS_FAILED;
mz_uint32 num_bits, dist, counter, num_extra;
tinfl_bit_buf_t bit_buf;
const mz_uint8 *pIn_buf_cur = pIn_buf_next,
*const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
mz_uint8 *pOut_buf_cur = pOut_buf_next,
*const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
size_t out_buf_size_mask =
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)
? (size_t)-1
: ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1,
dist_from_out_buf_start;
// Ensure the output buffer's size is a power of 2, unless the output buffer
// is large enough to hold the entire output file (in which case it doesn't
// matter).
if (((out_buf_size_mask + 1) & out_buf_size_mask) ||
(pOut_buf_next < pOut_buf_start)) {
*pIn_buf_size = *pOut_buf_size = 0;
return TINFL_STATUS_BAD_PARAM;
}
num_bits = r->m_num_bits;
bit_buf = r->m_bit_buf;
dist = r->m_dist;
counter = r->m_counter;
num_extra = r->m_num_extra;
dist_from_out_buf_start = r->m_dist_from_out_buf_start;
TINFL_CR_BEGIN
bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0;
r->m_z_adler32 = r->m_check_adler32 = 1;
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_GET_BYTE(1, r->m_zhdr0);
TINFL_GET_BYTE(2, r->m_zhdr1);
counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) ||
(r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) ||
((out_buf_size_mask + 1) <
(size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
if (counter) {
TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED);
}
}
do {
TINFL_GET_BITS(3, r->m_final, 3);
r->m_type = r->m_final >> 1;
if (r->m_type == 0) {
TINFL_SKIP_BITS(5, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
if (num_bits)
TINFL_GET_BITS(6, r->m_raw_header[counter], 8);
else
TINFL_GET_BYTE(7, r->m_raw_header[counter]);
}
if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) !=
(mz_uint)(0xFFFF ^
(r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) {
TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED);
}
while ((counter) && (num_bits)) {
TINFL_GET_BITS(51, dist, 8);
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)dist;
counter--;
}
while (counter) {
size_t n;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT);
}
while (pIn_buf_cur >= pIn_buf_end) {
if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) {
TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
} else {
TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
}
}
n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur),
(size_t)(pIn_buf_end - pIn_buf_cur)),
counter);
TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n);
pIn_buf_cur += n;
pOut_buf_cur += n;
counter -= (mz_uint)n;
}
} else if (r->m_type == 3) {
TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
} else {
if (r->m_type == 1) {
mz_uint8 *p = r->m_tables[0].m_code_size;
mz_uint i;
r->m_table_sizes[0] = 288;
r->m_table_sizes[1] = 32;
TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
for (i = 0; i <= 143; ++i)
*p++ = 8;
for (; i <= 255; ++i)
*p++ = 9;
for (; i <= 279; ++i)
*p++ = 7;
for (; i <= 287; ++i)
*p++ = 8;
} else {
for (counter = 0; counter < 3; counter++) {
TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]);
r->m_table_sizes[counter] += s_min_table_sizes[counter];
}
MZ_CLEAR_OBJ(r->m_tables[2].m_code_size);
for (counter = 0; counter < r->m_table_sizes[2]; counter++) {
mz_uint s;
TINFL_GET_BITS(14, s, 3);
r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s;
}
r->m_table_sizes[2] = 19;
}
for (; (int)r->m_type >= 0; r->m_type--) {
int tree_next, tree_cur;
tinfl_huff_table *pTable;
mz_uint i, j, used_syms, total, sym_index, next_code[17],
total_syms[16];
pTable = &r->m_tables[r->m_type];
MZ_CLEAR_OBJ(total_syms);
MZ_CLEAR_OBJ(pTable->m_look_up);
MZ_CLEAR_OBJ(pTable->m_tree);
for (i = 0; i < r->m_table_sizes[r->m_type]; ++i)
total_syms[pTable->m_code_size[i]]++;
used_syms = 0, total = 0;
next_code[0] = next_code[1] = 0;
for (i = 1; i <= 15; ++i) {
used_syms += total_syms[i];
next_code[i + 1] = (total = ((total + total_syms[i]) << 1));
}
if ((65536 != total) && (used_syms > 1)) {
TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
}
for (tree_next = -1, sym_index = 0;
sym_index < r->m_table_sizes[r->m_type]; ++sym_index) {
mz_uint rev_code = 0, l, cur_code,
code_size = pTable->m_code_size[sym_index];
if (!code_size)
continue;
cur_code = next_code[code_size]++;
for (l = code_size; l > 0; l--, cur_code >>= 1)
rev_code = (rev_code << 1) | (cur_code & 1);
if (code_size <= TINFL_FAST_LOOKUP_BITS) {
mz_int16 k = (mz_int16)((code_size << 9) | sym_index);
while (rev_code < TINFL_FAST_LOOKUP_SIZE) {
pTable->m_look_up[rev_code] = k;
rev_code += (1 << code_size);
}
continue;
}
if (0 ==
(tree_cur = pTable->m_look_up[rev_code &
(TINFL_FAST_LOOKUP_SIZE - 1)])) {
pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] =
(mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
}
rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) {
tree_cur -= ((rev_code >>= 1) & 1);
if (!pTable->m_tree[-tree_cur - 1]) {
pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next;
tree_cur = tree_next;
tree_next -= 2;
} else
tree_cur = pTable->m_tree[-tree_cur - 1];
}
tree_cur -= ((rev_code >>= 1) & 1);
pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
}
if (r->m_type == 2) {
for (counter = 0;
counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) {
mz_uint s;
TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]);
if (dist < 16) {
r->m_len_codes[counter++] = (mz_uint8)dist;
continue;
}
if ((dist == 16) && (!counter)) {
TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
}
num_extra = "\02\03\07"[dist - 16];
TINFL_GET_BITS(18, s, num_extra);
s += "\03\03\013"[dist - 16];
TINFL_MEMSET(r->m_len_codes + counter,
(dist == 16) ? r->m_len_codes[counter - 1] : 0, s);
counter += s;
}
if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) {
TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
}
TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes,
r->m_table_sizes[0]);
TINFL_MEMCPY(r->m_tables[1].m_code_size,
r->m_len_codes + r->m_table_sizes[0],
r->m_table_sizes[1]);
}
}
for (;;) {
mz_uint8 *pSrc;
for (;;) {
if (((pIn_buf_end - pIn_buf_cur) < 4) ||
((pOut_buf_end - pOut_buf_cur) < 2)) {
TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
if (counter >= 256)
break;
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ = (mz_uint8)counter;
} else {
int sym2;
mz_uint code_len;
#if TINFL_USE_64BIT_BITBUF
if (num_bits < 30) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 4;
num_bits += 32;
}
#else
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
counter = sym2;
bit_buf >>= code_len;
num_bits -= code_len;
if (counter & 256)
break;
#if !TINFL_USE_64BIT_BITBUF
if (num_bits < 15) {
bit_buf |=
(((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits);
pIn_buf_cur += 2;
num_bits += 16;
}
#endif
if ((sym2 =
r->m_tables[0]
.m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >=
0)
code_len = sym2 >> 9;
else {
code_len = TINFL_FAST_LOOKUP_BITS;
do {
sym2 = r->m_tables[0]
.m_tree[~sym2 + ((bit_buf >> code_len++) & 1)];
} while (sym2 < 0);
}
bit_buf >>= code_len;
num_bits -= code_len;
pOut_buf_cur[0] = (mz_uint8)counter;
if (sym2 & 256) {
pOut_buf_cur++;
counter = sym2;
break;
}
pOut_buf_cur[1] = (mz_uint8)sym2;
pOut_buf_cur += 2;
}
}
if ((counter &= 511) == 256)
break;
num_extra = s_length_extra[counter - 257];
counter = s_length_base[counter - 257];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(25, extra_bits, num_extra);
counter += extra_bits;
}
TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
num_extra = s_dist_extra[dist];
dist = s_dist_base[dist];
if (num_extra) {
mz_uint extra_bits;
TINFL_GET_BITS(27, extra_bits, num_extra);
dist += extra_bits;
}
dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
if ((dist > dist_from_out_buf_start) &&
(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) {
TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
}
pSrc = pOut_buf_start +
((dist_from_out_buf_start - dist) & out_buf_size_mask);
if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) {
while (counter--) {
while (pOut_buf_cur >= pOut_buf_end) {
TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT);
}
*pOut_buf_cur++ =
pOut_buf_start[(dist_from_out_buf_start++ - dist) &
out_buf_size_mask];
}
continue;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
else if ((counter >= 9) && (counter <= dist)) {
const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
do {
((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
pOut_buf_cur += 8;
} while ((pSrc += 8) < pSrc_end);
if ((counter &= 7) < 3) {
if (counter) {
pOut_buf_cur[0] = pSrc[0];
if (counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
continue;
}
}
#endif
do {
pOut_buf_cur[0] = pSrc[0];
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur[2] = pSrc[2];
pOut_buf_cur += 3;
pSrc += 3;
} while ((int)(counter -= 3) > 2);
if ((int)counter > 0) {
pOut_buf_cur[0] = pSrc[0];
if ((int)counter > 1)
pOut_buf_cur[1] = pSrc[1];
pOut_buf_cur += counter;
}
}
}
} while (!(r->m_final & 1));
if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) {
TINFL_SKIP_BITS(32, num_bits & 7);
for (counter = 0; counter < 4; ++counter) {
mz_uint s;
if (num_bits)
TINFL_GET_BITS(41, s, 8);
else
TINFL_GET_BYTE(42, s);
r->m_z_adler32 = (r->m_z_adler32 << 8) | s;
}
}
TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
TINFL_CR_FINISH
common_exit:
r->m_num_bits = num_bits;
r->m_bit_buf = bit_buf;
r->m_dist = dist;
r->m_counter = counter;
r->m_num_extra = num_extra;
r->m_dist_from_out_buf_start = dist_from_out_buf_start;
*pIn_buf_size = pIn_buf_cur - pIn_buf_next;
*pOut_buf_size = pOut_buf_cur - pOut_buf_next;
if ((decomp_flags &
(TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) &&
(status >= 0)) {
const mz_uint8 *ptr = pOut_buf_next;
size_t buf_len = *pOut_buf_size;
mz_uint32 i, s1 = r->m_check_adler32 & 0xffff,
s2 = r->m_check_adler32 >> 16;
size_t block_len = buf_len % 5552;
while (buf_len) {
for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
s1 += ptr[0], s2 += s1;
s1 += ptr[1], s2 += s1;
s1 += ptr[2], s2 += s1;
s1 += ptr[3], s2 += s1;
s1 += ptr[4], s2 += s1;
s1 += ptr[5], s2 += s1;
s1 += ptr[6], s2 += s1;
s1 += ptr[7], s2 += s1;
}
for (; i < block_len; ++i)
s1 += *ptr++, s2 += s1;
s1 %= 65521U, s2 %= 65521U;
buf_len -= block_len;
block_len = 5552;
}
r->m_check_adler32 = (s2 << 16) + s1;
if ((status == TINFL_STATUS_DONE) &&
(decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) &&
(r->m_check_adler32 != r->m_z_adler32))
status = TINFL_STATUS_ADLER32_MISMATCH;
}
return status;
}
// Higher level helper functions.
void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tinfl_decompressor decomp;
void *pBuf = NULL, *pNew_buf;
size_t src_buf_ofs = 0, out_buf_capacity = 0;
*pOut_len = 0;
tinfl_init(&decomp);
for (;;) {
size_t src_buf_size = src_buf_len - src_buf_ofs,
dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
tinfl_status status = tinfl_decompress(
&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size,
(mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL,
&dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
src_buf_ofs += src_buf_size;
*pOut_len += dst_buf_size;
if (status == TINFL_STATUS_DONE)
break;
new_out_buf_capacity = out_buf_capacity * 2;
if (new_out_buf_capacity < 128)
new_out_buf_capacity = 128;
pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
if (!pNew_buf) {
MZ_FREE(pBuf);
*pOut_len = 0;
return NULL;
}
pBuf = pNew_buf;
out_buf_capacity = new_out_buf_capacity;
}
return pBuf;
}
size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tinfl_decompressor decomp;
tinfl_status status;
tinfl_init(&decomp);
status =
tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len,
(mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len,
(flags & ~TINFL_FLAG_HAS_MORE_INPUT) |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED
: out_buf_len;
}
int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size,
tinfl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
int result = 0;
tinfl_decompressor decomp;
mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE);
size_t in_buf_ofs = 0, dict_ofs = 0;
if (!pDict)
return TINFL_STATUS_FAILED;
tinfl_init(&decomp);
for (;;) {
size_t in_buf_size = *pIn_buf_size - in_buf_ofs,
dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
tinfl_status status =
tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs,
&in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
(flags &
~(TINFL_FLAG_HAS_MORE_INPUT |
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
in_buf_ofs += in_buf_size;
if ((dst_buf_size) &&
(!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
break;
if (status != TINFL_STATUS_HAS_MORE_OUTPUT) {
result = (status == TINFL_STATUS_DONE);
break;
}
dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
}
MZ_FREE(pDict);
*pIn_buf_size = in_buf_ofs;
return result;
}
// ------------------- Low-level Compression (independent from all decompression
// API's)
// Purposely making these tables static for faster init and thread safety.
static const mz_uint16 s_tdefl_len_sym[256] = {
257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268,
268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272,
272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274,
274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276,
276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277,
277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278,
278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279,
279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280,
280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281,
281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282,
282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284,
285};
static const mz_uint8 s_tdefl_len_extra[256] = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0};
static const mz_uint8 s_tdefl_small_dist_sym[512] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,
17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17};
static const mz_uint8 s_tdefl_small_dist_extra[512] = {
0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7};
static const mz_uint8 s_tdefl_large_dist_sym[128] = {
0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24,
24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29};
static const mz_uint8 s_tdefl_large_dist_extra[128] = {
0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13};
// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted
// values.
typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms,
tdefl_sym_freq *pSyms0,
tdefl_sym_freq *pSyms1) {
mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2];
tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
MZ_CLEAR_OBJ(hist);
for (i = 0; i < num_syms; i++) {
mz_uint freq = pSyms0[i].m_key;
hist[freq & 0xFF]++;
hist[256 + ((freq >> 8) & 0xFF)]++;
}
while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
total_passes--;
for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) {
const mz_uint32 *pHist = &hist[pass << 8];
mz_uint offsets[256], cur_ofs = 0;
for (i = 0; i < 256; i++) {
offsets[i] = cur_ofs;
cur_ofs += pHist[i];
}
for (i = 0; i < num_syms; i++)
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] =
pCur_syms[i];
{
tdefl_sym_freq *t = pCur_syms;
pCur_syms = pNew_syms;
pNew_syms = t;
}
}
return pCur_syms;
}
// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat,
// alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) {
int root, leaf, next, avbl, used, dpth;
if (n == 0)
return;
else if (n == 1) {
A[0].m_key = 1;
return;
}
A[0].m_key += A[1].m_key;
root = 0;
leaf = 2;
for (next = 1; next < n - 1; next++) {
if (leaf >= n || A[root].m_key < A[leaf].m_key) {
A[next].m_key = A[root].m_key;
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = A[leaf++].m_key;
if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) {
A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key);
A[root++].m_key = (mz_uint16)next;
} else
A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
}
A[n - 2].m_key = 0;
for (next = n - 3; next >= 0; next--)
A[next].m_key = A[A[next].m_key].m_key + 1;
avbl = 1;
used = dpth = 0;
root = n - 2;
next = n - 1;
while (avbl > 0) {
while (root >= 0 && (int)A[root].m_key == dpth) {
used++;
root--;
}
while (avbl > used) {
A[next--].m_key = (mz_uint16)(dpth);
avbl--;
}
avbl = 2 * used;
dpth++;
used = 0;
}
}
// Limits canonical Huffman code table's max code size.
enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
static void tdefl_huffman_enforce_max_code_size(int *pNum_codes,
int code_list_len,
int max_code_size) {
int i;
mz_uint32 total = 0;
if (code_list_len <= 1)
return;
for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++)
pNum_codes[max_code_size] += pNum_codes[i];
for (i = max_code_size; i > 0; i--)
total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
while (total != (1UL << max_code_size)) {
pNum_codes[max_code_size]--;
for (i = max_code_size - 1; i > 0; i--)
if (pNum_codes[i]) {
pNum_codes[i]--;
pNum_codes[i + 1] += 2;
break;
}
total--;
}
}
static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num,
int table_len, int code_size_limit,
int static_table) {
int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE];
mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1];
MZ_CLEAR_OBJ(num_codes);
if (static_table) {
for (i = 0; i < table_len; i++)
num_codes[d->m_huff_code_sizes[table_num][i]]++;
} else {
tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS],
*pSyms;
int num_used_syms = 0;
const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
for (i = 0; i < table_len; i++)
if (pSym_count[i]) {
syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i];
syms0[num_used_syms++].m_sym_index = (mz_uint16)i;
}
pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1);
tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
for (i = 0; i < num_used_syms; i++)
num_codes[pSyms[i].m_key]++;
tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms,
code_size_limit);
MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]);
MZ_CLEAR_OBJ(d->m_huff_codes[table_num]);
for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
for (l = num_codes[i]; l > 0; l--)
d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
}
next_code[1] = 0;
for (j = 0, i = 2; i <= code_size_limit; i++)
next_code[i] = j = ((j + num_codes[i - 1]) << 1);
for (i = 0; i < table_len; i++) {
mz_uint rev_code = 0, code, code_size;
if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0)
continue;
code = next_code[code_size]++;
for (l = code_size; l > 0; l--, code >>= 1)
rev_code = (rev_code << 1) | (code & 1);
d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
}
}
#define TDEFL_PUT_BITS(b, l) \
do { \
mz_uint bits = b; \
mz_uint len = l; \
MZ_ASSERT(bits <= ((1U << len) - 1U)); \
d->m_bit_buffer |= (bits << d->m_bits_in); \
d->m_bits_in += len; \
while (d->m_bits_in >= 8) { \
if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
*d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
d->m_bit_buffer >>= 8; \
d->m_bits_in -= 8; \
} \
} \
MZ_MACRO_END
#define TDEFL_RLE_PREV_CODE_SIZE() \
{ \
if (rle_repeat_count) { \
if (rle_repeat_count < 3) { \
d->m_huff_count[2][prev_code_size] = (mz_uint16)( \
d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
while (rle_repeat_count--) \
packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
} else { \
d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 16; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_repeat_count - 3); \
} \
rle_repeat_count = 0; \
} \
}
#define TDEFL_RLE_ZERO_CODE_SIZE() \
{ \
if (rle_z_count) { \
if (rle_z_count < 3) { \
d->m_huff_count[2][0] = \
(mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \
while (rle_z_count--) \
packed_code_sizes[num_packed_code_sizes++] = 0; \
} else if (rle_z_count <= 10) { \
d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 17; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 3); \
} else { \
d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \
packed_code_sizes[num_packed_code_sizes++] = 18; \
packed_code_sizes[num_packed_code_sizes++] = \
(mz_uint8)(rle_z_count - 11); \
} \
rle_z_count = 0; \
} \
}
static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = {
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
static void tdefl_start_dynamic_block(tdefl_compressor *d) {
int num_lit_codes, num_dist_codes, num_bit_lengths;
mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count,
rle_repeat_count, packed_code_sizes_index;
mz_uint8
code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1],
prev_code_size = 0xFF;
d->m_huff_count[0][256] = 1;
tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--)
if (d->m_huff_code_sizes[0][num_lit_codes - 1])
break;
for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--)
if (d->m_huff_code_sizes[1][num_dist_codes - 1])
break;
memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0],
num_dist_codes);
total_code_sizes_to_pack = num_lit_codes + num_dist_codes;
num_packed_code_sizes = 0;
rle_z_count = 0;
rle_repeat_count = 0;
memset(&d->m_huff_count[2][0], 0,
sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
for (i = 0; i < total_code_sizes_to_pack; i++) {
mz_uint8 code_size = code_sizes_to_pack[i];
if (!code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
if (++rle_z_count == 138) {
TDEFL_RLE_ZERO_CODE_SIZE();
}
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
if (code_size != prev_code_size) {
TDEFL_RLE_PREV_CODE_SIZE();
d->m_huff_count[2][code_size] =
(mz_uint16)(d->m_huff_count[2][code_size] + 1);
packed_code_sizes[num_packed_code_sizes++] = code_size;
} else if (++rle_repeat_count == 6) {
TDEFL_RLE_PREV_CODE_SIZE();
}
}
prev_code_size = code_size;
}
if (rle_repeat_count) {
TDEFL_RLE_PREV_CODE_SIZE();
} else {
TDEFL_RLE_ZERO_CODE_SIZE();
}
tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
TDEFL_PUT_BITS(2, 2);
TDEFL_PUT_BITS(num_lit_codes - 257, 5);
TDEFL_PUT_BITS(num_dist_codes - 1, 5);
for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--)
if (d->m_huff_code_sizes
[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]])
break;
num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1));
TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
for (i = 0; (int)i < num_bit_lengths; i++)
TDEFL_PUT_BITS(
d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
for (packed_code_sizes_index = 0;
packed_code_sizes_index < num_packed_code_sizes;) {
mz_uint code = packed_code_sizes[packed_code_sizes_index++];
MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
if (code >= 16)
TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++],
"\02\03\07"[code - 16]);
}
}
static void tdefl_start_static_block(tdefl_compressor *d) {
mz_uint i;
mz_uint8 *p = &d->m_huff_code_sizes[0][0];
for (i = 0; i <= 143; ++i)
*p++ = 8;
for (; i <= 255; ++i)
*p++ = 9;
for (; i <= 279; ++i)
*p++ = 7;
for (; i <= 287; ++i)
*p++ = 8;
memset(d->m_huff_code_sizes[1], 5, 32);
tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
TDEFL_PUT_BITS(1, 2);
}
static const mz_uint mz_bitmasks[17] = {
0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \
MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
mz_uint8 *pOutput_buf = d->m_pOutput_buf;
mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
mz_uint64 bit_buffer = d->m_bit_buffer;
mz_uint bits_in = d->m_bits_in;
#define TDEFL_PUT_BITS_FAST(b, l) \
{ \
bit_buffer |= (((mz_uint64)(b)) << bits_in); \
bits_in += (l); \
}
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end;
flags >>= 1) {
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint s0, s1, n0, n1, sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = *(const mz_uint16 *)(pLZ_codes + 1);
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
// This sequence coaxes MSVC into using cmov's vs. jmp's.
s0 = s_tdefl_small_dist_sym[match_dist & 511];
n0 = s_tdefl_small_dist_extra[match_dist & 511];
s1 = s_tdefl_large_dist_sym[match_dist >> 8];
n1 = s_tdefl_large_dist_extra[match_dist >> 8];
sym = (match_dist < 512) ? s0 : s1;
num_extra_bits = (match_dist < 512) ? n0 : n1;
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym],
d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits],
num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) {
flags >>= 1;
lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit],
d->m_huff_code_sizes[0][lit]);
}
}
}
if (pOutput_buf >= d->m_pOutput_buf_end)
return MZ_FALSE;
*(mz_uint64 *)pOutput_buf = bit_buffer;
pOutput_buf += (bits_in >> 3);
bit_buffer >>= (bits_in & ~7);
bits_in &= 7;
}
#undef TDEFL_PUT_BITS_FAST
d->m_pOutput_buf = pOutput_buf;
d->m_bits_in = 0;
d->m_bit_buffer = 0;
while (bits_in) {
mz_uint32 n = MZ_MIN(bits_in, 16);
TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
bit_buffer >>= n;
bits_in -= n;
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#else
static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) {
mz_uint flags;
mz_uint8 *pLZ_codes;
flags = 1;
for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf;
flags >>= 1) {
if (flags == 1)
flags = *pLZ_codes++ | 0x100;
if (flags & 1) {
mz_uint sym, num_extra_bits;
mz_uint match_len = pLZ_codes[0],
match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8));
pLZ_codes += 3;
MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]],
d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]],
s_tdefl_len_extra[match_len]);
if (match_dist < 512) {
sym = s_tdefl_small_dist_sym[match_dist];
num_extra_bits = s_tdefl_small_dist_extra[match_dist];
} else {
sym = s_tdefl_large_dist_sym[match_dist >> 8];
num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
}
MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
} else {
mz_uint lit = *pLZ_codes++;
MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
}
}
TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
return (d->m_pOutput_buf < d->m_pOutput_buf_end);
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN &&
// MINIZ_HAS_64BIT_REGISTERS
static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) {
if (static_block)
tdefl_start_static_block(d);
else
tdefl_start_dynamic_block(d);
return tdefl_compress_lz_codes(d);
}
static int tdefl_flush_block(tdefl_compressor *d, int flush) {
mz_uint saved_bit_buf, saved_bits_in;
mz_uint8 *pSaved_output_buf;
mz_bool comp_block_succeeded = MZ_FALSE;
int n, use_raw_block =
((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) &&
(d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
mz_uint8 *pOutput_buf_start =
((d->m_pPut_buf_func == NULL) &&
((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE))
? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs)
: d->m_output_buf;
d->m_pOutput_buf = pOutput_buf_start;
d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
MZ_ASSERT(!d->m_output_flush_remaining);
d->m_output_flush_ofs = 0;
d->m_output_flush_remaining = 0;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) {
TDEFL_PUT_BITS(0x78, 8);
TDEFL_PUT_BITS(0x01, 8);
}
TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
pSaved_output_buf = d->m_pOutput_buf;
saved_bit_buf = d->m_bit_buffer;
saved_bits_in = d->m_bits_in;
if (!use_raw_block)
comp_block_succeeded =
tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) ||
(d->m_total_lz_bytes < 48));
// If the block gets expanded, forget the current contents of the output
// buffer and send a raw block instead.
if (((use_raw_block) ||
((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >=
d->m_total_lz_bytes))) &&
((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) {
mz_uint i;
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
TDEFL_PUT_BITS(0, 2);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) {
TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
}
for (i = 0; i < d->m_total_lz_bytes; ++i) {
TDEFL_PUT_BITS(
d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK],
8);
}
}
// Check for the extremely unlikely (if not impossible) case of the compressed
// block not fitting into the output buffer when using dynamic codes.
else if (!comp_block_succeeded) {
d->m_pOutput_buf = pSaved_output_buf;
d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
tdefl_compress_block(d, MZ_TRUE);
}
if (flush) {
if (flush == TDEFL_FINISH) {
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) {
mz_uint i, a = d->m_adler32;
for (i = 0; i < 4; i++) {
TDEFL_PUT_BITS((a >> 24) & 0xFF, 8);
a <<= 8;
}
}
} else {
mz_uint i, z = 0;
TDEFL_PUT_BITS(0, 3);
if (d->m_bits_in) {
TDEFL_PUT_BITS(0, 8 - d->m_bits_in);
}
for (i = 2; i; --i, z ^= 0xFFFF) {
TDEFL_PUT_BITS(z & 0xFFFF, 16);
}
}
}
MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes;
d->m_total_lz_bytes = 0;
d->m_block_index++;
if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) {
if (d->m_pPut_buf_func) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
} else if (pOutput_buf_start == d->m_output_buf) {
int bytes_to_copy = (int)MZ_MIN(
(size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf,
bytes_to_copy);
d->m_out_buf_ofs += bytes_to_copy;
if ((n -= bytes_to_copy) != 0) {
d->m_output_flush_ofs = bytes_to_copy;
d->m_output_flush_remaining = n;
}
} else {
d->m_out_buf_ofs += n;
}
}
return d->m_output_flush_remaining;
}
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p)
static MZ_FORCEINLINE void
tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist,
mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q;
mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]),
s01 = TDEFL_READ_UNALIGNED_WORD(s);
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len)
return;
for (;;) {
for (;;) {
if (--num_probes_left == 0)
return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist)
break;
q = (const mz_uint16 *)(d->m_dict + probe_pos);
if (TDEFL_READ_UNALIGNED_WORD(q) != s01)
continue;
p = s;
probe_len = 32;
do {
} while (
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
if (!probe_len) {
*pMatch_dist = dist;
*pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN);
break;
} else if ((probe_len = ((mz_uint)(p - s) * 2) +
(mz_uint)(*(const mz_uint8 *)p ==
*(const mz_uint8 *)q)) > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) ==
max_match_len)
break;
c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
}
}
}
#else
static MZ_FORCEINLINE void
tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist,
mz_uint max_match_len, mz_uint *pMatch_dist,
mz_uint *pMatch_len) {
mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK,
match_len = *pMatch_len, probe_pos = pos, next_probe_pos,
probe_len;
mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
const mz_uint8 *s = d->m_dict + pos, *p, *q;
mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN);
if (max_match_len <= match_len)
return;
for (;;) {
for (;;) {
if (--num_probes_left == 0)
return;
#define TDEFL_PROBE \
next_probe_pos = d->m_next[probe_pos]; \
if ((!next_probe_pos) || \
((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \
return; \
probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
if ((d->m_dict[probe_pos + match_len] == c0) && \
(d->m_dict[probe_pos + match_len - 1] == c1)) \
break;
TDEFL_PROBE;
TDEFL_PROBE;
TDEFL_PROBE;
}
if (!dist)
break;
p = s;
q = d->m_dict + probe_pos;
for (probe_len = 0; probe_len < max_match_len; probe_len++)
if (*p++ != *q++)
break;
if (probe_len > match_len) {
*pMatch_dist = dist;
if ((*pMatch_len = match_len = probe_len) == max_match_len)
return;
c0 = d->m_dict[pos + match_len];
c1 = d->m_dict[pos + match_len - 1];
}
}
}
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static mz_bool tdefl_compress_fast(tdefl_compressor *d) {
// Faster, minimally featured LZRW1-style match+parse loop with better
// register utilization. Intended for applications where raw throughput is
// valued more highly than ratio.
mz_uint lookahead_pos = d->m_lookahead_pos,
lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size,
total_lz_bytes = d->m_total_lz_bytes,
num_flags_left = d->m_num_flags_left;
mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) {
const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
mz_uint dst_pos =
(lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
d->m_src_buf_left -= num_bytes_to_process;
lookahead_size += num_bytes_to_process;
while (num_bytes_to_process) {
mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc,
MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
d->m_pSrc += n;
dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
num_bytes_to_process -= n;
}
dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE))
break;
while (lookahead_size >= 4) {
mz_uint cur_match_dist, cur_match_len = 1;
mz_uint8 *pCur_dict = d->m_dict + cur_pos;
mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
mz_uint hash =
(first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) &
TDEFL_LEVEL1_HASH_SIZE_MASK;
mz_uint probe_pos = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)lookahead_pos;
if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <=
dict_size) &&
((*(const mz_uint32 *)(d->m_dict +
(probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) &
0xFFFFFF) == first_trigram)) {
const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
mz_uint32 probe_len = 32;
do {
} while ((TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(TDEFL_READ_UNALIGNED_WORD(++p) ==
TDEFL_READ_UNALIGNED_WORD(++q)) &&
(--probe_len > 0));
cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) +
(mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
if (!probe_len)
cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
if ((cur_match_len < TDEFL_MIN_MATCH_LEN) ||
((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U))) {
cur_match_len = 1;
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
} else {
mz_uint32 s0, s1;
cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 1) &&
(cur_match_dist <= TDEFL_LZ_DICT_SIZE));
cur_match_dist--;
pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
*(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
pLZ_code_buf += 3;
*pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
d->m_huff_count[0][s_tdefl_len_sym[cur_match_len -
TDEFL_MIN_MATCH_LEN]]++;
}
} else {
*pLZ_code_buf++ = (mz_uint8)first_trigram;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
d->m_huff_count[0][(mz_uint8)first_trigram]++;
}
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
total_lz_bytes += cur_match_len;
lookahead_pos += cur_match_len;
dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
MZ_ASSERT(lookahead_size >= cur_match_len);
lookahead_size -= cur_match_len;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
while (lookahead_size) {
mz_uint8 lit = d->m_dict[cur_pos];
total_lz_bytes++;
*pLZ_code_buf++ = lit;
*pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
if (--num_flags_left == 0) {
num_flags_left = 8;
pLZ_flags = pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
lookahead_pos++;
dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
lookahead_size--;
if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) {
int n;
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
total_lz_bytes = d->m_total_lz_bytes;
pLZ_code_buf = d->m_pLZ_code_buf;
pLZ_flags = d->m_pLZ_flags;
num_flags_left = d->m_num_flags_left;
}
}
}
d->m_lookahead_pos = lookahead_pos;
d->m_lookahead_size = lookahead_size;
d->m_dict_size = dict_size;
d->m_total_lz_bytes = total_lz_bytes;
d->m_pLZ_code_buf = pLZ_code_buf;
d->m_pLZ_flags = pLZ_flags;
d->m_num_flags_left = num_flags_left;
return MZ_TRUE;
}
#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d,
mz_uint8 lit) {
d->m_total_lz_bytes++;
*d->m_pLZ_code_buf++ = lit;
*d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
d->m_huff_count[0][lit]++;
}
static MZ_FORCEINLINE void
tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) {
mz_uint32 s0, s1;
MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) &&
(match_dist <= TDEFL_LZ_DICT_SIZE));
d->m_total_lz_bytes += match_len;
d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
match_dist -= 1;
d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8);
d->m_pLZ_code_buf += 3;
*d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80);
if (--d->m_num_flags_left == 0) {
d->m_num_flags_left = 8;
d->m_pLZ_flags = d->m_pLZ_code_buf++;
}
s0 = s_tdefl_small_dist_sym[match_dist & 511];
s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
if (match_len >= TDEFL_MIN_MATCH_LEN)
d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
}
static mz_bool tdefl_compress_normal(tdefl_compressor *d) {
const mz_uint8 *pSrc = d->m_pSrc;
size_t src_buf_left = d->m_src_buf_left;
tdefl_flush flush = d->m_flush;
while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) {
mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
// Update dictionary and hash chains. Keeps the lookahead size equal to
// TDEFL_MAX_MATCH_LEN.
if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) {
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK,
ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(
src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process;
src_buf_left -= num_bytes_to_process;
d->m_lookahead_size += num_bytes_to_process;
while (pSrc != pSrc_end) {
mz_uint8 c = *pSrc++;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
ins_pos++;
}
} else {
while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) {
mz_uint8 c = *pSrc++;
mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) &
TDEFL_LZ_DICT_SIZE_MASK;
src_buf_left--;
d->m_dict[dst_pos] = c;
if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) {
mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK]
<< (TDEFL_LZ_HASH_SHIFT * 2)) ^
(d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]
<< TDEFL_LZ_HASH_SHIFT) ^
c) &
(TDEFL_LZ_HASH_SIZE - 1);
d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash];
d->m_hash[hash] = (mz_uint16)(ins_pos);
}
}
}
d->m_dict_size =
MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
break;
// Simple lazy/greedy parsing state machine.
len_to_move = 1;
cur_match_dist = 0;
cur_match_len =
d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1);
cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) {
if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) {
mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
cur_match_len = 0;
while (cur_match_len < d->m_lookahead_size) {
if (d->m_dict[cur_pos + cur_match_len] != c)
break;
cur_match_len++;
}
if (cur_match_len < TDEFL_MIN_MATCH_LEN)
cur_match_len = 0;
else
cur_match_dist = 1;
}
} else {
tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size,
d->m_lookahead_size, &cur_match_dist, &cur_match_len);
}
if (((cur_match_len == TDEFL_MIN_MATCH_LEN) &&
(cur_match_dist >= 8U * 1024U)) ||
(cur_pos == cur_match_dist) ||
((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) {
cur_match_dist = cur_match_len = 0;
}
if (d->m_saved_match_len) {
if (cur_match_len > d->m_saved_match_len) {
tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
if (cur_match_len >= 128) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
d->m_saved_match_len = 0;
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[cur_pos];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
} else {
tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
len_to_move = d->m_saved_match_len - 1;
d->m_saved_match_len = 0;
}
} else if (!cur_match_dist)
tdefl_record_literal(d,
d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) ||
(cur_match_len >= 128)) {
tdefl_record_match(d, cur_match_len, cur_match_dist);
len_to_move = cur_match_len;
} else {
d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)];
d->m_saved_match_dist = cur_match_dist;
d->m_saved_match_len = cur_match_len;
}
// Move the lookahead forward by len_to_move bytes.
d->m_lookahead_pos += len_to_move;
MZ_ASSERT(d->m_lookahead_size >= len_to_move);
d->m_lookahead_size -= len_to_move;
d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE);
// Check if it's time to flush the current LZ codes to the internal output
// buffer.
if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
((d->m_total_lz_bytes > 31 * 1024) &&
(((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >=
d->m_total_lz_bytes) ||
(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) {
int n;
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
if ((n = tdefl_flush_block(d, 0)) != 0)
return (n < 0) ? MZ_FALSE : MZ_TRUE;
}
}
d->m_pSrc = pSrc;
d->m_src_buf_left = src_buf_left;
return MZ_TRUE;
}
static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) {
if (d->m_pIn_buf_size) {
*d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
}
if (d->m_pOut_buf_size) {
size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs,
d->m_output_flush_remaining);
memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs,
d->m_output_buf + d->m_output_flush_ofs, n);
d->m_output_flush_ofs += (mz_uint)n;
d->m_output_flush_remaining -= (mz_uint)n;
d->m_out_buf_ofs += n;
*d->m_pOut_buf_size = d->m_out_buf_ofs;
}
return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE
: TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf,
size_t *pIn_buf_size, void *pOut_buf,
size_t *pOut_buf_size, tdefl_flush flush) {
if (!d) {
if (pIn_buf_size)
*pIn_buf_size = 0;
if (pOut_buf_size)
*pOut_buf_size = 0;
return TDEFL_STATUS_BAD_PARAM;
}
d->m_pIn_buf = pIn_buf;
d->m_pIn_buf_size = pIn_buf_size;
d->m_pOut_buf = pOut_buf;
d->m_pOut_buf_size = pOut_buf_size;
d->m_pSrc = (const mz_uint8 *)(pIn_buf);
d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
d->m_out_buf_ofs = 0;
d->m_flush = flush;
if (((d->m_pPut_buf_func != NULL) ==
((pOut_buf != NULL) || (pOut_buf_size != NULL))) ||
(d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
(d->m_wants_to_finish && (flush != TDEFL_FINISH)) ||
(pIn_buf_size && *pIn_buf_size && !pIn_buf) ||
(pOut_buf_size && *pOut_buf_size && !pOut_buf)) {
if (pIn_buf_size)
*pIn_buf_size = 0;
if (pOut_buf_size)
*pOut_buf_size = 0;
return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
}
d->m_wants_to_finish |= (flush == TDEFL_FINISH);
if ((d->m_output_flush_remaining) || (d->m_finished))
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS |
TDEFL_RLE_MATCHES)) == 0)) {
if (!tdefl_compress_fast(d))
return d->m_prev_return_status;
} else
#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
{
if (!tdefl_compress_normal(d))
return d->m_prev_return_status;
}
if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) &&
(pIn_buf))
d->m_adler32 =
(mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf,
d->m_pSrc - (const mz_uint8 *)pIn_buf);
if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) &&
(!d->m_output_flush_remaining)) {
if (tdefl_flush_block(d, flush) < 0)
return d->m_prev_return_status;
d->m_finished = (flush == TDEFL_FINISH);
if (flush == TDEFL_FULL_FLUSH) {
MZ_CLEAR_OBJ(d->m_hash);
MZ_CLEAR_OBJ(d->m_next);
d->m_dict_size = 0;
}
}
return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
}
tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf,
size_t in_buf_size, tdefl_flush flush) {
MZ_ASSERT(d->m_pPut_buf_func);
return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
}
tdefl_status tdefl_init(tdefl_compressor *d,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
d->m_pPut_buf_func = pPut_buf_func;
d->m_pPut_buf_user = pPut_buf_user;
d->m_flags = (mz_uint)(flags);
d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3;
d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG))
MZ_CLEAR_OBJ(d->m_hash);
d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size =
d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished =
d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
d->m_pLZ_code_buf = d->m_lz_code_buf + 1;
d->m_pLZ_flags = d->m_lz_code_buf;
d->m_num_flags_left = 8;
d->m_pOutput_buf = d->m_output_buf;
d->m_pOutput_buf_end = d->m_output_buf;
d->m_prev_return_status = TDEFL_STATUS_OKAY;
d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0;
d->m_adler32 = 1;
d->m_pIn_buf = NULL;
d->m_pOut_buf = NULL;
d->m_pIn_buf_size = NULL;
d->m_pOut_buf_size = NULL;
d->m_flush = TDEFL_NO_FLUSH;
d->m_pSrc = NULL;
d->m_src_buf_left = 0;
d->m_out_buf_ofs = 0;
memset(&d->m_huff_count[0][0], 0,
sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
memset(&d->m_huff_count[1][0], 0,
sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
return TDEFL_STATUS_OKAY;
}
tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) {
return d->m_prev_return_status;
}
mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; }
mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len,
tdefl_put_buf_func_ptr pPut_buf_func,
void *pPut_buf_user, int flags) {
tdefl_compressor *pComp;
mz_bool succeeded;
if (((buf_len) && (!pBuf)) || (!pPut_buf_func))
return MZ_FALSE;
pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
if (!pComp)
return MZ_FALSE;
succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) ==
TDEFL_STATUS_OKAY);
succeeded =
succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) ==
TDEFL_STATUS_DONE);
MZ_FREE(pComp);
return succeeded;
}
typedef struct {
size_t m_size, m_capacity;
mz_uint8 *m_pBuf;
mz_bool m_expandable;
} tdefl_output_buffer;
static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len,
void *pUser) {
tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
size_t new_size = p->m_size + len;
if (new_size > p->m_capacity) {
size_t new_capacity = p->m_capacity;
mz_uint8 *pNew_buf;
if (!p->m_expandable)
return MZ_FALSE;
do {
new_capacity = MZ_MAX(128U, new_capacity << 1U);
} while (new_size > new_capacity);
pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity);
if (!pNew_buf)
return MZ_FALSE;
p->m_pBuf = pNew_buf;
p->m_capacity = new_capacity;
}
memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len);
p->m_size = new_size;
return MZ_TRUE;
}
void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len,
size_t *pOut_len, int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_len)
return MZ_FALSE;
else
*pOut_len = 0;
out_buf.m_expandable = MZ_TRUE;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return NULL;
*pOut_len = out_buf.m_size;
return out_buf.m_pBuf;
}
size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len,
const void *pSrc_buf, size_t src_buf_len,
int flags) {
tdefl_output_buffer out_buf;
MZ_CLEAR_OBJ(out_buf);
if (!pOut_buf)
return 0;
out_buf.m_pBuf = (mz_uint8 *)pOut_buf;
out_buf.m_capacity = out_buf_len;
if (!tdefl_compress_mem_to_output(
pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags))
return 0;
return out_buf.m_size;
}
#ifndef MINIZ_NO_ZLIB_APIS
static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32,
128, 256, 512, 768, 1500};
// level may actually range from [0,10] (10 is a "hidden" max level, where we
// want a bit more compression and it's fine if throughput to fall off a cliff
// on some files).
mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits,
int strategy) {
mz_uint comp_flags =
s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] |
((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
if (window_bits > 0)
comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
if (!level)
comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
else if (strategy == MZ_FILTERED)
comp_flags |= TDEFL_FILTER_MATCHES;
else if (strategy == MZ_HUFFMAN_ONLY)
comp_flags &= ~TDEFL_MAX_PROBES_MASK;
else if (strategy == MZ_FIXED)
comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
else if (strategy == MZ_RLE)
comp_flags |= TDEFL_RLE_MATCHES;
return comp_flags;
}
#endif // MINIZ_NO_ZLIB_APIS
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4204) // nonstandard extension used : non-constant
// aggregate initializer (also supported by GNU
// C and C99, so no big deal)
#pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to
// 'int', possible loss of data
#pragma warning(disable : 4267) // 'argument': conversion from '__int64' to 'int',
// possible loss of data
#pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is
// deprecated. Instead, use the ISO C and C++
// conformant name: _strdup.
#endif
// Simple PNG writer function by Alex Evans, 2011. Released into the public
// domain: https://gist.github.com/908299, more context at
// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
// This is actually a modification of Alex's original code so PNG files
// generated by this function pass pngcheck.
void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w,
int h, int num_chans,
size_t *pLen_out,
mz_uint level, mz_bool flip) {
// Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was
// defined.
static const mz_uint s_tdefl_png_num_probes[11] = {
0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500};
tdefl_compressor *pComp =
(tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor));
tdefl_output_buffer out_buf;
int i, bpl = w * num_chans, y, z;
mz_uint32 c;
*pLen_out = 0;
if (!pComp)
return NULL;
MZ_CLEAR_OBJ(out_buf);
out_buf.m_expandable = MZ_TRUE;
out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h);
if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) {
MZ_FREE(pComp);
return NULL;
}
// write dummy header
for (z = 41; z; --z)
tdefl_output_buffer_putter(&z, 1, &out_buf);
// compress image data
tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf,
s_tdefl_png_num_probes[MZ_MIN(10, level)] |
TDEFL_WRITE_ZLIB_HEADER);
for (y = 0; y < h; ++y) {
tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH);
tdefl_compress_buffer(pComp,
(mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl,
bpl, TDEFL_NO_FLUSH);
}
if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) !=
TDEFL_STATUS_DONE) {
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
// write real header
*pLen_out = out_buf.m_size - 41;
{
static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
mz_uint8 pnghdr[41] = {
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0,
(mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0,
0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16),
(mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41,
0x54};
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17);
for (i = 0; i < 4; ++i, c <<= 8)
((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24);
memcpy(out_buf.m_pBuf, pnghdr, 41);
}
// write footer (IDAT CRC-32, followed by IEND chunk)
if (!tdefl_output_buffer_putter(
"\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) {
*pLen_out = 0;
MZ_FREE(pComp);
MZ_FREE(out_buf.m_pBuf);
return NULL;
}
c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4,
*pLen_out + 4);
for (i = 0; i < 4; ++i, c <<= 8)
(out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24);
// compute final size of file, grab compressed data buffer and return
*pLen_out += 57;
MZ_FREE(pComp);
return out_buf.m_pBuf;
}
void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h,
int num_chans, size_t *pLen_out) {
// Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we
// can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's
// where #defined out)
return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans,
pLen_out, 6, MZ_FALSE);
}
// ------------------- .ZIP archive reading
#ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef MINIZ_NO_STDIO
#define MZ_FILE void *
#else
#include <stdio.h>
#include <sys/stat.h>
#if defined(_MSC_VER) //|| defined(__MINGW64__)
static FILE *mz_fopen(const char *pFilename, const char *pMode) {
FILE *pFile = NULL;
fopen_s(&pFile, pFilename, pMode);
return pFile;
}
static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) {
FILE *pFile = NULL;
if (freopen_s(&pFile, pPath, pMode, pStream))
return NULL;
return pFile;
}
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN mz_fopen
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 _ftelli64
#define MZ_FSEEK64 _fseeki64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN mz_freopen
#define MZ_DELETE_FILE remove
#elif defined(__MINGW32__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT _stat
#define MZ_FILE_STAT _stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__TINYC__)
#ifndef MINIZ_NO_TIME
#include <sys/utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftell
#define MZ_FSEEK64 fseek
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen64(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello64
#define MZ_FSEEK64 fseeko64
#define MZ_FILE_STAT_STRUCT stat64
#define MZ_FILE_STAT stat64
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
#define MZ_DELETE_FILE remove
#else
#ifndef MINIZ_NO_TIME
#include <utime.h>
#endif
#define MZ_FILE FILE
#define MZ_FOPEN(f, m) fopen(f, m)
#define MZ_FCLOSE fclose
#define MZ_FREAD fread
#define MZ_FWRITE fwrite
#define MZ_FTELL64 ftello
#define MZ_FSEEK64 fseeko
#define MZ_FILE_STAT_STRUCT stat
#define MZ_FILE_STAT stat
#define MZ_FFLUSH fflush
#define MZ_FREOPEN(f, m, s) freopen(f, m, s)
#define MZ_DELETE_FILE remove
#endif // #ifdef _MSC_VER
#endif // #ifdef MINIZ_NO_STDIO
#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
// Various ZIP archive enums. To completely avoid cross platform compiler
// alignment and platform endian issues, miniz.c doesn't use structs for any of
// this stuff.
enum {
// ZIP archive identifiers and record sizes
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50,
MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
// Central directory header record offsets
MZ_ZIP_CDH_SIG_OFS = 0,
MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4,
MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6,
MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
MZ_ZIP_CDH_METHOD_OFS = 10,
MZ_ZIP_CDH_FILE_TIME_OFS = 12,
MZ_ZIP_CDH_FILE_DATE_OFS = 14,
MZ_ZIP_CDH_CRC32_OFS = 16,
MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20,
MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24,
MZ_ZIP_CDH_FILENAME_LEN_OFS = 28,
MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
MZ_ZIP_CDH_COMMENT_LEN_OFS = 32,
MZ_ZIP_CDH_DISK_START_OFS = 34,
MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36,
MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38,
MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
// Local directory header offsets
MZ_ZIP_LDH_SIG_OFS = 0,
MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4,
MZ_ZIP_LDH_BIT_FLAG_OFS = 6,
MZ_ZIP_LDH_METHOD_OFS = 8,
MZ_ZIP_LDH_FILE_TIME_OFS = 10,
MZ_ZIP_LDH_FILE_DATE_OFS = 12,
MZ_ZIP_LDH_CRC32_OFS = 14,
MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18,
MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
MZ_ZIP_LDH_FILENAME_LEN_OFS = 26,
MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
// End of central directory offsets
MZ_ZIP_ECDH_SIG_OFS = 0,
MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4,
MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6,
MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10,
MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12,
MZ_ZIP_ECDH_CDIR_OFS_OFS = 16,
MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
};
typedef struct {
void *m_p;
size_t m_size, m_capacity;
mz_uint m_element_size;
} mz_zip_array;
struct mz_zip_internal_state_tag {
mz_zip_array m_central_dir;
mz_zip_array m_central_dir_offsets;
mz_zip_array m_sorted_central_dir_offsets;
MZ_FILE *m_pFile;
void *m_pMem;
size_t m_mem_size;
size_t m_mem_capacity;
};
#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \
(array_ptr)->m_element_size = element_size
#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \
((element_type *)((array_ptr)->m_p))[index]
static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip,
mz_zip_array *pArray) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
memset(pArray, 0, sizeof(mz_zip_array));
}
static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip,
mz_zip_array *pArray,
size_t min_new_capacity,
mz_uint growing) {
void *pNew_p;
size_t new_capacity = min_new_capacity;
MZ_ASSERT(pArray->m_element_size);
if (pArray->m_capacity >= min_new_capacity)
return MZ_TRUE;
if (growing) {
new_capacity = MZ_MAX(1, pArray->m_capacity);
while (new_capacity < min_new_capacity)
new_capacity *= 2;
}
if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p,
pArray->m_element_size, new_capacity)))
return MZ_FALSE;
pArray->m_p = pNew_p;
pArray->m_capacity = new_capacity;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray,
size_t new_capacity, mz_uint growing) {
if (new_capacity > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing))
return MZ_FALSE;
}
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size,
mz_uint growing) {
if (new_size > pArray->m_capacity) {
if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing))
return MZ_FALSE;
}
pArray->m_size = new_size;
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) {
return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
}
static MZ_FORCEINLINE mz_bool
mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray,
const void *pElements, size_t n) {
size_t orig_size = pArray->m_size;
if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE))
return MZ_FALSE;
memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size,
pElements, n * pArray->m_element_size);
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) {
struct tm tm;
memset(&tm, 0, sizeof(tm));
tm.tm_isdst = -1;
tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900;
tm.tm_mon = ((dos_date >> 5) & 15) - 1;
tm.tm_mday = dos_date & 31;
tm.tm_hour = (dos_time >> 11) & 31;
tm.tm_min = (dos_time >> 5) & 63;
tm.tm_sec = (dos_time << 1) & 62;
return mktime(&tm);
}
static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef _MSC_VER
struct tm tm_struct;
struct tm *tm = &tm_struct;
errno_t err = localtime_s(tm, &time);
if (err) {
*pDOS_date = 0;
*pDOS_time = 0;
return;
}
#else
struct tm *tm = localtime(&time);
#endif
*pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) +
((tm->tm_sec) >> 1));
*pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) +
((tm->tm_mon + 1) << 5) + tm->tm_mday);
}
#endif
#ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_get_file_modified_time(const char *pFilename,
mz_uint16 *pDOS_time,
mz_uint16 *pDOS_date) {
#ifdef MINIZ_NO_TIME
(void)pFilename;
*pDOS_date = *pDOS_time = 0;
#else
struct MZ_FILE_STAT_STRUCT file_stat;
// On Linux with x86 glibc, this call will fail on large files (>= 0x80000000
// bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
return MZ_FALSE;
mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
#endif // #ifdef MINIZ_NO_TIME
return MZ_TRUE;
}
#ifndef MINIZ_NO_TIME
static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time,
time_t modified_time) {
struct utimbuf t;
t.actime = access_time;
t.modtime = modified_time;
return !utime(pFilename, &t);
}
#endif // #ifndef MINIZ_NO_TIME
#endif // #ifndef MINIZ_NO_STDIO
static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip,
mz_uint32 flags) {
(void)flags;
if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (!pZip->m_pAlloc)
pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree)
pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc)
pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_READING;
pZip->m_archive_size = 0;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static MZ_FORCEINLINE mz_bool
mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets,
mz_uint l_index, mz_uint r_index) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
const mz_uint8 *pR =
&MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS),
r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
break;
pL++;
pR++;
}
return (pL == pE) ? (l_len < r_len) : (l < r);
}
#define MZ_SWAP_UINT32(a, b) \
do { \
mz_uint32 t = a; \
a = b; \
b = t; \
} \
MZ_MACRO_END
// Heap sort of lowercased filenames, used to help accelerate plain central
// directory searches by mz_zip_reader_locate_file(). (Could also use qsort(),
// but it could allocate memory.)
static void
mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices =
&MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
0);
const int size = pZip->m_total_files;
int start = (size - 2) >> 1, end;
while (start >= 0) {
int child, root = start;
for (;;) {
if ((child = (root << 1) + 1) >= size)
break;
child +=
(((child + 1) < size) &&
(mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1])));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
start--;
}
end = size - 1;
while (end > 0) {
int child, root = 0;
MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
for (;;) {
if ((child = (root << 1) + 1) >= end)
break;
child +=
(((child + 1) < end) &&
mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[child], pIndices[child + 1]));
if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets,
pIndices[root], pIndices[child]))
break;
MZ_SWAP_UINT32(pIndices[root], pIndices[child]);
root = child;
}
end--;
}
}
static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip,
mz_uint32 flags) {
mz_uint cdir_size, num_this_disk, cdir_disk_index;
mz_uint64 cdir_ofs;
mz_int64 cur_file_ofs;
const mz_uint8 *p;
mz_uint32 buf_u32[4096 / sizeof(mz_uint32)];
mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
mz_bool sort_central_dir =
((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
// Basic sanity checks - reject files which are too small, and check the first
// 4 bytes of the file to make sure a local header is there.
if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
// Find the end of central directory record by scanning the file from the end
// towards the beginning.
cur_file_ofs =
MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
for (;;) {
int i,
n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
return MZ_FALSE;
for (i = n - 4; i >= 0; --i)
if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
break;
if (i >= 0) {
cur_file_ofs += i;
break;
}
if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >=
(0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
return MZ_FALSE;
cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
}
// Read and verify the end of central directory record.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) !=
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
((pZip->m_total_files =
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) !=
MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
return MZ_FALSE;
num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
if (((num_this_disk | cdir_disk_index) != 0) &&
((num_this_disk != 1) || (cdir_disk_index != 1)))
return MZ_FALSE;
if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) <
pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
return MZ_FALSE;
pZip->m_central_directory_file_ofs = cdir_ofs;
if (pZip->m_total_files) {
mz_uint i, n;
// Read the entire central directory into a heap block, and allocate another
// heap block to hold the unsorted central dir file record offsets, and
// another to hold the sorted indices.
if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size,
MZ_FALSE)) ||
(!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets,
pZip->m_total_files, MZ_FALSE)))
return MZ_FALSE;
if (sort_central_dir) {
if (!mz_zip_array_resize(pZip,
&pZip->m_pState->m_sorted_central_dir_offsets,
pZip->m_total_files, MZ_FALSE))
return MZ_FALSE;
}
if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs,
pZip->m_pState->m_central_dir.m_p,
cdir_size) != cdir_size)
return MZ_FALSE;
// Now create an index into the central directory file records, do some
// basic sanity checking on each record, and check for zip64 entries (which
// are not yet supported).
p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) {
mz_uint total_header_size, comp_size, decomp_size, disk_index;
if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) ||
(MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
return MZ_FALSE;
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32,
i) =
(mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
if (sort_central_dir)
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets,
mz_uint32, i) = i;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) &&
(decomp_size != comp_size)) ||
(decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) ||
(comp_size == 0xFFFFFFFF))
return MZ_FALSE;
disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
if ((disk_index != num_this_disk) && (disk_index != 1))
return MZ_FALSE;
if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) >
n)
return MZ_FALSE;
n -= total_header_size;
p += total_header_size;
}
}
if (sort_central_dir)
mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
return MZ_TRUE;
}
mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size,
mz_uint32 flags) {
if ((!pZip) || (!pZip->m_pRead))
return MZ_FALSE;
if (!mz_zip_reader_init_internal(pZip, flags))
return MZ_FALSE;
pZip->m_archive_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
size_t s = (file_ofs >= pZip->m_archive_size)
? 0
: (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
return s;
}
mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem,
size_t size, mz_uint32 flags) {
if (!mz_zip_reader_init_internal(pZip, flags))
return MZ_FALSE;
pZip->m_archive_size = size;
pZip->m_pRead = mz_zip_mem_read_func;
pZip->m_pIO_opaque = pZip;
#ifdef __cplusplus
pZip->m_pState->m_pMem = const_cast<void *>(pMem);
#else
pZip->m_pState->m_pMem = (void *)pMem;
#endif
pZip->m_pState->m_mem_size = size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs,
void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint32 flags) {
mz_uint64 file_size;
MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
if (!pFile)
return MZ_FALSE;
if (MZ_FSEEK64(pFile, 0, SEEK_END)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
file_size = MZ_FTELL64(pFile);
if (!mz_zip_reader_init_internal(pZip, flags)) {
MZ_FCLOSE(pFile);
return MZ_FALSE;
}
pZip->m_pRead = mz_zip_file_read_func;
pZip->m_pIO_opaque = pZip;
pZip->m_pState->m_pFile = pFile;
pZip->m_archive_size = file_size;
if (!mz_zip_reader_read_central_dir(pZip, flags)) {
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) {
return pZip ? pZip->m_total_files : 0;
}
static MZ_FORCEINLINE const mz_uint8 *
mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) {
if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return NULL;
return &MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
mz_uint32, file_index));
}
mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint m_bit_flag;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p)
return MZ_FALSE;
m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
return (m_bit_flag & 1);
}
mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip,
mz_uint file_index) {
mz_uint filename_len, external_attr;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p)
return MZ_FALSE;
// First see if the filename ends with a '/' character.
filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_len) {
if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
return MZ_TRUE;
}
// Bugfix: This code was also checking if the internal attribute was non-zero,
// which wasn't correct.
// Most/all zip writers (hopefully) set DOS file/directory attributes in the
// low 16-bits, so check for the DOS directory flag and ignore the source OS
// ID in the created by field.
// FIXME: Remove this check? Is it necessary - we already check the filename.
external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
if ((external_attr & 0x10) != 0)
return MZ_TRUE;
return MZ_FALSE;
}
mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index,
mz_zip_archive_file_stat *pStat) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if ((!p) || (!pStat))
return MZ_FALSE;
// Unpack the central directory record.
pStat->m_file_index = file_index;
pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
#ifndef MINIZ_NO_TIME
pStat->m_time =
mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS),
MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
#endif
pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
// Copy as much of the filename and comment as possible.
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pStat->m_filename[n] = '\0';
n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS);
n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
pStat->m_comment_size = n;
memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS),
n);
pStat->m_comment[n] = '\0';
return MZ_TRUE;
}
mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index,
char *pFilename, mz_uint filename_buf_size) {
mz_uint n;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
if (!p) {
if (filename_buf_size)
pFilename[0] = '\0';
return 0;
}
n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
if (filename_buf_size) {
n = MZ_MIN(n, filename_buf_size - 1);
memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
pFilename[n] = '\0';
}
return n + 1;
}
static MZ_FORCEINLINE mz_bool
mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len,
mz_uint flags) {
mz_uint i;
if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
return 0 == memcmp(pA, pB, len);
for (i = 0; i < len; ++i)
if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
return MZ_FALSE;
return MZ_TRUE;
}
static MZ_FORCEINLINE int
mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array,
const mz_zip_array *pCentral_dir_offsets,
mz_uint l_index, const char *pR, mz_uint r_len) {
const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(
pCentral_dir_array, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32,
l_index)),
*pE;
mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
mz_uint8 l = 0, r = 0;
pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
pE = pL + MZ_MIN(l_len, r_len);
while (pL < pE) {
if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
break;
pL++;
pR++;
}
return (pL == pE) ? (int)(l_len - r_len) : (l - r);
}
static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState = pZip->m_pState;
const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
const mz_zip_array *pCentral_dir = &pState->m_central_dir;
mz_uint32 *pIndices =
&MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32,
0);
const int size = pZip->m_total_files;
const mz_uint filename_len = (mz_uint)strlen(pFilename);
int l = 0, h = size - 1;
while (l <= h) {
int m = (l + h) >> 1, file_index = pIndices[m],
comp =
mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets,
file_index, pFilename, filename_len);
if (!comp)
return file_index;
else if (comp < 0)
l = m + 1;
else
h = m - 1;
}
return -1;
}
int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName,
const char *pComment, mz_uint flags) {
mz_uint file_index;
size_t name_len, comment_len;
if ((!pZip) || (!pZip->m_pState) || (!pName) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return -1;
if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) &&
(!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
return mz_zip_reader_locate_file_binary_search(pZip, pName);
name_len = strlen(pName);
if (name_len > 0xFFFF)
return -1;
comment_len = pComment ? strlen(pComment) : 0;
if (comment_len > 0xFFFF)
return -1;
for (file_index = 0; file_index < pZip->m_total_files; file_index++) {
const mz_uint8 *pHeader =
&MZ_ZIP_ARRAY_ELEMENT(
&pZip->m_pState->m_central_dir, mz_uint8,
MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets,
mz_uint32, file_index));
mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
const char *pFilename =
(const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
if (filename_len < name_len)
continue;
if (comment_len) {
mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS),
file_comment_len =
MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
const char *pFile_comment = pFilename + filename_len + file_extra_len;
if ((file_comment_len != comment_len) ||
(!mz_zip_reader_string_equal(pComment, pFile_comment,
file_comment_len, flags)))
continue;
}
if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) {
int ofs = filename_len - 1;
do {
if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') ||
(pFilename[ofs] == ':'))
break;
} while (--ofs >= 0);
ofs++;
pFilename += ofs;
filename_len -= ofs;
}
if ((filename_len == name_len) &&
(mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
return file_index;
}
return -1;
}
mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip,
mz_uint file_index, void *pBuf,
size_t buf_size, mz_uint flags,
void *pUser_read_buf,
size_t user_read_buf_size) {
int status = TINFL_STATUS_DONE;
mz_uint64 needed_size, cur_file_ofs, comp_remaining,
out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
mz_zip_archive_file_stat file_stat;
void *pRead_buf;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
tinfl_decompressor inflator;
if ((buf_size) && (!pBuf))
return MZ_FALSE;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size)
return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index))
return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32))
return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Ensure supplied output buffer is large enough.
needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size
: file_stat.m_uncomp_size;
if (buf_size < needed_size)
return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf,
(size_t)needed_size) != needed_size)
return MZ_FALSE;
return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
}
// Decompress the file either directly from memory or from a file input
// buffer.
tinfl_init(&inflator);
if (pZip->m_pState->m_pMem) {
// Read directly from the archive in memory.
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else if (pUser_read_buf) {
// Use a user provided read buffer.
if (!user_read_buf_size)
return MZ_FALSE;
pRead_buf = (mz_uint8 *)pUser_read_buf;
read_buf_size = user_read_buf_size;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
} else {
// Temporarily allocate a read buffer.
read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(read_buf_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
#endif
return MZ_FALSE;
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
do {
size_t in_buf_size,
out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size,
TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF |
(comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
out_buf_ofs += out_buf_size;
} while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
if (status == TINFL_STATUS_DONE) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf,
(size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(
mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size,
mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, pUser_read_buf,
user_read_buf_size);
}
mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index,
void *pBuf, size_t buf_size,
mz_uint flags) {
return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size,
flags, NULL, 0);
}
mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip,
const char *pFilename, void *pBuf,
size_t buf_size, mz_uint flags) {
return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf,
buf_size, flags, NULL, 0);
}
void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index,
size_t *pSize, mz_uint flags) {
mz_uint64 comp_size, uncomp_size, alloc_size;
const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
void *pBuf;
if (pSize)
*pSize = 0;
if (!p)
return NULL;
comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
#endif
return NULL;
if (NULL ==
(pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
return NULL;
if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size,
flags)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return NULL;
}
if (pSize)
*pSize = (size_t)alloc_size;
return pBuf;
}
void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip,
const char *pFilename, size_t *pSize,
mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0) {
if (pSize)
*pSize = 0;
return MZ_FALSE;
}
return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
}
mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip,
mz_uint file_index,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int status = TINFL_STATUS_DONE;
mz_uint file_crc32 = MZ_CRC32_INIT;
mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining,
out_buf_ofs = 0, cur_file_ofs;
mz_zip_archive_file_stat file_stat;
void *pRead_buf = NULL;
void *pWrite_buf = NULL;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
// Empty file, or a directory (but not always a directory - I've seen odd zips
// with directories that have compressed data which inflates to 0 bytes)
if (!file_stat.m_comp_size)
return MZ_TRUE;
// Entry is a subdirectory (I've seen old zips with dir entries which have
// compressed deflate data which inflates to 0 bytes, but these entries claim
// to uncompress to 512 bytes in the headers).
// I'm torn how to handle this case - should it fail instead?
if (mz_zip_reader_is_file_a_directory(pZip, file_index))
return MZ_TRUE;
// Encryption and patch files are not supported.
if (file_stat.m_bit_flag & (1 | 32))
return MZ_FALSE;
// This function only supports stored and deflate.
if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) &&
(file_stat.m_method != MZ_DEFLATED))
return MZ_FALSE;
// Read and parse the local directory entry.
cur_file_ofs = file_stat.m_local_header_ofs;
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
return MZ_FALSE;
// Decompress the file either directly from memory or from a file input
// buffer.
if (pZip->m_pState->m_pMem) {
pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
read_buf_size = read_buf_avail = file_stat.m_comp_size;
comp_remaining = 0;
} else {
read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)read_buf_size)))
return MZ_FALSE;
read_buf_avail = 0;
comp_remaining = file_stat.m_comp_size;
}
if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) {
// The file is stored or the caller has requested the compressed data.
if (pZip->m_pState->m_pMem) {
#ifdef _MSC_VER
if (((0, sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#else
if (((sizeof(size_t) == sizeof(mz_uint32))) &&
(file_stat.m_comp_size > 0xFFFFFFFF))
#endif
return MZ_FALSE;
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
status = TINFL_STATUS_FAILED;
else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf,
(size_t)file_stat.m_comp_size);
cur_file_ofs += file_stat.m_comp_size;
out_buf_ofs += file_stat.m_comp_size;
comp_remaining = 0;
} else {
while (comp_remaining) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
file_crc32 = (mz_uint32)mz_crc32(
file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
if (pCallback(pOpaque, out_buf_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
out_buf_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
}
}
} else {
tinfl_decompressor inflator;
tinfl_init(&inflator);
if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
TINFL_LZ_DICT_SIZE)))
status = TINFL_STATUS_FAILED;
else {
do {
mz_uint8 *pWrite_buf_cur =
(mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
size_t in_buf_size,
out_buf_size =
TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) {
read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf,
(size_t)read_buf_avail) != read_buf_avail) {
status = TINFL_STATUS_FAILED;
break;
}
cur_file_ofs += read_buf_avail;
comp_remaining -= read_buf_avail;
read_buf_ofs = 0;
}
in_buf_size = (size_t)read_buf_avail;
status = tinfl_decompress(
&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size,
(mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size,
comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
read_buf_avail -= in_buf_size;
read_buf_ofs += in_buf_size;
if (out_buf_size) {
if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) !=
out_buf_size) {
status = TINFL_STATUS_FAILED;
break;
}
file_crc32 =
(mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) {
status = TINFL_STATUS_FAILED;
break;
}
}
} while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) ||
(status == TINFL_STATUS_HAS_MORE_OUTPUT));
}
}
if ((status == TINFL_STATUS_DONE) &&
(!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) {
// Make sure the entire file was decompressed, and check its CRC.
if ((out_buf_ofs != file_stat.m_uncomp_size) ||
(file_crc32 != file_stat.m_crc32))
status = TINFL_STATUS_FAILED;
}
if (!pZip->m_pState->m_pMem)
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
if (pWrite_buf)
pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
return status == TINFL_STATUS_DONE;
}
mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip,
const char *pFilename,
mz_file_write_func pCallback,
void *pOpaque, mz_uint flags) {
int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque,
flags);
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs,
const void *pBuf, size_t n) {
(void)ofs;
return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque);
}
mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index,
const char *pDst_filename,
mz_uint flags) {
mz_bool status;
mz_zip_archive_file_stat file_stat;
MZ_FILE *pFile;
if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
return MZ_FALSE;
pFile = MZ_FOPEN(pDst_filename, "wb");
if (!pFile)
return MZ_FALSE;
status = mz_zip_reader_extract_to_callback(
pZip, file_index, mz_zip_file_write_callback, pFile, flags);
if (MZ_FCLOSE(pFile) == EOF)
return MZ_FALSE;
#ifndef MINIZ_NO_TIME
if (status)
mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
#endif
return status;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_end(mz_zip_archive *pZip) {
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
if (pZip->m_pState) {
mz_zip_internal_state *pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
}
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip,
const char *pArchive_filename,
const char *pDst_filename,
mz_uint flags) {
int file_index =
mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
if (file_index < 0)
return MZ_FALSE;
return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
}
#endif
// ------------------- .ZIP archive writing
#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
static void mz_write_le16(mz_uint8 *p, mz_uint16 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
}
static void mz_write_le32(mz_uint8 *p, mz_uint32 v) {
p[0] = (mz_uint8)v;
p[1] = (mz_uint8)(v >> 8);
p[2] = (mz_uint8)(v >> 16);
p[3] = (mz_uint8)(v >> 24);
}
#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) {
if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
return MZ_FALSE;
if (pZip->m_file_offset_alignment) {
// Ensure user specified file offset alignment is a power of 2.
if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
return MZ_FALSE;
}
if (!pZip->m_pAlloc)
pZip->m_pAlloc = def_alloc_func;
if (!pZip->m_pFree)
pZip->m_pFree = def_free_func;
if (!pZip->m_pRealloc)
pZip->m_pRealloc = def_realloc_func;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_archive_size = existing_size;
pZip->m_central_directory_file_ofs = 0;
pZip->m_total_files = 0;
if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
return MZ_FALSE;
memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir,
sizeof(mz_uint8));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets,
sizeof(mz_uint32));
MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets,
sizeof(mz_uint32));
return MZ_TRUE;
}
static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
#ifdef _MSC_VER
if ((!n) ||
((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#else
if ((!n) ||
((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
#endif
return 0;
if (new_size > pState->m_mem_capacity) {
void *pNew_block;
size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity);
while (new_capacity < new_size)
new_capacity *= 2;
if (NULL == (pNew_block = pZip->m_pRealloc(
pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
return 0;
pState->m_pMem = pNew_block;
pState->m_mem_capacity = new_capacity;
}
memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
pState->m_mem_size = (size_t)new_size;
return n;
}
mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip,
size_t size_to_reserve_at_beginning,
size_t initial_allocation_size) {
pZip->m_pWrite = mz_zip_heap_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
return MZ_FALSE;
if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size,
size_to_reserve_at_beginning))) {
if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, initial_allocation_size))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_mem_capacity = initial_allocation_size;
}
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs,
const void *pBuf, size_t n) {
mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
if (((mz_int64)file_ofs < 0) ||
(((cur_ofs != (mz_int64)file_ofs)) &&
(MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
return 0;
return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
}
mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename,
mz_uint64 size_to_reserve_at_beginning) {
MZ_FILE *pFile;
pZip->m_pWrite = mz_zip_file_write_func;
pZip->m_pIO_opaque = pZip;
if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
return MZ_FALSE;
if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
pZip->m_pState->m_pFile = pFile;
if (size_to_reserve_at_beginning) {
mz_uint64 cur_ofs = 0;
char buf[4096];
MZ_CLEAR_OBJ(buf);
do {
size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) {
mz_zip_writer_end(pZip);
return MZ_FALSE;
}
cur_ofs += n;
size_to_reserve_at_beginning -= n;
} while (size_to_reserve_at_beginning);
}
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip,
const char *pFilename) {
mz_zip_internal_state *pState;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
return MZ_FALSE;
// No sense in trying to write to an archive that's already at the support max
// size
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
pState = pZip->m_pState;
if (pState->m_pFile) {
#ifdef MINIZ_NO_STDIO
pFilename;
return MZ_FALSE;
#else
// Archive is being read from stdio - try to reopen as writable.
if (pZip->m_pIO_opaque != pZip)
return MZ_FALSE;
if (!pFilename)
return MZ_FALSE;
pZip->m_pWrite = mz_zip_file_write_func;
if (NULL ==
(pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) {
// The mz_zip_archive is now in a bogus state because pState->m_pFile is
// NULL, so just close it.
mz_zip_reader_end(pZip);
return MZ_FALSE;
}
#endif // #ifdef MINIZ_NO_STDIO
} else if (pState->m_pMem) {
// Archive lives in a memory block. Assume it's from the heap that we can
// resize using the realloc callback.
if (pZip->m_pIO_opaque != pZip)
return MZ_FALSE;
pState->m_mem_capacity = pState->m_mem_size;
pZip->m_pWrite = mz_zip_heap_write_func;
}
// Archive is being read via a user provided read function - make sure the
// user has specified a write function too.
else if (!pZip->m_pWrite)
return MZ_FALSE;
// Start writing new files at the archive's current central directory
// location.
pZip->m_archive_size = pZip->m_central_directory_file_ofs;
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
pZip->m_central_directory_file_ofs = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name,
const void *pBuf, size_t buf_size,
mz_uint level_and_flags) {
return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0,
level_and_flags, 0, 0);
}
typedef struct {
mz_zip_archive *m_pZip;
mz_uint64 m_cur_archive_file_ofs;
mz_uint64 m_comp_size;
} mz_zip_writer_add_state;
static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len,
void *pUser) {
mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque,
pState->m_cur_archive_file_ofs, pBuf,
len) != len)
return MZ_FALSE;
pState->m_cur_archive_file_ofs += len;
pState->m_comp_size += len;
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_local_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_create_central_dir_header(
mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size,
mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size,
mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method,
mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date,
mz_uint64 local_header_ofs, mz_uint32 ext_attributes) {
(void)pZip;
memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
return MZ_TRUE;
}
static mz_bool mz_zip_writer_add_to_central_dir(
mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size,
const void *pExtra, mz_uint16 extra_size, const void *pComment,
mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size,
mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags,
mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs,
mz_uint32 ext_attributes) {
mz_zip_internal_state *pState = pZip->m_pState;
mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
size_t orig_central_dir_size = pState->m_central_dir.m_size;
mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
// No zip64 support yet
if ((local_header_ofs > 0xFFFFFFFF) ||
(((mz_uint64)pState->m_central_dir.m_size +
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size +
comment_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_central_dir_header(
pZip, central_dir_header, filename_size, extra_size, comment_size,
uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time,
dos_date, local_header_ofs, ext_attributes))
return MZ_FALSE;
if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename,
filename_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra,
extra_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment,
comment_size)) ||
(!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets,
¢ral_dir_ofs, 1))) {
// Try to push the central directory array back into its original state.
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
return MZ_TRUE;
}
static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) {
// Basic ZIP archive filename validity checks: Valid filenames cannot start
// with a forward slash, cannot contain a drive letter, and cannot use
// DOS-style backward slashes.
if (*pArchive_name == '/')
return MZ_FALSE;
while (*pArchive_name) {
if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
return MZ_FALSE;
pArchive_name++;
}
return MZ_TRUE;
}
static mz_uint
mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) {
mz_uint32 n;
if (!pZip->m_file_offset_alignment)
return 0;
n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
return (pZip->m_file_offset_alignment - n) &
(pZip->m_file_offset_alignment - 1);
}
static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip,
mz_uint64 cur_file_ofs, mz_uint32 n) {
char buf[4096];
memset(buf, 0, MZ_MIN(sizeof(buf), n));
while (n) {
mz_uint32 s = MZ_MIN(sizeof(buf), n);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
return MZ_FALSE;
cur_file_ofs += s;
n -= s;
}
return MZ_TRUE;
}
mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip,
const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags, mz_uint64 uncomp_size,
mz_uint32 uncomp_crc32) {
mz_uint16 method = 0, dos_time = 0, dos_date = 0;
mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
tdefl_compressor *pComp = NULL;
mz_bool store_data_uncompressed;
mz_zip_internal_state *pState;
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
store_data_uncompressed =
((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) ||
(!pArchive_name) || ((comment_size) && (!pComment)) ||
(pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
pState = pZip->m_pState;
if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
return MZ_FALSE;
// No zip64 support yet
if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
#ifndef MINIZ_NO_TIME
{
time_t cur_time;
time(&cur_time);
mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
}
#endif // #ifndef MINIZ_NO_TIME
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF)
return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) {
// Set DOS Subdirectory attribute bit.
ext_attributes |= 0x10;
// Subdirectories cannot contain data.
if ((buf_size) || (uncomp_size))
return MZ_FALSE;
}
// Try to do any allocations before writing to the archive, so if an
// allocation fails the file remains unmodified. (A good idea if we're doing
// an in-place modification.)
if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
archive_name_size + comment_size)) ||
(!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
return MZ_FALSE;
if ((!store_data_uncompressed) && (buf_size)) {
if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
return MZ_FALSE;
}
if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
num_alignment_padding_bytes +
sizeof(local_dir_header))) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) {
uncomp_crc32 =
(mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size);
uncomp_size = buf_size;
if (uncomp_size <= 3) {
level = 0;
store_data_uncompressed = MZ_TRUE;
}
}
if (store_data_uncompressed) {
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf,
buf_size) != buf_size) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
cur_archive_file_ofs += buf_size;
comp_size = buf_size;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
method = MZ_DEFLATED;
} else if (buf_size) {
mz_zip_writer_add_state state;
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) ||
(tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) !=
TDEFL_STATUS_DONE)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pComp = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name,
const char *pSrc_filename, const void *pComment,
mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
mz_uint64 local_dir_header_ofs = pZip->m_archive_size,
cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0,
comp_size = 0;
size_t archive_name_size;
mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
MZ_FILE *pSrc_file = NULL;
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
level = level_and_flags & 0xF;
if ((!pZip) || (!pZip->m_pState) ||
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) ||
((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
archive_name_size = strlen(pArchive_name);
if (archive_name_size > 0xFFFF)
return MZ_FALSE;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE +
comment_size + archive_name_size) > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
return MZ_FALSE;
pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
if (!pSrc_file)
return MZ_FALSE;
MZ_FSEEK64(pSrc_file, 0, SEEK_END);
uncomp_size = MZ_FTELL64(pSrc_file);
MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
if (uncomp_size > 0xFFFFFFFF) {
// No zip64 support yet
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (uncomp_size <= 3)
level = 0;
if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs,
num_alignment_padding_bytes +
sizeof(local_dir_header))) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
local_dir_header_ofs += num_alignment_padding_bytes;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
cur_archive_file_ofs +=
num_alignment_padding_bytes + sizeof(local_dir_header);
MZ_CLEAR_OBJ(local_dir_header);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name,
archive_name_size) != archive_name_size) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
cur_archive_file_ofs += archive_name_size;
if (uncomp_size) {
mz_uint64 uncomp_remaining = uncomp_size;
void *pRead_buf =
pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
if (!pRead_buf) {
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
if (!level) {
while (uncomp_remaining) {
mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) ||
(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf,
n) != n)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
uncomp_crc32 =
(mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
uncomp_remaining -= n;
cur_archive_file_ofs += n;
}
comp_size = uncomp_size;
} else {
mz_bool result = MZ_FALSE;
mz_zip_writer_add_state state;
tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(
pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
if (!pComp) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
state.m_pZip = pZip;
state.m_cur_archive_file_ofs = cur_archive_file_ofs;
state.m_comp_size = 0;
if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state,
tdefl_create_comp_flags_from_zip_params(
level, -15, MZ_DEFAULT_STRATEGY)) !=
TDEFL_STATUS_OKAY) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
for (;;) {
size_t in_buf_size =
(mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE);
tdefl_status status;
if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
break;
uncomp_crc32 = (mz_uint32)mz_crc32(
uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
uncomp_remaining -= in_buf_size;
status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size,
uncomp_remaining ? TDEFL_NO_FLUSH
: TDEFL_FINISH);
if (status == TDEFL_STATUS_DONE) {
result = MZ_TRUE;
break;
} else if (status != TDEFL_STATUS_OKAY)
break;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
if (!result) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
MZ_FCLOSE(pSrc_file);
return MZ_FALSE;
}
comp_size = state.m_comp_size;
cur_archive_file_ofs = state.m_cur_archive_file_ofs;
method = MZ_DEFLATED;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
}
MZ_FCLOSE(pSrc_file);
pSrc_file = NULL;
// no zip64 support yet
if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
return MZ_FALSE;
if (!mz_zip_writer_create_local_dir_header(
pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size,
comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
return MZ_FALSE;
if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header,
sizeof(local_dir_header)) != sizeof(local_dir_header))
return MZ_FALSE;
if (!mz_zip_writer_add_to_central_dir(
pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment,
comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0,
dos_time, dos_date, local_dir_header_ofs, ext_attributes))
return MZ_FALSE;
pZip->m_total_files++;
pZip->m_archive_size = cur_archive_file_ofs;
return MZ_TRUE;
}
#endif // #ifndef MINIZ_NO_STDIO
mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip,
mz_zip_archive *pSource_zip,
mz_uint file_index) {
mz_uint n, bit_flags, num_alignment_padding_bytes;
mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
mz_uint32
local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) /
sizeof(mz_uint32)];
mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
size_t orig_central_dir_size;
mz_zip_internal_state *pState;
void *pBuf;
const mz_uint8 *pSrc_central_header;
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
if (NULL ==
(pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
return MZ_FALSE;
pState = pZip->m_pState;
num_alignment_padding_bytes =
mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
// no zip64 support yet
if ((pZip->m_total_files == 0xFFFF) ||
((pZip->m_archive_size + num_alignment_padding_bytes +
MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) >
0xFFFFFFFF))
return MZ_FALSE;
cur_src_file_ofs =
MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
cur_dst_file_ofs = pZip->m_archive_size;
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs,
pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
return MZ_FALSE;
cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs,
num_alignment_padding_bytes))
return MZ_FALSE;
cur_dst_file_ofs += num_alignment_padding_bytes;
local_dir_header_ofs = cur_dst_file_ofs;
if (pZip->m_file_offset_alignment) {
MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) ==
0);
}
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header,
MZ_ZIP_LOCAL_DIR_HEADER_SIZE) !=
MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
return MZ_FALSE;
cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
comp_bytes_remaining =
n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
if (NULL ==
(pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1,
(size_t)MZ_MAX(sizeof(mz_uint32) * 4,
MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE,
comp_bytes_remaining)))))
return MZ_FALSE;
while (comp_bytes_remaining) {
n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_dst_file_ofs += n;
comp_bytes_remaining -= n;
}
bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
if (bit_flags & 8) {
// Copy data descriptor
if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf,
sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
return MZ_FALSE;
}
cur_src_file_ofs += n;
cur_dst_file_ofs += n;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
// no zip64 support yet
if (cur_dst_file_ofs > 0xFFFFFFFF)
return MZ_FALSE;
orig_central_dir_size = pState->m_central_dir.m_size;
memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS,
local_dir_header_ofs);
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header,
MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
return MZ_FALSE;
n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) +
MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
if (!mz_zip_array_push_back(
pZip, &pState->m_central_dir,
pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
if (pState->m_central_dir.m_size > 0xFFFFFFFF)
return MZ_FALSE;
n = (mz_uint32)orig_central_dir_size;
if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) {
mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size,
MZ_FALSE);
return MZ_FALSE;
}
pZip->m_total_files++;
pZip->m_archive_size = cur_dst_file_ofs;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_uint64 central_dir_ofs, central_dir_size;
mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
return MZ_FALSE;
pState = pZip->m_pState;
// no zip64 support yet
if ((pZip->m_total_files > 0xFFFF) ||
((pZip->m_archive_size + pState->m_central_dir.m_size +
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
return MZ_FALSE;
central_dir_ofs = 0;
central_dir_size = 0;
if (pZip->m_total_files) {
// Write central directory
central_dir_ofs = pZip->m_archive_size;
central_dir_size = pState->m_central_dir.m_size;
pZip->m_central_directory_file_ofs = central_dir_ofs;
if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs,
pState->m_central_dir.m_p,
(size_t)central_dir_size) != central_dir_size)
return MZ_FALSE;
pZip->m_archive_size += central_dir_size;
}
// Write end of central directory record
MZ_CLEAR_OBJ(hdr);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS,
MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS,
pZip->m_total_files);
MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr,
sizeof(hdr)) != sizeof(hdr))
return MZ_FALSE;
#ifndef MINIZ_NO_STDIO
if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
return MZ_FALSE;
#endif // #ifndef MINIZ_NO_STDIO
pZip->m_archive_size += sizeof(hdr);
pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
return MZ_TRUE;
}
mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf,
size_t *pSize) {
if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
return MZ_FALSE;
if (pZip->m_pWrite != mz_zip_heap_write_func)
return MZ_FALSE;
if (!mz_zip_writer_finalize_archive(pZip))
return MZ_FALSE;
*pBuf = pZip->m_pState->m_pMem;
*pSize = pZip->m_pState->m_mem_size;
pZip->m_pState->m_pMem = NULL;
pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
return MZ_TRUE;
}
mz_bool mz_zip_writer_end(mz_zip_archive *pZip) {
mz_zip_internal_state *pState;
mz_bool status = MZ_TRUE;
if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) ||
((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) &&
(pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
return MZ_FALSE;
pState = pZip->m_pState;
pZip->m_pState = NULL;
mz_zip_array_clear(pZip, &pState->m_central_dir);
mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
#ifndef MINIZ_NO_STDIO
if (pState->m_pFile) {
MZ_FCLOSE(pState->m_pFile);
pState->m_pFile = NULL;
}
#endif // #ifndef MINIZ_NO_STDIO
if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) {
pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
pState->m_pMem = NULL;
}
pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
return status;
}
#ifndef MINIZ_NO_STDIO
mz_bool mz_zip_add_mem_to_archive_file_in_place(
const char *pZip_filename, const char *pArchive_name, const void *pBuf,
size_t buf_size, const void *pComment, mz_uint16 comment_size,
mz_uint level_and_flags) {
mz_bool status, created_new_archive = MZ_FALSE;
mz_zip_archive zip_archive;
struct MZ_FILE_STAT_STRUCT file_stat;
MZ_CLEAR_OBJ(zip_archive);
if ((int)level_and_flags < 0)
level_and_flags = MZ_DEFAULT_LEVEL;
if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) ||
((comment_size) && (!pComment)) ||
((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
return MZ_FALSE;
if (!mz_zip_writer_validate_archive_name(pArchive_name))
return MZ_FALSE;
if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) {
// Create a new archive.
if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
return MZ_FALSE;
created_new_archive = MZ_TRUE;
} else {
// Append to an existing archive.
if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
level_and_flags |
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return MZ_FALSE;
if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) {
mz_zip_reader_end(&zip_archive);
return MZ_FALSE;
}
}
status =
mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size,
pComment, comment_size, level_and_flags, 0, 0);
// Always finalize, even if adding failed for some reason, so we have a valid
// central directory. (This may not always succeed, but we can try.)
if (!mz_zip_writer_finalize_archive(&zip_archive))
status = MZ_FALSE;
if (!mz_zip_writer_end(&zip_archive))
status = MZ_FALSE;
if ((!status) && (created_new_archive)) {
// It's a new archive and something went wrong, so just delete it.
int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
(void)ignoredStatus;
}
return status;
}
void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename,
const char *pArchive_name,
size_t *pSize, mz_uint flags) {
int file_index;
mz_zip_archive zip_archive;
void *p = NULL;
if (pSize)
*pSize = 0;
if ((!pZip_filename) || (!pArchive_name))
return NULL;
MZ_CLEAR_OBJ(zip_archive);
if (!mz_zip_reader_init_file(&zip_archive, pZip_filename,
flags |
MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
return NULL;
if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL,
flags)) >= 0)
p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
mz_zip_reader_end(&zip_archive);
return p;
}
#endif // #ifndef MINIZ_NO_STDIO
#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
#endif // #ifndef MINIZ_NO_ARCHIVE_APIS
#ifdef __cplusplus
}
#endif
#endif // MINIZ_HEADER_FILE_ONLY
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
// ---------------------- end of miniz ----------------------------------------
}
bool IsBigEndian(void) {
union {
unsigned int i;
char c[4];
} bint = {0x01020304};
return bint.c[0] == 1;
}
void swap2(unsigned short *val) {
unsigned short tmp = *val;
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[1];
dst[1] = src[0];
}
void swap4(unsigned int *val) {
unsigned int tmp = *val;
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
}
void swap8(unsigned long long *val) {
unsigned long long tmp = (*val);
unsigned char *dst = (unsigned char *)val;
unsigned char *src = (unsigned char *)&tmp;
dst[0] = src[7];
dst[1] = src[6];
dst[2] = src[5];
dst[3] = src[4];
dst[4] = src[3];
dst[5] = src[2];
dst[6] = src[1];
dst[7] = src[0];
}
// https://gist.github.com/rygorous/2156668
// Reuse MINIZ_LITTLE_ENDIAN flag from miniz.
union FP32 {
unsigned int u;
float f;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 23;
unsigned int Exponent : 8;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 8;
unsigned int Mantissa : 23;
#endif
} s;
};
union FP16 {
unsigned short u;
struct {
#if MINIZ_LITTLE_ENDIAN
unsigned int Mantissa : 10;
unsigned int Exponent : 5;
unsigned int Sign : 1;
#else
unsigned int Sign : 1;
unsigned int Exponent : 5;
unsigned int Mantissa : 10;
#endif
} s;
};
FP32 half_to_float(FP16 h) {
static const FP32 magic = {113 << 23};
static const unsigned int shifted_exp = 0x7c00
<< 13; // exponent mask after shift
FP32 o;
o.u = (h.u & 0x7fff) << 13; // exponent/mantissa bits
unsigned int exp_ = shifted_exp & o.u; // just the exponent
o.u += (127 - 15) << 23; // exponent adjust
// handle exponent special cases
if (exp_ == shifted_exp) // Inf/NaN?
o.u += (128 - 16) << 23; // extra exp adjust
else if (exp_ == 0) // Zero/Denormal?
{
o.u += 1 << 23; // extra exp adjust
o.f -= magic.f; // renormalize
}
o.u |= (h.u & 0x8000) << 16; // sign bit
return o;
}
FP16 float_to_half_full(FP32 f) {
FP16 o = {0};
// Based on ISPC reference code (with minor modifications)
if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow)
o.s.Exponent = 0;
else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set)
{
o.s.Exponent = 31;
o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf
} else // Normalized number
{
// Exponent unbias the single, then bias the halfp
int newexp = f.s.Exponent - 127 + 15;
if (newexp >= 31) // Overflow, return signed infinity
o.s.Exponent = 31;
else if (newexp <= 0) // Underflow
{
if ((14 - newexp) <= 24) // Mantissa might be non-zero
{
unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit
o.s.Mantissa = mant >> (14 - newexp);
if ((mant >> (13 - newexp)) & 1) // Check for rounding
o.u++; // Round, might overflow into exp bit, but this is OK
}
} else {
o.s.Exponent = newexp;
o.s.Mantissa = f.s.Mantissa >> 13;
if (f.s.Mantissa & 0x1000) // Check for rounding
o.u++; // Round, might overflow to inf, this is OK
}
}
o.s.Sign = f.s.Sign;
return o;
}
// NOTE: From OpenEXR code
// #define IMF_INCREASING_Y 0
// #define IMF_DECREASING_Y 1
// #define IMF_RAMDOM_Y 2
//
// #define IMF_NO_COMPRESSION 0
// #define IMF_RLE_COMPRESSION 1
// #define IMF_ZIPS_COMPRESSION 2
// #define IMF_ZIP_COMPRESSION 3
// #define IMF_PIZ_COMPRESSION 4
// #define IMF_PXR24_COMPRESSION 5
// #define IMF_B44_COMPRESSION 6
// #define IMF_B44A_COMPRESSION 7
const char *ReadString(std::string &s, const char *ptr) {
// Read untile NULL(\0).
const char *p = ptr;
const char *q = ptr;
while ((*q) != 0)
q++;
s = std::string(p, q);
return q + 1; // skip '\0'
}
const char *ReadAttribute(std::string &name, std::string &ty,
std::vector<unsigned char> &data, const char *ptr) {
if ((*ptr) == 0) {
// end of attribute.
return NULL;
}
const char *p = ReadString(name, ptr);
p = ReadString(ty, p);
int dataLen;
memcpy(&dataLen, p, sizeof(int));
p += 4;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dataLen));
}
data.resize(dataLen);
memcpy(&data.at(0), p, dataLen);
p += dataLen;
return p;
}
void WriteAttribute(FILE *fp, const char *name, const char *type,
const unsigned char *data, int len) {
size_t n = fwrite(name, 1, strlen(name) + 1, fp);
assert(n == strlen(name) + 1);
n = fwrite(type, 1, strlen(type) + 1, fp);
assert(n == strlen(type) + 1);
int outLen = len;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&outLen));
}
n = fwrite(&outLen, 1, sizeof(int), fp);
assert(n == sizeof(int));
n = fwrite(data, 1, len, fp);
assert(n == (size_t)len);
(void)n;
}
void WriteAttributeToMemory(std::vector<unsigned char> &out, const char *name,
const char *type, const unsigned char *data,
int len) {
out.insert(out.end(), name, name + strlen(name) + 1);
out.insert(out.end(), type, type + strlen(type) + 1);
int outLen = len;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&outLen));
}
out.insert(out.end(), reinterpret_cast<unsigned char *>(&outLen),
reinterpret_cast<unsigned char *>(&outLen) + sizeof(int));
out.insert(out.end(), data, data + len);
}
typedef struct {
std::string name; // less than 255 bytes long
int pixelType;
unsigned char pLinear;
int xSampling;
int ySampling;
} ChannelInfo;
void ReadChannelInfo(std::vector<ChannelInfo> &channels,
const std::vector<unsigned char> &data) {
const char *p = reinterpret_cast<const char *>(&data.at(0));
for (;;) {
if ((*p) == 0) {
break;
}
ChannelInfo info;
p = ReadString(info.name, p);
memcpy(&info.pixelType, p, sizeof(int));
p += 4;
info.pLinear = p[0]; // uchar
p += 1 + 3; // reserved: uchar[3]
memcpy(&info.xSampling, p, sizeof(int)); // int
p += 4;
memcpy(&info.ySampling, p, sizeof(int)); // int
p += 4;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&info.pixelType));
swap4(reinterpret_cast<unsigned int *>(&info.xSampling));
swap4(reinterpret_cast<unsigned int *>(&info.ySampling));
}
channels.push_back(info);
}
}
void WriteChannelInfo(std::vector<unsigned char> &data,
const std::vector<ChannelInfo> &channels) {
size_t sz = 0;
// Calculate total size.
for (size_t c = 0; c < channels.size(); c++) {
sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0
sz += 16; // 4 * int
}
data.resize(sz + 1);
unsigned char *p = &data.at(0);
for (size_t c = 0; c < channels.size(); c++) {
memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str()));
p += strlen(channels[c].name.c_str());
(*p) = '\0';
p++;
int pixelType = channels[c].pixelType;
int xSampling = channels[c].xSampling;
int ySampling = channels[c].ySampling;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelType));
swap4(reinterpret_cast<unsigned int *>(&xSampling));
swap4(reinterpret_cast<unsigned int *>(&ySampling));
}
memcpy(p, &pixelType, sizeof(int));
p += sizeof(int);
(*p) = channels[c].pLinear;
p += 4;
memcpy(p, &xSampling, sizeof(int));
p += sizeof(int);
memcpy(p, &ySampling, sizeof(int));
p += sizeof(int);
}
(*p) = '\0';
}
void CompressZip(unsigned char *dst, unsigned long long &compressedSize,
const unsigned char *src, unsigned long srcSize) {
std::vector<unsigned char> tmpBuf(srcSize);
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
//
// Reorder the pixel data.
//
{
char *t1 = (char *)&tmpBuf.at(0);
char *t2 = (char *)&tmpBuf.at(0) + (srcSize + 1) / 2;
const char *stop = (const char *)src + srcSize;
while (true) {
if ((const char *)src < stop)
*(t1++) = *(src++);
else
break;
if ((const char *)src < stop)
*(t2++) = *(src++);
else
break;
}
}
//
// Predictor.
//
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + srcSize;
int p = t[-1];
while (t < stop) {
int d = int(t[0]) - p + (128 + 256);
p = t[0];
t[0] = d;
++t;
}
}
//
// Compress the data using miniz
//
miniz::mz_ulong outSize = miniz::mz_compressBound(srcSize);
int ret = miniz::mz_compress(dst, &outSize,
(const unsigned char *)&tmpBuf.at(0), srcSize);
assert(ret == miniz::MZ_OK);
(void)ret;
compressedSize = outSize;
}
void DecompressZip(unsigned char *dst, unsigned long &uncompressedSize,
const unsigned char *src, unsigned long srcSize) {
std::vector<unsigned char> tmpBuf(uncompressedSize);
int ret =
miniz::mz_uncompress(&tmpBuf.at(0), &uncompressedSize, src, srcSize);
assert(ret == miniz::MZ_OK);
(void)ret;
//
// Apply EXR-specific? postprocess. Grabbed from OpenEXR's
// ImfZipCompressor.cpp
//
// Predictor.
{
unsigned char *t = &tmpBuf.at(0) + 1;
unsigned char *stop = &tmpBuf.at(0) + uncompressedSize;
while (t < stop) {
int d = int(t[-1]) + int(t[0]) - 128;
t[0] = d;
++t;
}
}
// Reorder the pixel data.
{
const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0));
const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) +
(uncompressedSize + 1) / 2;
char *s = reinterpret_cast<char *>(dst);
char *stop = s + uncompressedSize;
while (true) {
if (s < stop)
*(s++) = *(t1++);
else
break;
if (s < stop)
*(s++) = *(t2++);
else
break;
}
}
}
//
// PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp
//
// -----------------------------------------------------------------
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC)
// (3 clause BSD license)
//
struct PIZChannelData {
unsigned short *start;
unsigned short *end;
int nx;
int ny;
int ys;
int size;
};
//-----------------------------------------------------------------------------
//
// 16-bit Haar Wavelet encoding and decoding
//
// The source code in this file is derived from the encoding
// and decoding routines written by Christian Rouet for his
// PIZ image file format.
//
//-----------------------------------------------------------------------------
//
// Wavelet basis functions without modulo arithmetic; they produce
// the best compression ratios when the wavelet-transformed data are
// Huffman-encoded, but the wavelet transform works only for 14-bit
// data (untransformed data values must be less than (1 << 14)).
//
#if 0 // @todo
inline void wenc14(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
short as = a;
short bs = b;
short ms = (as + bs) >> 1;
short ds = as - bs;
l = ms;
h = ds;
}
#endif
inline void wdec14(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
short ls = l;
short hs = h;
int hi = hs;
int ai = ls + (hi & 1) + (hi >> 1);
short as = ai;
short bs = ai - hi;
a = as;
b = bs;
}
//
// Wavelet basis functions with modulo arithmetic; they work with full
// 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't
// compress the data quite as well.
//
const int NBITS = 16;
const int A_OFFSET = 1 << (NBITS - 1);
// const int M_OFFSET = 1 << (NBITS - 1);
const int MOD_MASK = (1 << NBITS) - 1;
#if 0 // @ood
inline void wenc16(unsigned short a, unsigned short b, unsigned short &l,
unsigned short &h) {
int ao = (a + A_OFFSET) & MOD_MASK;
int m = ((ao + b) >> 1);
int d = ao - b;
if (d < 0)
m = (m + M_OFFSET) & MOD_MASK;
d &= MOD_MASK;
l = m;
h = d;
}
#endif
inline void wdec16(unsigned short l, unsigned short h, unsigned short &a,
unsigned short &b) {
int m = l;
int d = h;
int bb = (m - (d >> 1)) & MOD_MASK;
int aa = (d + bb - A_OFFSET) & MOD_MASK;
b = bb;
a = aa;
}
//
// 2D Wavelet encoding:
//
#if 0 // @todo
void wav2Encode(unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1; // == 1 << level
int p2 = 2; // == 1 << (level+1)
//
// Hierachical loop on smaller dimension n
//
while (p2 <= n) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet encoding
//
if (w14) {
wenc14(*px, *p01, i00, i01);
wenc14(*p10, *p11, i10, i11);
wenc14(i00, i10, *px, *p10);
wenc14(i01, i11, *p01, *p11);
} else {
wenc16(*px, *p01, i00, i01);
wenc16(*p10, *p11, i10, i11);
wenc16(i00, i10, *px, *p10);
wenc16(i01, i11, *p01, *p11);
}
}
//
// Encode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wenc14(*px, *p10, i00, *p10);
else
wenc16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Encode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wenc14(*px, *p01, i00, *p01);
else
wenc16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p = p2;
p2 <<= 1;
}
}
#endif
//
// 2D Wavelet decoding:
//
void wav2Decode(unsigned short *in, // io: values are transformed in place
int nx, // i : x size
int ox, // i : x offset
int ny, // i : y size
int oy, // i : y offset
unsigned short mx) // i : maximum in[x][y] value
{
bool w14 = (mx < (1 << 14));
int n = (nx > ny) ? ny : nx;
int p = 1;
int p2;
//
// Search max level
//
while (p <= n)
p <<= 1;
p >>= 1;
p2 = p;
p >>= 1;
//
// Hierarchical loop on smaller dimension n
//
while (p >= 1) {
unsigned short *py = in;
unsigned short *ey = in + oy * (ny - p2);
int oy1 = oy * p;
int oy2 = oy * p2;
int ox1 = ox * p;
int ox2 = ox * p2;
unsigned short i00, i01, i10, i11;
//
// Y loop
//
for (; py <= ey; py += oy2) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
//
// X loop
//
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
unsigned short *p10 = px + oy1;
unsigned short *p11 = p10 + ox1;
//
// 2D wavelet decoding
//
if (w14) {
wdec14(*px, *p10, i00, i10);
wdec14(*p01, *p11, i01, i11);
wdec14(i00, i01, *px, *p01);
wdec14(i10, i11, *p10, *p11);
} else {
wdec16(*px, *p10, i00, i10);
wdec16(*p01, *p11, i01, i11);
wdec16(i00, i01, *px, *p01);
wdec16(i10, i11, *p10, *p11);
}
}
//
// Decode (1D) odd column (still in Y loop)
//
if (nx & p) {
unsigned short *p10 = px + oy1;
if (w14)
wdec14(*px, *p10, i00, *p10);
else
wdec16(*px, *p10, i00, *p10);
*px = i00;
}
}
//
// Decode (1D) odd line (must loop in X)
//
if (ny & p) {
unsigned short *px = py;
unsigned short *ex = py + ox * (nx - p2);
for (; px <= ex; px += ox2) {
unsigned short *p01 = px + ox1;
if (w14)
wdec14(*px, *p01, i00, *p01);
else
wdec16(*px, *p01, i00, *p01);
*px = i00;
}
}
//
// Next level
//
p2 = p;
p >>= 1;
}
}
//-----------------------------------------------------------------------------
//
// 16-bit Huffman compression and decompression.
//
// The source code in this file is derived from the 8-bit
// Huffman compression and decompression routines written
// by Christian Rouet for his PIZ image file format.
//
//-----------------------------------------------------------------------------
// Adds some modification for tinyexr.
const int HUF_ENCBITS = 16; // literal (value) bit length
const int HUF_DECBITS = 14; // decoding bit size (>= 8)
const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size
const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
const int HUF_DECMASK = HUF_DECSIZE - 1;
struct HufDec { // short code long code
//-------------------------------
int len : 8; // code length 0
int lit : 24; // lit p size
int *p; // 0 lits
};
inline long long hufLength(long long code) { return code & 63; }
inline long long hufCode(long long code) { return code >> 6; }
#if 0
inline void outputBits(int nBits, long long bits, long long &c, int &lc,
char *&out) {
c <<= nBits;
lc += nBits;
c |= bits;
while (lc >= 8)
*out++ = (c >> (lc -= 8));
}
#endif
inline long long getBits(int nBits, long long &c, int &lc, const char *&in) {
while (lc < nBits) {
c = (c << 8) | *(unsigned char *)(in++);
lc += 8;
}
lc -= nBits;
return (c >> lc) & ((1 << nBits) - 1);
}
//
// ENCODING TABLE BUILDING & (UN)PACKING
//
//
// Build a "canonical" Huffman code table:
// - for each (uncompressed) symbol, hcode contains the length
// of the corresponding code (in the compressed data)
// - canonical codes are computed and stored in hcode
// - the rules for constructing canonical codes are as follows:
// * shorter codes (if filled with zeroes to the right)
// have a numerically higher value than longer codes
// * for codes with the same length, numerical values
// increase with numerical symbol values
// - because the canonical code table can be constructed from
// symbol lengths alone, the code table can be transmitted
// without sending the actual code values
// - see http://www.compressconsult.com/huffman/
//
void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) {
long long n[59];
//
// For each i from 0 through 58, count the
// number of different codes of length i, and
// store the count in n[i].
//
for (int i = 0; i <= 58; ++i)
n[i] = 0;
for (int i = 0; i < HUF_ENCSIZE; ++i)
n[hcode[i]] += 1;
//
// For each i from 58 through 1, compute the
// numerically lowest code with length i, and
// store that code in n[i].
//
long long c = 0;
for (int i = 58; i > 0; --i) {
long long nc = ((c + n[i]) >> 1);
n[i] = c;
c = nc;
}
//
// hcode[i] contains the length, l, of the
// code for symbol i. Assign the next available
// code of length l to the symbol and store both
// l and the code in hcode[i].
//
for (int i = 0; i < HUF_ENCSIZE; ++i) {
int l = hcode[i];
if (l > 0)
hcode[i] = l | (n[l]++ << 6);
}
}
//
// Compute Huffman codes (based on frq input) and store them in frq:
// - code structure is : [63:lsb - 6:msb] | [5-0: bit length];
// - max code length is 58 bits;
// - codes outside the range [im-iM] have a null length (unused values);
// - original frequencies are destroyed;
// - encoding tables are used by hufEncode() and hufBuildDecTable();
//
#if 0 // @todo
struct FHeapCompare {
bool operator()(long long *a, long long *b) { return *a > *b; }
};
void hufBuildEncTable(
long long *frq, // io: input frequencies [HUF_ENCSIZE], output table
int *im, // o: min frq index
int *iM) // o: max frq index
{
//
// This function assumes that when it is called, array frq
// indicates the frequency of all possible symbols in the data
// that are to be Huffman-encoded. (frq[i] contains the number
// of occurrences of symbol i in the data.)
//
// The loop below does three things:
//
// 1) Finds the minimum and maximum indices that point
// to non-zero entries in frq:
//
// frq[im] != 0, and frq[i] == 0 for all i < im
// frq[iM] != 0, and frq[i] == 0 for all i > iM
//
// 2) Fills array fHeap with pointers to all non-zero
// entries in frq.
//
// 3) Initializes array hlink such that hlink[i] == i
// for all array entries.
//
int hlink[HUF_ENCSIZE];
long long *fHeap[HUF_ENCSIZE];
*im = 0;
while (!frq[*im])
(*im)++;
int nf = 0;
for (int i = *im; i < HUF_ENCSIZE; i++) {
hlink[i] = i;
if (frq[i]) {
fHeap[nf] = &frq[i];
nf++;
*iM = i;
}
}
//
// Add a pseudo-symbol, with a frequency count of 1, to frq;
// adjust the fHeap and hlink array accordingly. Function
// hufEncode() uses the pseudo-symbol for run-length encoding.
//
(*iM)++;
frq[*iM] = 1;
fHeap[nf] = &frq[*iM];
nf++;
//
// Build an array, scode, such that scode[i] contains the number
// of bits assigned to symbol i. Conceptually this is done by
// constructing a tree whose leaves are the symbols with non-zero
// frequency:
//
// Make a heap that contains all symbols with a non-zero frequency,
// with the least frequent symbol on top.
//
// Repeat until only one symbol is left on the heap:
//
// Take the two least frequent symbols off the top of the heap.
// Create a new node that has first two nodes as children, and
// whose frequency is the sum of the frequencies of the first
// two nodes. Put the new node back into the heap.
//
// The last node left on the heap is the root of the tree. For each
// leaf node, the distance between the root and the leaf is the length
// of the code for the corresponding symbol.
//
// The loop below doesn't actually build the tree; instead we compute
// the distances of the leaves from the root on the fly. When a new
// node is added to the heap, then that node's descendants are linked
// into a single linear list that starts at the new node, and the code
// lengths of the descendants (that is, their distance from the root
// of the tree) are incremented by one.
//
std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
long long scode[HUF_ENCSIZE];
memset(scode, 0, sizeof(long long) * HUF_ENCSIZE);
while (nf > 1) {
//
// Find the indices, mm and m, of the two smallest non-zero frq
// values in fHeap, add the smallest frq to the second-smallest
// frq, and remove the smallest frq value from fHeap.
//
int mm = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
--nf;
int m = fHeap[0] - frq;
std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
frq[m] += frq[mm];
std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare());
//
// The entries in scode are linked into lists with the
// entries in hlink serving as "next" pointers and with
// the end of a list marked by hlink[j] == j.
//
// Traverse the lists that start at scode[m] and scode[mm].
// For each element visited, increment the length of the
// corresponding code by one bit. (If we visit scode[j]
// during the traversal, then the code for symbol j becomes
// one bit longer.)
//
// Merge the lists that start at scode[m] and scode[mm]
// into a single list that starts at scode[m].
//
//
// Add a bit to all codes in the first list.
//
for (int j = m; true; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j) {
//
// Merge the two lists.
//
hlink[j] = mm;
break;
}
}
//
// Add a bit to all codes in the second list
//
for (int j = mm; true; j = hlink[j]) {
scode[j]++;
assert(scode[j] <= 58);
if (hlink[j] == j)
break;
}
}
//
// Build a canonical Huffman code table, replacing the code
// lengths in scode with (code, code length) pairs. Copy the
// code table from scode into frq.
//
hufCanonicalCodeTable(scode);
memcpy(frq, scode, sizeof(long long) * HUF_ENCSIZE);
}
#endif
//
// Pack an encoding table:
// - only code lengths, not actual codes, are stored
// - runs of zeroes are compressed as follows:
//
// unpacked packed
// --------------------------------
// 1 zero 0 (6 bits)
// 2 zeroes 59
// 3 zeroes 60
// 4 zeroes 61
// 5 zeroes 62
// n zeroes (6 or more) 63 n-6 (6 + 8 bits)
//
const int SHORT_ZEROCODE_RUN = 59;
const int LONG_ZEROCODE_RUN = 63;
const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
// const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN;
#if 0
void hufPackEncTable(const long long *hcode, // i : encoding table [HUF_ENCSIZE]
int im, // i : min hcode index
int iM, // i : max hcode index
char **pcode) // o: ptr to packed table (updated)
{
char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
int l = hufLength(hcode[im]);
if (l == 0) {
int zerun = 1;
while ((im < iM) && (zerun < LONGEST_LONG_RUN)) {
if (hufLength(hcode[im + 1]) > 0)
break;
im++;
zerun++;
}
if (zerun >= 2) {
if (zerun >= SHORTEST_LONG_RUN) {
outputBits(6, LONG_ZEROCODE_RUN, c, lc, p);
outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p);
} else {
outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p);
}
continue;
}
}
outputBits(6, l, c, lc, p);
}
if (lc > 0)
*p++ = (unsigned char)(c << (8 - lc));
*pcode = p;
}
#endif
//
// Unpack an encoding table packed by hufPackEncTable():
//
bool hufUnpackEncTable(const char **pcode, // io: ptr to packed table (updated)
int ni, // i : input size (in bytes)
int im, // i : min hcode index
int iM, // i : max hcode index
long long *hcode) // o: encoding table [HUF_ENCSIZE]
{
memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE);
const char *p = *pcode;
long long c = 0;
int lc = 0;
for (; im <= iM; im++) {
if (p - *pcode > ni) {
return false;
}
long long l = hcode[im] = getBits(6, c, lc, p); // code length
if (l == (long long)LONG_ZEROCODE_RUN) {
if (p - *pcode > ni) {
return false;
}
int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--)
hcode[im++] = 0;
im--;
} else if (l >= (long long)SHORT_ZEROCODE_RUN) {
int zerun = l - SHORT_ZEROCODE_RUN + 2;
if (im + zerun > iM + 1) {
return false;
}
while (zerun--)
hcode[im++] = 0;
im--;
}
}
*pcode = const_cast<char *>(p);
hufCanonicalCodeTable(hcode);
return true;
}
//
// DECODING TABLE BUILDING
//
//
// Clear a newly allocated decoding table so that it contains only zeroes.
//
void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
for (int i = 0; i < HUF_DECSIZE; i++) {
hdecod[i].len = 0;
hdecod[i].lit = 0;
hdecod[i].p = NULL;
}
// memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE);
}
//
// Build a decoding hash table based on the encoding table hcode:
// - short codes (<= HUF_DECBITS) are resolved with a single table access;
// - long code entry allocations are not optimized, because long codes are
// unfrequent;
// - decoding tables are used by hufDecode();
//
bool hufBuildDecTable(const long long *hcode, // i : encoding table
int im, // i : min index in hcode
int iM, // i : max index in hcode
HufDec *hdecod) // o: (allocated by caller)
// decoding table [HUF_DECSIZE]
{
//
// Init hashtable & loop on all codes.
// Assumes that hufClearDecTable(hdecod) has already been called.
//
for (; im <= iM; im++) {
long long c = hufCode(hcode[im]);
int l = hufLength(hcode[im]);
if (c >> l) {
//
// Error: c is supposed to be an l-bit code,
// but c contains a value that is greater
// than the largest l-bit number.
//
// invalidTableEntry();
return false;
}
if (l > HUF_DECBITS) {
//
// Long code: add a secondary entry
//
HufDec *pl = hdecod + (c >> (l - HUF_DECBITS));
if (pl->len) {
//
// Error: a short code has already
// been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->lit++;
if (pl->p) {
int *p = pl->p;
pl->p = new int[pl->lit];
for (int i = 0; i < pl->lit - 1; ++i)
pl->p[i] = p[i];
delete[] p;
} else {
pl->p = new int[1];
}
pl->p[pl->lit - 1] = im;
} else if (l) {
//
// Short code: init all primary entries
//
HufDec *pl = hdecod + (c << (HUF_DECBITS - l));
for (long long i = 1 << (HUF_DECBITS - l); i > 0; i--, pl++) {
if (pl->len || pl->p) {
//
// Error: a short code or a long code has
// already been stored in table entry *pl.
//
// invalidTableEntry();
return false;
}
pl->len = l;
pl->lit = im;
}
}
}
return true;
}
//
// Free the long code entries of a decoding table built by hufBuildDecTable()
//
void hufFreeDecTable(HufDec *hdecod) // io: Decoding table
{
for (int i = 0; i < HUF_DECSIZE; i++) {
if (hdecod[i].p) {
delete[] hdecod[i].p;
hdecod[i].p = 0;
}
}
}
//
// ENCODING
//
#if 0 // @todo
inline void outputCode(long long code, long long &c, int &lc, char *&out) {
outputBits(hufLength(code), hufCode(code), c, lc, out);
}
inline void sendCode(long long sCode, int runCount, long long runCode,
long long &c, int &lc, char *&out) {
//
// Output a run of runCount instances of the symbol sCount.
// Output the symbols explicitly, or if that is shorter, output
// the sCode symbol once followed by a runCode symbol and runCount
// expressed as an 8-bit number.
//
if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) {
outputCode(sCode, c, lc, out);
outputCode(runCode, c, lc, out);
outputBits(8, runCount, c, lc, out);
} else {
while (runCount-- >= 0)
outputCode(sCode, c, lc, out);
}
}
//
// Encode (compress) ni values based on the Huffman encoding table hcode:
//
int hufEncode // return: output size (in bits)
(const long long *hcode, // i : encoding table
const unsigned short *in, // i : uncompressed input buffer
const int ni, // i : input buffer size (in bytes)
int rlc, // i : rl code
char *out) // o: compressed output buffer
{
char *outStart = out;
long long c = 0; // bits not yet written to out
int lc = 0; // number of valid bits in c (LSB)
int s = in[0];
int cs = 0;
//
// Loop on input values
//
for (int i = 1; i < ni; i++) {
//
// Count same values or send code
//
if (s == in[i] && cs < 255) {
cs++;
} else {
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
cs = 0;
}
s = in[i];
}
//
// Send remaining code
//
sendCode(hcode[s], cs, hcode[rlc], c, lc, out);
if (lc)
*out = (c << (8 - lc)) & 0xff;
return (out - outStart) * 8 + lc;
}
#endif
//
// DECODING
//
//
// In order to force the compiler to inline them,
// getChar() and getCode() are implemented as macros
// instead of "inline" functions.
//
#define getChar(c, lc, in) \
{ \
c = (c << 8) | *(unsigned char *)(in++); \
lc += 8; \
}
#define getCode(po, rlc, c, lc, in, out, oe) \
{ \
if (po == rlc) { \
if (lc < 8) \
getChar(c, lc, in); \
\
lc -= 8; \
\
unsigned char cs = (c >> lc); \
\
if (out + cs > oe) \
return false; \
\
unsigned short s = out[-1]; \
\
while (cs-- > 0) \
*out++ = s; \
} else if (out < oe) { \
*out++ = po; \
} else { \
return false; \
} \
}
//
// Decode (uncompress) ni bits based on encoding & decoding tables:
//
bool hufDecode(const long long *hcode, // i : encoding table
const HufDec *hdecod, // i : decoding table
const char *in, // i : compressed input buffer
int ni, // i : input size (in bits)
int rlc, // i : run-length code
int no, // i : expected output size (in bytes)
unsigned short *out) // o: uncompressed output buffer
{
long long c = 0;
int lc = 0;
unsigned short *outb = out;
unsigned short *oe = out + no;
const char *ie = in + (ni + 7) / 8; // input byte size
//
// Loop on input bytes
//
while (in < ie) {
getChar(c, lc, in);
//
// Access decoding table
//
while (lc >= HUF_DECBITS) {
const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK];
if (pl.len) {
//
// Get short code
//
lc -= pl.len;
getCode(pl.lit, rlc, c, lc, in, out, oe);
} else {
if (!pl.p) {
return false;
}
// invalidCode(); // wrong code
//
// Search long code
//
int j;
for (j = 0; j < pl.lit; j++) {
int l = hufLength(hcode[pl.p[j]]);
while (lc < l && in < ie) // get more bits
getChar(c, lc, in);
if (lc >= l) {
if (hufCode(hcode[pl.p[j]]) ==
((c >> (lc - l)) & (((long long)(1) << l) - 1))) {
//
// Found : get long code
//
lc -= l;
getCode(pl.p[j], rlc, c, lc, in, out, oe);
break;
}
}
}
if (j == pl.lit) {
return false;
// invalidCode(); // Not found
}
}
}
}
//
// Get remaining (short) codes
//
int i = (8 - ni) & 7;
c >>= i;
lc -= i;
while (lc > 0) {
const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK];
if (pl.len) {
lc -= pl.len;
getCode(pl.lit, rlc, c, lc, in, out, oe);
} else {
return false;
// invalidCode(); // wrong (long) code
}
}
if (out - outb != no) {
return false;
}
// notEnoughData ();
return true;
}
#if 0 // @todo
void countFrequencies(long long freq[HUF_ENCSIZE],
const unsigned short data[/*n*/], int n) {
for (int i = 0; i < HUF_ENCSIZE; ++i)
freq[i] = 0;
for (int i = 0; i < n; ++i)
++freq[data[i]];
}
void writeUInt(char buf[4], unsigned int i) {
unsigned char *b = (unsigned char *)buf;
b[0] = i;
b[1] = i >> 8;
b[2] = i >> 16;
b[3] = i >> 24;
}
#endif
unsigned int readUInt(const char buf[4]) {
const unsigned char *b = (const unsigned char *)buf;
return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) |
((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000);
}
//
// EXTERNAL INTERFACE
//
#if 0 // @todo
int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) {
if (nRaw == 0)
return 0;
long long freq[HUF_ENCSIZE];
countFrequencies(freq, raw, nRaw);
int im = 0;
int iM = 0;
hufBuildEncTable(freq, &im, &iM);
char *tableStart = compressed + 20;
char *tableEnd = tableStart;
hufPackEncTable(freq, im, iM, &tableEnd);
int tableLength = tableEnd - tableStart;
char *dataStart = tableEnd;
int nBits = hufEncode(freq, raw, nRaw, iM, dataStart);
int dataLength = (nBits + 7) / 8;
writeUInt(compressed, im);
writeUInt(compressed + 4, iM);
writeUInt(compressed + 8, tableLength);
writeUInt(compressed + 12, nBits);
writeUInt(compressed + 16, 0); // room for future extensions
return dataStart + dataLength - compressed;
}
#endif
bool hufUncompress(const char compressed[], int nCompressed,
unsigned short raw[], int nRaw) {
if (nCompressed == 0) {
if (nRaw != 0)
return false;
return false;
}
int im = readUInt(compressed);
int iM = readUInt(compressed + 4);
// int tableLength = readUInt (compressed + 8);
int nBits = readUInt(compressed + 12);
if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE)
return false;
const char *ptr = compressed + 20;
//
// Fast decoder needs at least 2x64-bits of compressed data, and
// needs to be run-able on this platform. Otherwise, fall back
// to the original decoder
//
// if (FastHufDecoder::enabled() && nBits > 128)
//{
// FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM);
// fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw);
//}
// else
{
std::vector<long long> freq(HUF_ENCSIZE);
std::vector<HufDec> hdec(HUF_DECSIZE);
hufClearDecTable(&hdec.at(0));
hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM,
&freq.at(0));
{
if (nBits > 8 * (nCompressed - (ptr - compressed))) {
return false;
}
hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0));
hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, nRaw, raw);
}
// catch (...)
//{
// hufFreeDecTable (hdec);
// throw;
//}
hufFreeDecTable(&hdec.at(0));
}
return true;
}
//
// Functions to compress the range of values in the pixel data
//
const int USHORT_RANGE = (1 << 16);
const int BITMAP_SIZE = (USHORT_RANGE >> 3);
#if 0 // @todo
void bitmapFromData(const unsigned short data[/*nData*/], int nData,
unsigned char bitmap[BITMAP_SIZE],
unsigned short &minNonZero, unsigned short &maxNonZero) {
for (int i = 0; i < BITMAP_SIZE; ++i)
bitmap[i] = 0;
for (int i = 0; i < nData; ++i)
bitmap[data[i] >> 3] |= (1 << (data[i] & 7));
bitmap[0] &= ~1; // zero is not explicitly stored in
// the bitmap; we assume that the
// data always contain zeroes
minNonZero = BITMAP_SIZE - 1;
maxNonZero = 0;
for (int i = 0; i < BITMAP_SIZE; ++i) {
if (bitmap[i]) {
if (minNonZero > i)
minNonZero = i;
if (maxNonZero < i)
maxNonZero = i;
}
}
}
unsigned short forwardLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[i] = k++;
else
lut[i] = 0;
}
return k - 1; // maximum value stored in lut[],
} // i.e. number of ones in bitmap minus 1
#endif
unsigned short reverseLutFromBitmap(const unsigned char bitmap[BITMAP_SIZE],
unsigned short lut[USHORT_RANGE]) {
int k = 0;
for (int i = 0; i < USHORT_RANGE; ++i) {
if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7))))
lut[k++] = i;
}
int n = k - 1;
while (k < USHORT_RANGE)
lut[k++] = 0;
return n; // maximum k where lut[k] is non-zero,
} // i.e. number of ones in bitmap minus 1
void applyLut(const unsigned short lut[USHORT_RANGE],
unsigned short data[/*nData*/], int nData) {
for (int i = 0; i < nData; ++i)
data[i] = lut[data[i]];
}
#if 0 // @todo
bool CompressPiz(unsigned char *outPtr, unsigned int &outSize) {
unsigned char bitmap[BITMAP_SIZE];
unsigned short minNonZero;
unsigned short maxNonZero;
if (IsBigEndian()) {
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
}
std::vector<unsigned short> tmpBuffer;
int nData = tmpBuffer.size();
bitmapFromData(&tmpBuffer.at(0), nData, bitmap, minNonZero, maxNonZero);
unsigned short lut[USHORT_RANGE];
//unsigned short maxValue = forwardLutFromBitmap(bitmap, lut);
applyLut(lut, &tmpBuffer.at(0), nData);
//
// Store range compression info in _outBuffer
//
char *buf = reinterpret_cast<char *>(outPtr);
memcpy(buf, &minNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
memcpy(buf, &maxNonZero, sizeof(unsigned short));
buf += sizeof(unsigned short);
if (minNonZero <= maxNonZero) {
memcpy(buf, (char *)&bitmap[0] + minNonZero, maxNonZero - minNonZero + 1);
buf += maxNonZero - minNonZero + 1;
}
#if 0 // @todo
//
// Apply wavelet encoding
//
for (int i = 0; i < channels; ++i)
{
ChannelData &cd = _channelData[i];
for (int j = 0; j < cd.size; ++j)
{
wav2Encode (cd.start + j,
cd.nx, cd.size,
cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Apply Huffman encoding; append the result to _outBuffer
//
char *lengthPtr = buf;
int zero = 0;
memcpy(buf, &zero, sizeof(int)); buf += sizeof(int);
int length = hufCompress (_tmpBuffer, tmpBufferEnd - _tmpBuffer, buf);
memcpy(lengthPtr, tmpBuffer, length);
//Xdr::write <CharPtrIO> (lengthPtr, length);
outPtr = _outBuffer;
return buf - _outBuffer + length;
#endif
assert(0);
return true;
}
#endif
bool DecompressPiz(unsigned char *outPtr, unsigned int &,
const unsigned char *inPtr, size_t tmpBufSize,
const std::vector<ChannelInfo> &channelInfo, int dataWidth,
int numLines) {
unsigned char bitmap[BITMAP_SIZE];
unsigned short minNonZero;
unsigned short maxNonZero;
if (IsBigEndian()) {
// @todo { PIZ compression on BigEndian architecture. }
assert(0);
return false;
}
memset(bitmap, 0, BITMAP_SIZE);
const unsigned char *ptr = inPtr;
minNonZero = *(reinterpret_cast<const unsigned short *>(ptr));
maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2));
ptr += 4;
if (maxNonZero >= BITMAP_SIZE) {
return false;
}
if (minNonZero <= maxNonZero) {
memcpy((char *)&bitmap[0] + minNonZero, ptr, maxNonZero - minNonZero + 1);
ptr += maxNonZero - minNonZero + 1;
}
unsigned short lut[USHORT_RANGE];
memset(lut, 0, sizeof(unsigned short) * USHORT_RANGE);
unsigned short maxValue = reverseLutFromBitmap(bitmap, lut);
//
// Huffman decoding
//
int length;
length = *(reinterpret_cast<const int *>(ptr));
ptr += sizeof(int);
std::vector<unsigned short> tmpBuffer(tmpBufSize);
hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer.at(0),
tmpBufSize);
//
// Wavelet decoding
//
std::vector<PIZChannelData> channelData(channelInfo.size());
unsigned short *tmpBufferEnd = &tmpBuffer.at(0);
for (size_t i = 0; i < channelInfo.size(); ++i) {
const ChannelInfo &chan = channelInfo[i];
int pixelSize = sizeof(int); // UINT and FLOAT
if (chan.pixelType == TINYEXR_PIXELTYPE_HALF) {
pixelSize = sizeof(short);
}
channelData[i].start = tmpBufferEnd;
channelData[i].end = channelData[i].start;
channelData[i].nx = dataWidth;
channelData[i].ny = numLines;
// channelData[i].ys = 1;
channelData[i].size = pixelSize / sizeof(short);
tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size;
}
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
for (int j = 0; j < cd.size; ++j) {
wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size,
maxValue);
}
}
//
// Expand the pixel data to their original range
//
applyLut(lut, &tmpBuffer.at(0), tmpBufSize);
// @todo { Xdr }
for (int y = 0; y < numLines; y++) {
for (size_t i = 0; i < channelData.size(); ++i) {
PIZChannelData &cd = channelData[i];
// if (modp (y, cd.ys) != 0)
// continue;
int n = cd.nx * cd.size;
memcpy(outPtr, cd.end, n * sizeof(unsigned short));
outPtr += n * sizeof(unsigned short);
cd.end += n;
}
}
return true;
}
//
// -----------------------------------------------------------------
//
} // namespace
int LoadEXR(float **out_rgba, int *width, int *height, const char *filename,
const char **err) {
if (out_rgba == NULL) {
if (err) {
(*err) = "Invalid argument.\n";
}
return -1;
}
EXRImage exrImage;
InitEXRImage(&exrImage);
{
int ret = ParseMultiChannelEXRHeaderFromFile(&exrImage, filename, err);
if (ret != 0) {
return ret;
}
}
// Read HALF channel as FLOAT.
for (int i = 0; i < exrImage.num_channels; i++) {
if (exrImage.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) {
exrImage.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
}
}
{
int ret = LoadMultiChannelEXRFromFile(&exrImage, filename, err);
if (ret != 0) {
return ret;
}
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
for (int c = 0; c < exrImage.num_channels; c++) {
if (strcmp(exrImage.channel_names[c], "R") == 0) {
idxR = c;
} else if (strcmp(exrImage.channel_names[c], "G") == 0) {
idxG = c;
} else if (strcmp(exrImage.channel_names[c], "B") == 0) {
idxB = c;
} else if (strcmp(exrImage.channel_names[c], "A") == 0) {
idxA = c;
}
}
if (idxR == -1) {
if (err) {
(*err) = "R channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxG == -1) {
if (err) {
(*err) = "G channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxB == -1) {
if (err) {
(*err) = "B channel not found\n";
}
// @todo { free exrImage }
return -1;
}
(*out_rgba) =
(float *)malloc(4 * sizeof(float) * exrImage.width * exrImage.height);
for (int i = 0; i < exrImage.width * exrImage.height; i++) {
(*out_rgba)[4 * i + 0] =
reinterpret_cast<float **>(exrImage.images)[idxR][i];
(*out_rgba)[4 * i + 1] =
reinterpret_cast<float **>(exrImage.images)[idxG][i];
(*out_rgba)[4 * i + 2] =
reinterpret_cast<float **>(exrImage.images)[idxB][i];
if (idxA > 0) {
(*out_rgba)[4 * i + 3] =
reinterpret_cast<float **>(exrImage.images)[idxA][i];
} else {
(*out_rgba)[4 * i + 3] = 1.0;
}
}
(*width) = exrImage.width;
(*height) = exrImage.height;
// @todo { free exrImage }
return 0;
}
int ParseEXRHeaderFromMemory(EXRAttribute *customAttributes,
int *numCustomAttributes, int *width, int *height,
const unsigned char *memory) {
if (memory == NULL) {
// Invalid argument
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
// if (err) {
// (*err) = "Header mismatch.";
//}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
// if (err) {
// (*err) = "Unsupported version or scanline.";
//}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int lineOrder = 0; // @fixme
int displayWindow[4] = {-1, -1, -1, -1}; // @fixme
float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
float screenWindowWidth = 1.0f; // @fixme
int numChannels = -1;
float pixelAspectRatio = 1.0f; // @fixme
std::vector<ChannelInfo> channels;
std::vector<EXRAttribute> attribs;
if (numCustomAttributes) {
(*numCustomAttributes) = 0;
}
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == TINYEXR_COMPRESSIONTYPE_NONE) {
// mwkm
// 0 : NO_COMPRESSION
// 1 : RLE
// 2 : ZIPS (Single scanline)
// 3 : ZIP (16-line block)
// 4 : PIZ (32-line block)
if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
// if (err) {
// (*err) = "Unsupported compression type.";
//}
return -5;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
// if (err) {
// (*err) = "Invalid channels format.";
//}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
memcpy(&displayWindow[0], &data.at(0), sizeof(int));
memcpy(&displayWindow[1], &data.at(4), sizeof(int));
memcpy(&displayWindow[2], &data.at(8), sizeof(int));
memcpy(&displayWindow[3], &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
}
} else if (attrName.compare("lineOrder") == 0) {
memcpy(&lineOrder, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineOrder));
}
} else if (attrName.compare("pixelAspectRatio") == 0) {
memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
}
} else if (attrName.compare("screenWindowCenter") == 0) {
memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
}
} else if (attrName.compare("screenWindowWidth") == 0) {
memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
}
} else {
// Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
if (numCustomAttributes &&
((*numCustomAttributes) < TINYEXR_MAX_ATTRIBUTES)) {
EXRAttribute attrib;
attrib.name = strdup(attrName.c_str());
attrib.type = strdup(attrType.c_str());
attrib.size = data.size();
attrib.value = (unsigned char *)malloc(data.size());
memcpy((char *)attrib.value, &data.at(0), data.size());
attribs.push_back(attrib);
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
(*width) = dataWidth;
(*height) = dataHeight;
if (numCustomAttributes) {
assert(attribs.size() < TINYEXR_MAX_ATTRIBUTES);
(*numCustomAttributes) = attribs.size();
// Assume the pointer to customAttributes has enough memory to store.
for (int i = 0; i < (int)attribs.size(); i++) {
customAttributes[i] = attribs[i];
}
}
return 0;
}
int LoadEXRFromMemory(float *out_rgba, const unsigned char *memory,
const char **err) {
if (out_rgba == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.\n";
}
return -1;
}
EXRImage exrImage;
InitEXRImage(&exrImage);
int ret = LoadMultiChannelEXRFromMemory(&exrImage, memory, err);
if (ret != 0) {
return ret;
}
// RGBA
int idxR = -1;
int idxG = -1;
int idxB = -1;
int idxA = -1;
for (int c = 0; c < exrImage.num_channels; c++) {
if (strcmp(exrImage.channel_names[c], "R") == 0) {
idxR = c;
} else if (strcmp(exrImage.channel_names[c], "G") == 0) {
idxG = c;
} else if (strcmp(exrImage.channel_names[c], "B") == 0) {
idxB = c;
} else if (strcmp(exrImage.channel_names[c], "A") == 0) {
idxA = c;
}
}
if (idxR == -1) {
if (err) {
(*err) = "R channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxG == -1) {
if (err) {
(*err) = "G channel not found\n";
}
// @todo { free exrImage }
return -1;
}
if (idxB == -1) {
if (err) {
(*err) = "B channel not found\n";
}
// @todo { free exrImage }
return -1;
}
// Assume `out_rgba` have enough memory allocated.
for (int i = 0; i < exrImage.width * exrImage.height; i++) {
out_rgba[4 * i + 0] = reinterpret_cast<float **>(exrImage.images)[idxR][i];
out_rgba[4 * i + 1] = reinterpret_cast<float **>(exrImage.images)[idxG][i];
out_rgba[4 * i + 2] = reinterpret_cast<float **>(exrImage.images)[idxB][i];
if (idxA > 0) {
out_rgba[4 * i + 3] =
reinterpret_cast<float **>(exrImage.images)[idxA][i];
} else {
out_rgba[4 * i + 3] = 1.0;
}
}
return 0;
}
int LoadMultiChannelEXRFromFile(EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return LoadMultiChannelEXRFromMemory(exrImage, &buf.at(0), err);
}
int LoadMultiChannelEXRFromMemory(EXRImage *exrImage,
const unsigned char *memory,
const char **err) {
if (exrImage == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *head = &buf[0];
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numScanlineBlocks = 1; // 16 for ZIP compression.
int compressionType = -1;
int numChannels = -1;
unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
std::vector<ChannelInfo> channels;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// mwkm
// 0 : NO_COMPRESSION
// 1 : RLE
// 2 : ZIPS (Single scanline)
// 3 : ZIP (16-line block)
// 4 : PIZ (32-line block)
if (data[0] != TINYEXR_COMPRESSIONTYPE_NONE &&
data[0] != TINYEXR_COMPRESSIONTYPE_ZIPS &&
data[0] != TINYEXR_COMPRESSIONTYPE_ZIP &&
data[0] != TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
if (compressionType == TINYEXR_COMPRESSIONTYPE_ZIP) {
numScanlineBlocks = 16;
} else if (compressionType == TINYEXR_COMPRESSIONTYPE_PIZ) {
numScanlineBlocks = 32;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
int x, y, w, h;
memcpy(&x, &data.at(0), sizeof(int));
memcpy(&y, &data.at(4), sizeof(int));
memcpy(&w, &data.at(8), sizeof(int));
memcpy(&h, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&x));
swap4(reinterpret_cast<unsigned int *>(&y));
swap4(reinterpret_cast<unsigned int *>(&w));
swap4(reinterpret_cast<unsigned int *>(&h));
}
} else if (attrName.compare("lineOrder") == 0) {
memcpy(&lineOrder, &data.at(0), sizeof(lineOrder));
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
// Read offset tables.
int numBlocks = dataHeight / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < dataHeight) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
for (int y = 0; y < numBlocks; y++) {
long long offset;
memcpy(&offset, marker, sizeof(long long));
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offset));
}
marker += sizeof(long long); // = 8
offsets[y] = offset;
}
exrImage->images = reinterpret_cast<unsigned char **>(
(float **)malloc(sizeof(float *) * numChannels));
std::vector<size_t> channelOffsetList(numChannels);
int pixelDataSize = 0;
size_t channelOffset = 0;
for (int c = 0; c < numChannels; c++) {
channelOffsetList[c] = channelOffset;
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
pixelDataSize += sizeof(unsigned short);
channelOffset += sizeof(unsigned short);
// Alloc internal image for half type.
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
exrImage->images[c] =
reinterpret_cast<unsigned char *>((unsigned short *)malloc(
sizeof(unsigned short) * dataWidth * dataHeight));
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
exrImage->images[c] = reinterpret_cast<unsigned char *>(
(float *)malloc(sizeof(float) * dataWidth * dataHeight));
} else {
assert(0);
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
pixelDataSize += sizeof(float);
channelOffset += sizeof(float);
exrImage->images[c] = reinterpret_cast<unsigned char *>(
(float *)malloc(sizeof(float) * dataWidth * dataHeight));
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
pixelDataSize += sizeof(unsigned int);
channelOffset += sizeof(unsigned int);
exrImage->images[c] = reinterpret_cast<unsigned char *>((
unsigned int *)malloc(sizeof(unsigned int) * dataWidth * dataHeight));
} else {
assert(0);
}
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed or compressed)
int lineNo;
memcpy(&lineNo, dataPtr, sizeof(int));
int dataLen;
memcpy(&dataLen, dataPtr + 4, sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineNo));
swap4(reinterpret_cast<unsigned int *>(&dataLen));
}
int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
int numLines = endLineNo - lineNo;
if (compressionType == 4) { // PIZ
// Allocate original data size.
std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
unsigned int dstLen;
size_t tmpBufLen = dataWidth * numLines * pixelDataSize;
DecompressPiz(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen,
dataPtr + 8, tmpBufLen, channels, dataWidth, numLines);
bool isBigEndian = IsBigEndian();
// For ZIP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
for (int v = 0; v < numLines; v++) {
const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = hf.u;
} else { // HALF -> FLOAT
FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = f32.f;
}
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (int v = 0; v < numLines; v++) {
const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(&val);
}
unsigned int *image =
reinterpret_cast<unsigned int **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (int v = 0; v < numLines; v++) {
const float *linePtr = reinterpret_cast<float *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else {
assert(0);
}
}
// mwkm, ZIPS or ZIP both good to go
} else if (compressionType == 2 || compressionType == 3) { // ZIP
// Allocate original data size.
std::vector<unsigned char> outBuf(dataWidth * numLines * pixelDataSize);
unsigned long dstLen = outBuf.size();
DecompressZip(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen,
dataPtr + 8, dataLen);
bool isBigEndian = IsBigEndian();
// For ZIP_COMPRESSION:
// pixel sample data for channel 0 for scanline 0
// pixel sample data for channel 1 for scanline 0
// pixel sample data for channel ... for scanline 0
// pixel sample data for channel n for scanline 0
// pixel sample data for channel 0 for scanline 1
// pixel sample data for channel 1 for scanline 1
// pixel sample data for channel ... for scanline 1
// pixel sample data for channel n for scanline 1
// ...
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
for (int v = 0; v < numLines; v++) {
const unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
unsigned short *image =
reinterpret_cast<unsigned short **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = hf.u;
} else { // HALF -> FLOAT
FP32 f32 = half_to_float(hf);
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = f32.f;
}
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT);
for (int v = 0; v < numLines; v++) {
const unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(&val);
}
unsigned int *image =
reinterpret_cast<unsigned int **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
assert(exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT);
for (int v = 0; v < numLines; v++) {
const float *linePtr = reinterpret_cast<float *>(
&outBuf.at(v * pixelDataSize * dataWidth +
channelOffsetList[c] * dataWidth));
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
float *image = reinterpret_cast<float **>(exrImage->images)[c];
if (lineOrder == 0) {
image += (lineNo + v) * dataWidth + u;
} else {
image += (dataHeight - 1 - (lineNo + v)) * dataWidth + u;
}
*image = val;
}
}
} else {
assert(0);
}
}
} else if (compressionType == 0) { // No compression
bool isBigEndian = IsBigEndian();
for (int c = 0; c < numChannels; c++) {
if (channels[c].pixelType == TINYEXR_PIXELTYPE_HALF) {
const unsigned short *linePtr =
reinterpret_cast<const unsigned short *>(
dataPtr + 8 + c * dataWidth * sizeof(unsigned short));
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
unsigned short *outLine =
reinterpret_cast<unsigned short *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
outLine[u] = hf.u;
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
FP16 hf;
hf.u = linePtr[u];
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&hf.u));
}
FP32 f32 = half_to_float(hf);
outLine[u] = f32.f;
}
} else {
assert(0);
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_FLOAT) {
const float *linePtr = reinterpret_cast<const float *>(
dataPtr + 8 + c * dataWidth * sizeof(float));
float *outLine = reinterpret_cast<float *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
float val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
outLine[u] = val;
}
} else if (channels[c].pixelType == TINYEXR_PIXELTYPE_UINT) {
const unsigned int *linePtr = reinterpret_cast<const unsigned int *>(
dataPtr + 8 + c * dataWidth * sizeof(unsigned int));
unsigned int *outLine =
reinterpret_cast<unsigned int *>(exrImage->images[c]);
if (lineOrder == 0) {
outLine += y * dataWidth;
} else {
outLine += (dataHeight - 1 - y) * dataWidth;
}
for (int u = 0; u < dataWidth; u++) {
unsigned int val = linePtr[u];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
outLine[u] = val;
}
}
}
}
} // omp parallel
{
exrImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
exrImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
exrImage->num_channels = numChannels;
exrImage->width = dataWidth;
exrImage->height = dataHeight;
// Fill with requested_pixel_types.
exrImage->pixel_types = (int *)malloc(sizeof(int *) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->pixel_types[c] = exrImage->requested_pixel_types[c];
}
}
return 0; // OK
}
// @deprecated
#if 0
int SaveEXR(const float *in_rgba, int width, int height, const char *filename,
const char **err) {
if (in_rgba == NULL || filename == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "wb");
if (!fp) {
if (err) {
(*err) = "Cannot write a file.";
}
return -1;
}
// Header
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
size_t n = fwrite(header, 1, 4, fp);
assert(n == 4);
}
// Version, scanline.
{
const char marker[] = {2, 0, 0, 0};
size_t n = fwrite(marker, 1, 4, fp);
assert(n == 4);
}
int numScanlineBlocks = 16; // 16 for ZIP compression.
// Write attributes.
{
unsigned char data[] = {
'A', 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'B',
0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'G', 0,
1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 'R', 0, 1,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0}; // last 0 =
// terminator.
WriteAttribute(fp, "channels", "chlist", data, 18 * 4 + 1); // +1 = null
}
{
int compressionType = 3; // ZIP compression
WriteAttribute(fp, "compression", "compression",
reinterpret_cast<const unsigned char *>(&compressionType),
1);
}
{
int data[4] = {0, 0, width - 1, height - 1};
WriteAttribute(fp, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttribute(fp, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
{
unsigned char lineOrder = 0; // increasingY
WriteAttribute(fp, "lineOrder", "lineOrder", &lineOrder, 1);
}
{
float aspectRatio = 1.0f;
WriteAttribute(fp, "pixelAspectRatio", "float",
reinterpret_cast<const unsigned char *>(&aspectRatio),
sizeof(float));
}
{
float center[2] = {0.0f, 0.0f};
WriteAttribute(fp, "screenWindowCenter", "v2f",
reinterpret_cast<const unsigned char *>(center),
2 * sizeof(float));
}
{
float w = (float)width;
WriteAttribute(fp, "screenWindowWidth", "float",
reinterpret_cast<const unsigned char *>(&w), sizeof(float));
}
{ // end of header
unsigned char e = 0;
fwrite(&e, 1, 1, fp);
}
int numBlocks = height / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < height) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
size_t headerSize = ftell(fp); // sizeof(header)
long long offset =
headerSize +
numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
std::vector<unsigned char> data;
for (int i = 0; i < numBlocks; i++) {
int startY = numScanlineBlocks * i;
int endY = (std::min)(numScanlineBlocks * (i + 1), height);
int h = endY - startY;
std::vector<unsigned short> buf(4 * width * h);
for (int y = 0; y < h; y++) {
for (int x = 0; x < width; x++) {
FP32 r, g, b, a;
r.f = in_rgba[4 * ((y + startY) * width + x) + 0];
g.f = in_rgba[4 * ((y + startY) * width + x) + 1];
b.f = in_rgba[4 * ((y + startY) * width + x) + 2];
a.f = in_rgba[4 * ((y + startY) * width + x) + 3];
FP16 hr, hg, hb, ha;
hr = float_to_half_full(r);
hg = float_to_half_full(g);
hb = float_to_half_full(b);
ha = float_to_half_full(a);
// Assume increasing Y
buf[4 * y * width + 3 * width + x] = hr.u;
buf[4 * y * width + 2 * width + x] = hg.u;
buf[4 * y * width + 1 * width + x] = hb.u;
buf[4 * y * width + 0 * width + x] = ha.u;
}
}
int bound = miniz::mz_compressBound(buf.size() * sizeof(unsigned short));
std::vector<unsigned char> block(
miniz::mz_compressBound(buf.size() * sizeof(unsigned short)));
unsigned long long outSize = block.size();
CompressZip(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size() * sizeof(unsigned short));
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = outSize; // truncate
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
data.insert(data.end(), header.begin(), header.end());
data.insert(data.end(), block.begin(), block.begin() + dataLen);
offsets[i] = offset;
offset += dataLen + 8; // 8 = sizeof(blockHeader)
}
fwrite(&offsets.at(0), 1, sizeof(unsigned long long) * numBlocks, fp);
fwrite(&data.at(0), 1, data.size(), fp);
fclose(fp);
return 0; // OK
}
#endif
size_t SaveMultiChannelEXRToMemory(const EXRImage *exrImage,
unsigned char **memory_out,
const char **err) {
if (exrImage == NULL || memory_out == NULL || exrImage->compression < 0 ||
exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Invalid argument.";
}
return 0;
}
std::vector<unsigned char> memory;
// Header
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
memory.insert(memory.end(), header, header + 4);
}
// Version, scanline.
{
const char marker[] = {2, 0, 0, 0};
memory.insert(memory.end(), marker, marker + 4);
}
int numScanlineBlocks = 1;
if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP) {
numScanlineBlocks = 16;
} else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
numScanlineBlocks = 32;
}
// Write attributes.
{
std::vector<unsigned char> data;
std::vector<ChannelInfo> channels;
for (int c = 0; c < exrImage->num_channels; c++) {
ChannelInfo info;
info.pLinear = 0;
info.pixelType = exrImage->requested_pixel_types[c];
info.xSampling = 1;
info.ySampling = 1;
info.name = std::string(exrImage->channel_names[c]);
channels.push_back(info);
}
WriteChannelInfo(data, channels);
WriteAttributeToMemory(memory, "channels", "chlist", &data.at(0),
data.size()); // +1 = null
}
{
int comp = exrImage->compression;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&comp));
}
WriteAttributeToMemory(memory, "compression", "compression",
reinterpret_cast<const unsigned char *>(&comp), 1);
}
{
int data[4] = {0, 0, exrImage->width - 1, exrImage->height - 1};
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&data[0]));
swap4(reinterpret_cast<unsigned int *>(&data[1]));
swap4(reinterpret_cast<unsigned int *>(&data[2]));
swap4(reinterpret_cast<unsigned int *>(&data[3]));
}
WriteAttributeToMemory(memory, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttributeToMemory(memory, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
{
unsigned char lineOrder = 0; // increasingY
WriteAttributeToMemory(memory, "lineOrder", "lineOrder", &lineOrder, 1);
}
{
float aspectRatio = 1.0f;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&aspectRatio));
}
WriteAttributeToMemory(
memory, "pixelAspectRatio", "float",
reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float));
}
{
float center[2] = {0.0f, 0.0f};
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(¢er[0]));
swap4(reinterpret_cast<unsigned int *>(¢er[1]));
}
WriteAttributeToMemory(memory, "screenWindowCenter", "v2f",
reinterpret_cast<const unsigned char *>(center),
2 * sizeof(float));
}
{
float w = (float)exrImage->width;
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&w));
}
WriteAttributeToMemory(memory, "screenWindowWidth", "float",
reinterpret_cast<const unsigned char *>(&w),
sizeof(float));
}
// Custom attributes
if (exrImage->num_custom_attributes > 0) {
// @todo { endian }
for (int i = 0; i < exrImage->num_custom_attributes; i++) {
WriteAttributeToMemory(memory, exrImage->custom_attributes[i].name,
exrImage->custom_attributes[i].type,
reinterpret_cast<const unsigned char *>(
&exrImage->custom_attributes[i].value),
exrImage->custom_attributes[i].size);
}
}
{ // end of header
unsigned char e = 0;
memory.push_back(e);
}
int numBlocks = exrImage->height / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < exrImage->height) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
size_t headerSize = memory.size();
long long offset =
headerSize +
numBlocks * sizeof(long long); // sizeof(header) + sizeof(offsetTable)
std::vector<unsigned char> data;
bool isBigEndian = IsBigEndian();
std::vector<std::vector<unsigned char> > dataList(numBlocks);
std::vector<size_t> channelOffsetList(exrImage->num_channels);
int pixelDataSize = 0;
size_t channelOffset = 0;
for (int c = 0; c < exrImage->num_channels; c++) {
channelOffsetList[c] = channelOffset;
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
pixelDataSize += sizeof(unsigned short);
channelOffset += sizeof(unsigned short);
} else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
pixelDataSize += sizeof(float);
channelOffset += sizeof(float);
} else if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
pixelDataSize += sizeof(unsigned int);
channelOffset += sizeof(unsigned int);
} else {
assert(0);
}
}
#ifdef _OPENMP
#pragma omp parallel for
#endif
for (int i = 0; i < numBlocks; i++) {
int startY = numScanlineBlocks * i;
int endY = (std::min)(numScanlineBlocks * (i + 1), exrImage->height);
int h = endY - startY;
std::vector<unsigned char> buf(exrImage->width * h * pixelDataSize);
for (int c = 0; c < exrImage->num_channels; c++) {
if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
FP16 h16;
h16.u = reinterpret_cast<unsigned short **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
FP32 f32 = half_to_float(h16);
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&f32.f));
}
// Assume increasing Y
float *linePtr = reinterpret_cast<float *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = f32.f;
}
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
unsigned short val = reinterpret_cast<unsigned short **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap2(&val);
}
// Assume increasing Y
unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
} else {
assert(0);
}
} else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) {
if (exrImage->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
FP32 f32;
f32.f = reinterpret_cast<float **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
FP16 h16;
h16 = float_to_half_full(f32);
if (isBigEndian) {
swap2(reinterpret_cast<unsigned short *>(&h16.u));
}
// Assume increasing Y
unsigned short *linePtr = reinterpret_cast<unsigned short *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = h16.u;
}
}
} else if (exrImage->requested_pixel_types[c] ==
TINYEXR_PIXELTYPE_FLOAT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
float val = reinterpret_cast<float **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap4(reinterpret_cast<unsigned int *>(&val));
}
// Assume increasing Y
float *linePtr = reinterpret_cast<float *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
} else {
assert(0);
}
} else if (exrImage->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < exrImage->width; x++) {
unsigned int val = reinterpret_cast<unsigned int **>(
exrImage->images)[c][(y + startY) * exrImage->width + x];
if (isBigEndian) {
swap4(&val);
}
// Assume increasing Y
unsigned int *linePtr = reinterpret_cast<unsigned int *>(
&buf.at(pixelDataSize * y * exrImage->width +
channelOffsetList[c] * exrImage->width));
linePtr[x] = val;
}
}
}
}
if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_NONE) {
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(uncompressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = (unsigned int)buf.size();
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
}
dataList[i].insert(dataList[i].end(), header.begin(), header.end());
dataList[i].insert(dataList[i].end(), buf.begin(), buf.begin() + dataLen);
} else if ((exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIPS) ||
(exrImage->compression == TINYEXR_COMPRESSIONTYPE_ZIP)) {
std::vector<unsigned char> block(miniz::mz_compressBound(buf.size()));
unsigned long long outSize = block.size();
CompressZip(&block.at(0), outSize,
reinterpret_cast<const unsigned char *>(&buf.at(0)),
buf.size());
// 4 byte: scan line
// 4 byte: data size
// ~ : pixel data(compressed)
std::vector<unsigned char> header(8);
unsigned int dataLen = outSize; // truncate
memcpy(&header.at(0), &startY, sizeof(int));
memcpy(&header.at(4), &dataLen, sizeof(unsigned int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&header.at(0)));
swap4(reinterpret_cast<unsigned int *>(&header.at(4)));
}
dataList[i].insert(dataList[i].end(), header.begin(), header.end());
dataList[i].insert(dataList[i].end(), block.begin(),
block.begin() + dataLen);
} else if (exrImage->compression == TINYEXR_COMPRESSIONTYPE_PIZ) {
// @todo
assert(0);
} else {
assert(0);
}
} // omp parallel
for (int i = 0; i < numBlocks; i++) {
data.insert(data.end(), dataList[i].begin(), dataList[i].end());
offsets[i] = offset;
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offsets[i]));
}
offset += dataList[i].size();
}
{
memory.insert(memory.end(),
reinterpret_cast<unsigned char *>(&offsets.at(0)),
reinterpret_cast<unsigned char *>(&offsets.at(0)) +
sizeof(unsigned long long) * numBlocks);
}
{ memory.insert(memory.end(), data.begin(), data.end()); }
assert(memory.size() > 0);
(*memory_out) = (unsigned char *)malloc(memory.size());
memcpy((*memory_out), &memory.at(0), memory.size());
return memory.size(); // OK
}
int SaveMultiChannelEXRToFile(const EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL || filename == NULL || exrImage->compression < 0 ||
exrImage->compression > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "wb");
if (!fp) {
if (err) {
(*err) = "Cannot write a file.";
}
return -1;
}
unsigned char *mem = NULL;
size_t mem_size = SaveMultiChannelEXRToMemory(exrImage, &mem, err);
if ((mem_size > 0) && mem) {
fwrite(mem, 1, mem_size, fp);
}
free(mem);
fclose(fp);
return 0; // OK
}
int LoadDeepEXR(DeepImage *deepImage, const char *filename, const char **err) {
if (deepImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
if (filesize == 0) {
fclose(fp);
if (err) {
(*err) = "File size is zero.";
}
return -1;
}
std::vector<char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
(void)ret;
}
fclose(fp);
const char *head = &buf[0];
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// ver 2.0, scanline, deep bit on(0x800)
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numScanlineBlocks = 1; // 16 for ZIP compression.
int compressionType = -1;
int numChannels = -1;
std::vector<ChannelInfo> channels;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// must be 0:No compression, 1: RLE, 2: ZIPs or 3: ZIP
if (data[0] > 3) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
if (compressionType == 3) { // ZIP
numScanlineBlocks = 16;
}
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
int x;
int y;
int w;
int h;
memcpy(&x, &data.at(0), sizeof(int));
memcpy(&y, &data.at(4), sizeof(int));
memcpy(&w, &data.at(8), sizeof(int));
memcpy(&h, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&x));
swap4(reinterpret_cast<unsigned int *>(&y));
swap4(reinterpret_cast<unsigned int *>(&w));
swap4(reinterpret_cast<unsigned int *>(&h));
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
std::vector<float> image(dataWidth * dataHeight * 4); // 4 = RGBA
// Read offset tables.
int numBlocks = dataHeight / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < dataHeight) {
numBlocks++;
}
std::vector<long long> offsets(numBlocks);
for (int y = 0; y < numBlocks; y++) {
long long offset;
memcpy(&offset, marker, sizeof(long long));
if (IsBigEndian()) {
swap8(reinterpret_cast<unsigned long long *>(&offset));
}
marker += sizeof(long long); // = 8
offsets[y] = offset;
}
if (compressionType != 0 && compressionType != 2 && compressionType != 3) {
if (err) {
(*err) = "Unsupported format.";
}
return -10;
}
deepImage->image = (float ***)malloc(sizeof(float **) * numChannels);
for (int c = 0; c < numChannels; c++) {
deepImage->image[c] = (float **)malloc(sizeof(float *) * dataHeight);
for (int y = 0; y < dataHeight; y++) {
}
}
deepImage->offset_table = (int **)malloc(sizeof(int *) * dataHeight);
for (int y = 0; y < dataHeight; y++) {
deepImage->offset_table[y] = (int *)malloc(sizeof(int) * dataWidth);
}
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// int: y coordinate
// int64: packed size of pixel offset table
// int64: packed size of sample data
// int64: unpacked size of sample data
// compressed pixel offset table
// compressed sample data
int lineNo;
long long packedOffsetTableSize;
long long packedSampleDataSize;
long long unpackedSampleDataSize;
memcpy(&lineNo, dataPtr, sizeof(int));
memcpy(&packedOffsetTableSize, dataPtr + 4, sizeof(long long));
memcpy(&packedSampleDataSize, dataPtr + 12, sizeof(long long));
memcpy(&unpackedSampleDataSize, dataPtr + 20, sizeof(long long));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&lineNo));
swap8(reinterpret_cast<unsigned long long *>(&packedOffsetTableSize));
swap8(reinterpret_cast<unsigned long long *>(&packedSampleDataSize));
swap8(reinterpret_cast<unsigned long long *>(&unpackedSampleDataSize));
}
std::vector<int> pixelOffsetTable(dataWidth);
// decode pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
for (int i = 0; i < dataWidth; i++) {
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
std::vector<unsigned char> sampleData(unpackedSampleDataSize);
// decode sample data.
{
unsigned long dstLen = unpackedSampleDataSize;
DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
dstLen, dataPtr + 28 + packedOffsetTableSize,
packedSampleDataSize);
assert(dstLen == (unsigned long)unpackedSampleDataSize);
}
// decode sample
int sampleSize = -1;
std::vector<int> channelOffsetList(numChannels);
{
int channelOffset = 0;
for (int i = 0; i < numChannels; i++) {
channelOffsetList[i] = channelOffset;
if (channels[i].pixelType == TINYEXR_PIXELTYPE_UINT) { // UINT
channelOffset += 4;
} else if (channels[i].pixelType == TINYEXR_PIXELTYPE_HALF) { // half
channelOffset += 2;
} else if (channels[i].pixelType == TINYEXR_PIXELTYPE_FLOAT) { // float
channelOffset += 4;
} else {
assert(0);
}
}
sampleSize = channelOffset;
}
assert(sampleSize >= 2);
assert((size_t)(pixelOffsetTable[dataWidth - 1] * sampleSize) ==
sampleData.size());
int samplesPerLine = sampleData.size() / sampleSize;
//
// Alloc memory
//
//
// pixel data is stored as image[channels][pixel_samples]
//
{
unsigned long long dataOffset = 0;
for (int c = 0; c < numChannels; c++) {
deepImage->image[c][y] =
(float *)malloc(sizeof(float) * samplesPerLine);
if (channels[c].pixelType == 0) { // UINT
for (int x = 0; x < samplesPerLine; x++) {
unsigned int ui = *reinterpret_cast<unsigned int *>(
&sampleData.at(dataOffset + x * sizeof(int)));
deepImage->image[c][y][x] = (float)ui; // @fixme
}
dataOffset += sizeof(unsigned int) * samplesPerLine;
} else if (channels[c].pixelType == 1) { // half
for (int x = 0; x < samplesPerLine; x++) {
FP16 f16;
f16.u = *reinterpret_cast<unsigned short *>(
&sampleData.at(dataOffset + x * sizeof(short)));
FP32 f32 = half_to_float(f16);
deepImage->image[c][y][x] = f32.f;
}
dataOffset += sizeof(short) * samplesPerLine;
} else { // float
for (int x = 0; x < samplesPerLine; x++) {
float f = *reinterpret_cast<float *>(
&sampleData.at(dataOffset + x * sizeof(float)));
deepImage->image[c][y][x] = f;
}
dataOffset += sizeof(float) * samplesPerLine;
}
}
}
} // y
deepImage->width = dataWidth;
deepImage->height = dataHeight;
deepImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
deepImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
deepImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
deepImage->num_channels = numChannels;
return 0; // OK
}
int SaveDeepEXR(const DeepImage *deepImage, const char *filename,
const char **err) {
if (deepImage == NULL || filename == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot write file.";
}
return -1;
}
// Write header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
size_t n = fwrite(header, 1, 4, fp);
if (n != 4) {
if (err) {
(*err) = "Header write failed.";
}
fclose(fp);
return -3;
}
}
// Version, scanline.
{
// ver 2.0, scanline, deep bit on(0x800)
const char data[] = {2, 8, 0, 0};
size_t n = fwrite(data, 1, 4, fp);
if (n != 4) {
if (err) {
(*err) = "Flag write failed.";
}
fclose(fp);
return -3;
}
}
// Write attributes.
{
int data = 2; // ZIPS
WriteAttribute(fp, "compression", "compression",
reinterpret_cast<const unsigned char *>(&data), sizeof(int));
}
{
int data[4] = {0, 0, deepImage->width - 1, deepImage->height - 1};
WriteAttribute(fp, "dataWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
WriteAttribute(fp, "displayWindow", "box2i",
reinterpret_cast<const unsigned char *>(data),
sizeof(int) * 4);
}
int numScanlineBlocks = 1;
// Write offset tables.
int numBlocks = deepImage->height / numScanlineBlocks;
if (numBlocks * numScanlineBlocks < deepImage->height) {
numBlocks++;
}
#if 0 // @todo
std::vector<long long> offsets(numBlocks);
//std::vector<int> pixelOffsetTable(dataWidth);
// compress pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
Compresses(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
// int ret =
// miniz::mz_uncompress(reinterpret_cast<unsigned char
// *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
// packedOffsetTableSize);
// printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
//
for (int i = 0; i < dataWidth; i++) {
// printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
for (int y = 0; y < numBlocks; y++) {
//long long offset = *(reinterpret_cast<const long long *>(marker));
// printf("offset[%d] = %lld\n", y, offset);
//marker += sizeof(long long); // = 8
offsets[y] = offset;
}
// Write offset table.
fwrite(&offsets.at(0), sizeof(long long), numBlocks, fp);
for (int y = 0; y < numBlocks; y++) {
const unsigned char *dataPtr =
reinterpret_cast<const unsigned char *>(head + offsets[y]);
// int: y coordinate
// int64: packed size of pixel offset table
// int64: packed size of sample data
// int64: unpacked size of sample data
// compressed pixel offset table
// compressed sample data
int lineNo = *reinterpret_cast<const int *>(dataPtr);
long long packedOffsetTableSize =
*reinterpret_cast<const long long *>(dataPtr + 4);
long long packedSampleDataSize =
*reinterpret_cast<const long long *>(dataPtr + 12);
long long unpackedSampleDataSize =
*reinterpret_cast<const long long *>(dataPtr + 20);
// printf("line: %d, %lld/%lld/%lld\n", lineNo, packedOffsetTableSize,
// packedSampleDataSize, unpackedSampleDataSize);
int endLineNo = (std::min)(lineNo + numScanlineBlocks, dataHeight);
int numLines = endLineNo - lineNo;
// printf("numLines: %d\n", numLines);
std::vector<int> pixelOffsetTable(dataWidth);
// decode pixel offset table.
{
unsigned long dstLen = pixelOffsetTable.size() * sizeof(int);
DecompressZip(reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)),
dstLen, dataPtr + 28, packedOffsetTableSize);
assert(dstLen == pixelOffsetTable.size() * sizeof(int));
// int ret =
// miniz::mz_uncompress(reinterpret_cast<unsigned char
// *>(&pixelOffsetTable.at(0)), &dstLen, dataPtr + 28,
// packedOffsetTableSize);
// printf("ret = %d, dstLen = %d\n", ret, (int)dstLen);
//
for (int i = 0; i < dataWidth; i++) {
// printf("offt[%d] = %d\n", i, pixelOffsetTable[i]);
deepImage->offset_table[y][i] = pixelOffsetTable[i];
}
}
std::vector<unsigned char> sampleData(unpackedSampleDataSize);
// decode sample data.
{
unsigned long dstLen = unpackedSampleDataSize;
// printf("dstLen = %d\n", dstLen);
// printf("srcLen = %d\n", packedSampleDataSize);
DecompressZip(reinterpret_cast<unsigned char *>(&sampleData.at(0)),
dstLen, dataPtr + 28 + packedOffsetTableSize,
packedSampleDataSize);
assert(dstLen == unpackedSampleDataSize);
}
// decode sample
int sampleSize = -1;
std::vector<int> channelOffsetList(numChannels);
{
int channelOffset = 0;
for (int i = 0; i < numChannels; i++) {
// printf("offt[%d] = %d\n", i, channelOffset);
channelOffsetList[i] = channelOffset;
if (channels[i].pixelType == 0) { // UINT
channelOffset += 4;
} else if (channels[i].pixelType == 1) { // half
channelOffset += 2;
} else if (channels[i].pixelType == 2) { // float
channelOffset += 4;
} else {
assert(0);
}
}
sampleSize = channelOffset;
}
assert(sampleSize >= 2);
assert(pixelOffsetTable[dataWidth - 1] * sampleSize == sampleData.size());
int samplesPerLine = sampleData.size() / sampleSize;
//
// Alloc memory
//
//
// pixel data is stored as image[channels][pixel_samples]
//
{
unsigned long long dataOffset = 0;
for (int c = 0; c < numChannels; c++) {
deepImage->image[c][y] =
(float *)malloc(sizeof(float) * samplesPerLine);
// unsigned int channelOffset = channelOffsetList[c];
// unsigned int i = channelOffset;
// printf("channel = %d. name = %s. ty = %d\n", c,
// channels[c].name.c_str(), channels[c].pixelType);
// printf("dataOffset = %d\n", (int)dataOffset);
if (channels[c].pixelType == 0) { // UINT
for (int x = 0; x < samplesPerLine; x++) {
unsigned int ui = *reinterpret_cast<unsigned int *>(
&sampleData.at(dataOffset + x * sizeof(int)));
deepImage->image[c][y][x] = (float)ui; // @fixme
}
dataOffset += sizeof(unsigned int) * samplesPerLine;
} else if (channels[c].pixelType == 1) { // half
for (int x = 0; x < samplesPerLine; x++) {
FP16 f16;
f16.u = *reinterpret_cast<unsigned short *>(
&sampleData.at(dataOffset + x * sizeof(short)));
FP32 f32 = half_to_float(f16);
deepImage->image[c][y][x] = f32.f;
// printf("c[%d] f(half) = %f (0x%08x)\n", c, f32.f, f16.u);
}
dataOffset += sizeof(short) * samplesPerLine;
} else { // float
for (int x = 0; x < samplesPerLine; x++) {
float f = *reinterpret_cast<float *>(
&sampleData.at(dataOffset + x * sizeof(float)));
// printf(" f = %f(0x%08x)\n", f, *((unsigned int *)&f));
deepImage->image[c][y][x] = f;
}
dataOffset += sizeof(float) * samplesPerLine;
}
}
// printf("total: %d\n", dataOffset);
}
} // y
#endif
fclose(fp);
return 0; // OK
}
void InitEXRImage(EXRImage *exrImage) {
if (exrImage == NULL) {
return;
}
exrImage->num_custom_attributes = 0;
exrImage->num_channels = 0;
exrImage->channel_names = NULL;
exrImage->images = NULL;
exrImage->pixel_types = NULL;
exrImage->requested_pixel_types = NULL;
exrImage->compression = TINYEXR_COMPRESSIONTYPE_ZIP;
}
int FreeEXRImage(EXRImage *exrImage) {
if (exrImage == NULL) {
return -1; // Err
}
for (int i = 0; i < exrImage->num_channels; i++) {
if (exrImage->channel_names && exrImage->channel_names[i]) {
free((char *)exrImage->channel_names[i]); // remove const
}
if (exrImage->images && exrImage->images[i]) {
free(exrImage->images[i]);
}
}
if (exrImage->channel_names) {
free(exrImage->channel_names);
}
if (exrImage->images) {
free(exrImage->images);
}
if (exrImage->pixel_types) {
free(exrImage->pixel_types);
}
if (exrImage->requested_pixel_types) {
free(exrImage->requested_pixel_types);
}
for (int i = 0; i < exrImage->num_custom_attributes; i++) {
if (exrImage->custom_attributes[i].name) {
free(exrImage->custom_attributes[i].name);
}
if (exrImage->custom_attributes[i].type) {
free(exrImage->custom_attributes[i].type);
}
if (exrImage->custom_attributes[i].value) {
free(exrImage->custom_attributes[i].value);
}
}
return 0;
}
int ParseMultiChannelEXRHeaderFromFile(EXRImage *exrImage, const char *filename,
const char **err) {
if (exrImage == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
FILE *fp = fopen(filename, "rb");
if (!fp) {
if (err) {
(*err) = "Cannot read file.";
}
return -1;
}
size_t filesize;
// Compute size
fseek(fp, 0, SEEK_END);
filesize = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<unsigned char> buf(filesize); // @todo { use mmap }
{
size_t ret;
ret = fread(&buf[0], 1, filesize, fp);
assert(ret == filesize);
fclose(fp);
(void)ret;
}
return ParseMultiChannelEXRHeaderFromMemory(exrImage, &buf.at(0), err);
}
int ParseMultiChannelEXRHeaderFromMemory(EXRImage *exrImage,
const unsigned char *memory,
const char **err) {
if (exrImage == NULL || memory == NULL) {
if (err) {
(*err) = "Invalid argument.";
}
return -1;
}
const char *buf = reinterpret_cast<const char *>(memory);
const char *marker = &buf[0];
// Header check.
{
const char header[] = {0x76, 0x2f, 0x31, 0x01};
if (memcmp(marker, header, 4) != 0) {
if (err) {
(*err) = "Header mismatch.";
}
return -3;
}
marker += 4;
}
// Version, scanline.
{
// must be [2, 0, 0, 0]
if (marker[0] != 2 || marker[1] != 0 || marker[2] != 0 || marker[3] != 0) {
if (err) {
(*err) = "Unsupported version or scanline.";
}
return -4;
}
marker += 4;
}
int dx = -1;
int dy = -1;
int dw = -1;
int dh = -1;
int numChannels = -1;
int displayWindow[4] = {-1, -1, -1, -1}; // @fixme.
float screenWindowCenter[2] = {0.0f, 0.0f}; // @fixme
float screenWindowWidth = 1.0f; // @fixme
float pixelAspectRatio = 1.0f;
unsigned char lineOrder = 0; // 0 -> increasing y; 1 -> decreasing
std::vector<ChannelInfo> channels;
int compressionType = 0; // @fixme
int numCustomAttributes = 0;
std::vector<EXRAttribute> customAttribs;
// Read attributes
for (;;) {
std::string attrName;
std::string attrType;
std::vector<unsigned char> data;
const char *marker_next = ReadAttribute(attrName, attrType, data, marker);
if (marker_next == NULL) {
marker++; // skip '\0'
break;
}
if (attrName.compare("compression") == 0) {
// must be 0:No compression, 1: RLE, 2: ZIPs, 3: ZIP or 4: PIZ
if (data[0] > TINYEXR_COMPRESSIONTYPE_PIZ) {
if (err) {
(*err) = "Unsupported compression type.";
}
return -5;
}
compressionType = data[0];
} else if (attrName.compare("channels") == 0) {
// name: zero-terminated string, from 1 to 255 bytes long
// pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2
// pLinear: unsigned char, possible values are 0 and 1
// reserved: three chars, should be zero
// xSampling: int
// ySampling: int
ReadChannelInfo(channels, data);
numChannels = channels.size();
if (numChannels < 1) {
if (err) {
(*err) = "Invalid channels format.";
}
return -6;
}
} else if (attrName.compare("dataWindow") == 0) {
memcpy(&dx, &data.at(0), sizeof(int));
memcpy(&dy, &data.at(4), sizeof(int));
memcpy(&dw, &data.at(8), sizeof(int));
memcpy(&dh, &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&dx));
swap4(reinterpret_cast<unsigned int *>(&dy));
swap4(reinterpret_cast<unsigned int *>(&dw));
swap4(reinterpret_cast<unsigned int *>(&dh));
}
} else if (attrName.compare("displayWindow") == 0) {
memcpy(&displayWindow[0], &data.at(0), sizeof(int));
memcpy(&displayWindow[1], &data.at(4), sizeof(int));
memcpy(&displayWindow[2], &data.at(8), sizeof(int));
memcpy(&displayWindow[3], &data.at(12), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&displayWindow[0]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[1]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[2]));
swap4(reinterpret_cast<unsigned int *>(&displayWindow[3]));
}
} else if (attrName.compare("lineOrder") == 0) {
int order;
memcpy(&order, &data.at(0), sizeof(int));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&order));
}
lineOrder = (unsigned char)order;
} else if (attrName.compare("pixelAspectRatio") == 0) {
memcpy(&pixelAspectRatio, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&pixelAspectRatio));
}
} else if (attrName.compare("screenWindowCenter") == 0) {
memcpy(&screenWindowCenter[0], &data.at(0), sizeof(float));
memcpy(&screenWindowCenter[1], &data.at(4), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[0]));
swap4(reinterpret_cast<unsigned int *>(&screenWindowCenter[1]));
}
} else if (attrName.compare("screenWindowWidth") == 0) {
memcpy(&screenWindowWidth, &data.at(0), sizeof(float));
if (IsBigEndian()) {
swap4(reinterpret_cast<unsigned int *>(&screenWindowWidth));
}
} else {
// Custom attribute(up to TINYEXR_MAX_ATTRIBUTES)
if (numCustomAttributes < TINYEXR_MAX_ATTRIBUTES) {
EXRAttribute attrib;
attrib.name = strdup(attrName.c_str());
attrib.type = strdup(attrType.c_str());
attrib.size = data.size();
attrib.value = (unsigned char *)malloc(data.size());
memcpy((char *)attrib.value, &data.at(0), data.size());
customAttribs.push_back(attrib);
}
}
marker = marker_next;
}
assert(dx >= 0);
assert(dy >= 0);
assert(dw >= 0);
assert(dh >= 0);
assert(numChannels >= 1);
int dataWidth = dw - dx + 1;
int dataHeight = dh - dy + 1;
{
exrImage->channel_names =
(const char **)malloc(sizeof(const char *) * numChannels);
for (int c = 0; c < numChannels; c++) {
#ifdef _WIN32
exrImage->channel_names[c] = _strdup(channels[c].name.c_str());
#else
exrImage->channel_names[c] = strdup(channels[c].name.c_str());
#endif
}
exrImage->num_channels = numChannels;
exrImage->width = dataWidth;
exrImage->height = dataHeight;
exrImage->pixel_aspect_ratio = pixelAspectRatio;
exrImage->screen_window_center[0] = screenWindowCenter[0];
exrImage->screen_window_center[1] = screenWindowCenter[1];
exrImage->screen_window_width = screenWindowWidth;
exrImage->display_window[0] = displayWindow[0];
exrImage->display_window[1] = displayWindow[1];
exrImage->display_window[2] = displayWindow[2];
exrImage->display_window[3] = displayWindow[3];
exrImage->data_window[0] = dx;
exrImage->data_window[1] = dy;
exrImage->data_window[2] = dw;
exrImage->data_window[3] = dh;
exrImage->line_order = lineOrder;
exrImage->compression = compressionType;
exrImage->pixel_types = (int *)malloc(sizeof(int) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->pixel_types[c] = channels[c].pixelType;
}
// Initially fill with values of `pixel-types`
exrImage->requested_pixel_types = (int *)malloc(sizeof(int) * numChannels);
for (int c = 0; c < numChannels; c++) {
exrImage->requested_pixel_types[c] = channels[c].pixelType;
}
}
if (numCustomAttributes > 0) {
assert(customAttribs.size() < TINYEXR_MAX_ATTRIBUTES);
exrImage->num_custom_attributes = numCustomAttributes;
for (int i = 0; i < (int)customAttribs.size(); i++) {
exrImage->custom_attributes[i] = customAttribs[i];
}
}
return 0; // OK
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
#endif // __TINYEXR_H__
|
solucao_omp_combinado.c | /******************************************************************************
* OpenMP Example - Combined Parallel Loop Work-sharing - C/C++ Version
* FILE: omp_workshare4.c
* DESCRIPTION:
* This is a corrected version of the omp_workshare3.c example. Corrections
* include removing all statements between the parallel for construct and
* the actual for loop, and introducing logic to preserve the ability to
* query a thread's id and print it from inside the for loop.
* SOURCE: Blaise Barney 5/99
* LAST REVISED:
******************************************************************************/
#include <omp.h>
#define N 50
#define CHUNK 5
main () {
int i, n, chunk, tid;
float a[N], b[N], c[N];
char first_time;
/* Some initializations */
for (i=0; i < N; i++)
a[i] = b[i] = i * 1.0;
n = N;
chunk = CHUNK;
first_time = 'y';
#pragma omp parallel for \
shared(a,b,c) \
private(i,tid) \
schedule(static,chunk) \
firstprivate(first_time)
for (i=0; i < n; i++)
{
if (first_time == 'y')
{
tid = omp_get_thread_num();
first_time = 'n';
}
c[i] = a[i] + b[i];
printf("tid= %d i= %d c[i]= %f\n", tid, i, c[i]);
}
}
|
admm.c |
/******************************************************************************
* INCLUDES
*****************************************************************************/
#include "admm.h"
#include "../util.h"
#include "../splatt_debug.h"
#include <omp.h>
#include <math.h>
/******************************************************************************
* PRIVATE FUNCTIONS
*****************************************************************************/
/**
* @brief Compute the auxiliary matrix before the Cholesky solve. This function
* computes: mat_mttkrp + (penalty .* (mat_primal - mat_dual)).
*
* @param mat_primal The primal variable.
* @param mat_mttkrp The latest MTTKRP result.
* @param mat_dual The dual variable.
* @param penalty The penalty parameter, 'rho'. This could also be used during
* l2 (Tikhonov) regularization.
* @param[out] mat_auxil The auxiliary matrix.
* @param should_parallelize Whether we should parallelize.
*/
static void p_setup_auxiliary(
matrix_t const * const mat_primal,
matrix_t const * const mat_mttkrp,
matrix_t const * const mat_dual,
val_t const penalty,
matrix_t * const mat_auxil,
bool const should_parallelize)
{
idx_t const I = mat_primal->I;
idx_t const J = mat_primal->J;
val_t * const restrict aux = mat_auxil->vals;
val_t const * const restrict mttkrp = mat_mttkrp->vals;
val_t const * const restrict primal = mat_primal->vals;
val_t const * const restrict dual = mat_dual->vals;
#pragma omp parallel for schedule(static) if(should_parallelize)
for(idx_t x=0; x < I * J; ++x) {
aux[x] = mttkrp[x] + penalty * (primal[x] + dual[x]);
}
}
/**
* @brief Update the dual variable after updating the primal and auxiliary
* variables. The squared Frobenius norm of the new dual is returned.
* This function performs: mat_dual += mat_primal - mat_auxil.
*
* @param mat_primal The newest primal variable.
* @param mat_auxil The newest auxiliary variable.
* @param[out] mat_dual The dual variable to update.
* @param should_parallelize Whether we should parallelize.
*
* @return The norm of the new dual; || mat_dual ||_F^2.
*/
static val_t p_update_dual(
matrix_t const * const mat_primal,
matrix_t const * const mat_auxil,
matrix_t * const mat_dual,
bool const should_parallelize)
{
idx_t const I = mat_primal->I;
idx_t const J = mat_primal->J;
val_t * const restrict dual = mat_dual->vals;
val_t const * const restrict matv = mat_primal->vals;
val_t const * const restrict auxl = mat_auxil->vals;
val_t norm = 0.;
#pragma omp parallel for schedule(static) reduction(+:norm) \
if(should_parallelize)
for(idx_t x=0; x < I * J; ++x) {
dual[x] += matv[x] - auxl[x];
norm += dual[x] * dual[x];
}
return norm;
}
/**
* @brief Initialize the primal matrix with (auxil - dual).
*
* @param[out] mat_primal The primal matrix to initialize.
* @param mat_auxil The auxiliary matrix.
* @param mat_dual The dual matrix.
* @param should_parallelize Whether we should parallelize.
*/
static void p_setup_proximity(
matrix_t * const mat_primal,
matrix_t const * const mat_auxil,
matrix_t const * const mat_dual,
bool const should_parallelize)
{
val_t * const restrict primal = mat_primal->vals;
val_t const * const restrict auxil = mat_auxil->vals;
val_t const * const restrict dual = mat_dual->vals;
idx_t const N = mat_primal->I * mat_primal->J;
#pragma omp parallel for schedule(static) if(should_parallelize)
for(idx_t x=0; x < N; ++x) {
primal[x] = auxil[x] - dual[x];
}
}
/**
* @brief Calculate the primal and dual residuals before the ADMM convergence
* check.
*
* @param mat_primal The primal variable (the factor we are updating).
* @param mat_auxil The auxiliary matrix; ideally mat_auxil^T = mat_primal.
* @param mat_init The initial matrix factor (at the start of this iteration).
* @param[out] primal_norm The norm of the primal variable; norm(mat_primal)^2.
* @param[out] primal_resid The residual of the primal variable;
* norm(mat_primal - mat_auxil)^2.
* @param[out] dual_resid The dual residual; norm(mat_primal - mat_init)^2.
* @param should_parallelize Whether we should parallelize.
*/
static void p_calc_residual(
matrix_t const * const mat_primal,
matrix_t const * const mat_auxil,
matrix_t const * const mat_init,
val_t * primal_norm,
val_t * primal_resid,
val_t * dual_resid,
bool const should_parallelize)
{
val_t const * const restrict matv = mat_primal->vals;
val_t const * const restrict auxv = mat_auxil->vals;
val_t const * const restrict init = mat_init->vals;
idx_t const nrows = mat_primal->I;
idx_t const ncols = mat_primal->J;
val_t p_norm = 0;
val_t p_resid = 0;
val_t d_resid = 0;
/*
* Converge based on max row movement.
*/
#if SPLATT_ADMM_ROW_CONVERGE
#pragma omp parallel for reduction(max:p_norm, p_resid, d_resid) \
if(should_parallelize)
for(idx_t i=0; i < nrows; ++i) {
val_t row_p_norm = 0;
val_t row_p_resid = 0;
val_t row_d_resid = 0;
for(idx_t j=0; j < ncols; ++j) {
idx_t const index = j + (i*ncols);
val_t const pdiff = matv[index] - auxv[index];
val_t const ddiff = matv[index] - init[index];
row_p_norm += matv[index] * matv[index];
row_p_resid += pdiff * pdiff;
row_d_resid += ddiff * ddiff;
}
/* save the row with the largest primal residual */
if(row_p_resid > p_resid) {
p_norm = row_p_norm;
p_resid = row_p_resid;
d_resid = row_d_resid;
}
}
#else
/*
* Converge based on aggregate row movement.
*/
#pragma omp parallel for reduction(+:p_norm, p_resid, d_resid) \
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);
val_t const pdiff = matv[index] - auxv[index];
val_t const ddiff = matv[index] - init[index];
p_norm += matv[index] * matv[index];
p_resid += pdiff * pdiff;
d_resid += ddiff * ddiff;
}
}
#endif
*primal_norm = p_norm;
*primal_resid = p_resid;
*dual_resid = d_resid;
}
/**
* @brief Optimally update the primal variable using a closed-form solution.
*
* @param[out] primal The matrix to update.
* @param ws CPD workspace.
* @param con The constraint we are enforcing.
*/
static void p_constraint_closedform(
matrix_t * const primal,
cpd_ws * const ws,
splatt_cpd_constraint * con)
{
/* Modify primal/Gram matrices if necessary. */
if(con->clsd_func != NULL) {
idx_t const nrows = primal->I;
idx_t const ncols = primal->J;
con->clsd_func(primal->vals, nrows, ncols, con->data);
}
mat_cholesky(ws->gram);
/* Copy and then solve directly against MTTKRP */
size_t const bytes = primal->I * primal->J * sizeof(*primal->vals);
par_memcpy(primal->vals, ws->mttkrp_buf->vals, bytes);
mat_solve_cholesky(ws->gram, primal);
}
static idx_t p_admm_iterate_chunk(
matrix_t * primal,
matrix_t * auxil,
matrix_t * dual,
matrix_t * cholesky,
matrix_t * mttkrp_buf,
matrix_t * init_buf,
idx_t mode,
splatt_cpd_constraint * const con,
val_t const rho,
cpd_ws * const ws,
splatt_cpd_opts const * const cpd_opts,
splatt_global_opts const * const global_opts,
bool const should_parallelize)
{
idx_t const rank = primal->J;
bool is_spd = mat_cholesky_(ws->gram);
/* for checking convergence */
val_t primal_norm = 0.;
val_t dual_norm = 0.;
val_t primal_residual = 0.;
val_t dual_residual = 0.;
/* foreach inner iteration */
idx_t it;
for(it=0; it < cpd_opts->max_inner_iterations; ++it) {
/* save starting point for convergence check */
size_t const bytes = primal->I * rank * sizeof(*primal->vals);
if(should_parallelize) {
par_memcpy(init_buf->vals, primal->vals, bytes);
} else {
memcpy(init_buf->vals, primal->vals, bytes);
}
/* auxiliary = MTTKRP + (rho .* (primal + dual)) */
p_setup_auxiliary(primal, mttkrp_buf, dual, rho, auxil,
should_parallelize);
/* Cholesky against auxiliary */
// mat_solve_cholesky(ws->gram, auxil);
mat_solve_cholesky_with_fallback(ws->gram, auxil, is_spd);
p_setup_proximity(primal, auxil, dual, should_parallelize);
/* APPLY CONSTRAINT / REGULARIZATION */
if(con->prox_func != NULL) {
con->prox_func(primal->vals, primal->I, rank, 0, con->data, rho,
should_parallelize);
} else {
fprintf(stderr, "SPLATT: WARNING no proximity operator specified for "
"constraint '%s'\n.", con->description);
}
/* update dual: U += (primal - auxiliary) */
dual_norm = p_update_dual(primal, auxil, dual, should_parallelize);
/* check ADMM convergence */
p_calc_residual(primal, auxil, init_buf, &primal_norm, &primal_residual,
&dual_residual, should_parallelize);
/* converged? */
if((primal_residual <= cpd_opts->inner_tolerance * primal_norm) &&
(dual_residual <= cpd_opts->inner_tolerance * dual_norm)) {
++it;
break;
}
}
return it;
}
val_t admm_stream_inner_maxcolnorm(
matrix_t * primal_mat,
matrix_t * auxil_mat,
matrix_t * dual_mat,
matrix_t * cholesky_mat,
matrix_t * mttkrp_buf,
matrix_t * init_buf,
idx_t chunk_size,
splatt_cpd_constraint * const con,
val_t const rho,
splatt_cpd_opts const * const cpd_opts)
{
idx_t rank = primal_mat->J;
idx_t niter;
/* for checking convergence */
val_t p_norm = 0.;
val_t d_norm = 0.;
val_t p_res = 0.;
val_t d_res = 0.;
chunk_size = 64;
idx_t num_chunks = (primal_mat->I / chunk_size);
if(primal_mat->I % chunk_size > 0) {
++num_chunks;
}
bool is_spd = mat_cholesky_(cholesky_mat);
#pragma omp parallel shared(p_norm,d_norm,p_res,d_res,niter)
{
int tid = omp_get_thread_num();
val_t * restrict norms = (val_t*) splatt_malloc(rank*sizeof(val_t));
val_t * restrict colnorms = (val_t*) splatt_malloc(rank*sizeof(val_t));
memset(norms, 0, rank*sizeof(val_t));
memset(colnorms, 0, rank*sizeof(val_t));
/*
__assume_aligned(norms, 64);
__assume_aligned(colnorms, 64);
*/
#pragma omp for
for(idx_t c=0; c < num_chunks; ++c) {
idx_t const start = c * chunk_size;
idx_t const stop = (c == num_chunks-1) ? primal_mat->I : (c+1)*chunk_size;
idx_t const offset = start * rank;
idx_t const nrows = stop - start;
idx_t const ncols = rank;
/* extract all the workspaces per chunk */
val_t * const restrict primal = primal_mat->vals + offset;
val_t * const restrict auxil = auxil_mat->vals + offset;
val_t * const restrict dual = dual_mat->vals + offset;
val_t * const restrict mttkrp = mttkrp_buf->vals + offset;
val_t * const restrict init = init_buf->vals + offset;
/*
__assume_aligned(primal, 64);
__assume_aligned(auxil, 64);
__assume_aligned(dual, 64);
__assume_aligned(mttkrp, 64);
__assume_aligned(init, 64);
*/
matrix_t auxil_chunk_mat;
mat_fillptr(&auxil_chunk_mat, auxil, nrows, rank, auxil_mat->rowmajor);
// row-wise/vector-wise fused formation of rhs
#pragma simd
#pragma vector aligned
for (idx_t idx = 0; idx < ncols*nrows; ++idx) {
auxil[idx] = mttkrp[idx] + rho*(primal[idx] + dual[idx]);
}
// chunk solve chol
// mat_solve_cholesky(cholesky_mat, &auxil_chunk_mat);
mat_solve_cholesky_with_fallback(cholesky_mat, &auxil_chunk_mat, is_spd);
// form prox and compute new norm
for (idx_t i = 0; i < nrows; ++i) {
for (idx_t j = 0; j < ncols; ++j) {
idx_t idx = j + i*ncols;
val_t x = auxil[idx] - dual[idx];
init[idx] = x; // primal
// TODO: compute colnorm and perform possible thresholding (non-neg)
colnorms[j] += x * x;
}
}
}
/* reduce norms */
#pragma omp barrier
thread_allreduce(colnorms, rank, SPLATT_REDUCE_SUM);
for (idx_t j=0; j < rank; ++j) {
colnorms[j] = sqrt(colnorms[j]);
colnorms[j] = (colnorms[j] > 1.) ? colnorms[j] : 1.;
}
memcpy(norms, colnorms, rank*sizeof(val_t));
memset(colnorms, 0, rank*sizeof(val_t));
idx_t it;
int do_break = 0;
for(it=0; it < cpd_opts->max_inner_iterations; ++it) {
{ p_res = 0; d_res = 0; p_norm = 0; d_norm = 0; }
#pragma omp for reduction(+:p_norm,p_res,d_norm,d_res)
for(idx_t c=0; c < num_chunks; ++c) {
idx_t const start = c * chunk_size;
idx_t const stop = (c == num_chunks-1) ? primal_mat->I : (c+1)*chunk_size;
idx_t const offset = start * rank;
idx_t const nrows = stop - start;
idx_t const ncols = rank;
/* extract all the workspaces per chunk */
val_t * const restrict primal = primal_mat->vals + offset;
val_t * const restrict auxil = auxil_mat->vals + offset;
val_t * const restrict dual = dual_mat->vals + offset;
val_t * const restrict mttkrp = mttkrp_buf->vals + offset;
val_t * const restrict init = init_buf->vals + offset;
/*
__assume_aligned(primal, 64);
__assume_aligned(auxil, 64);
__assume_aligned(dual, 64);
__assume_aligned(mttkrp, 64);
__assume_aligned(init, 64);
*/
matrix_t auxil_chunk_mat;
mat_fillptr(&auxil_chunk_mat, auxil, nrows, rank, auxil_mat->rowmajor);
// vectorized loop?
// form prox and compute new norm
// TODO:
// instead do inner loop of some vector blocksize (64 bytes)
// - duplicate norms to at least (B + ncols)
// - ncols % blocksize remainder, how to handle?
// - block b is element b*B, which is column: b*B % ncols
for (idx_t i = 0; i < nrows; ++i) {
for (idx_t j = 0; j < ncols; ++j) {
idx_t idx = j + i*ncols;
init[idx] /= norms[j];
}
}
const idx_t cs = nrows*ncols;
#pragma simd
#pragma vector aligned
for (idx_t idx = 0; idx < cs; ++idx) {
// compute new primal and dual residual
val_t x = init[idx];
val_t pdiff = x - primal[idx];
d_res += pdiff*pdiff;
primal[idx] = x;
// update primal norm
p_norm += x*x;
// update dual U <- U + (pri - aux)
val_t y = x - auxil[idx];
val_t di = dual[idx] + y;
dual[idx] = di;
// update dual norm and primal residual
d_norm += di*di;
p_res += y*y;
// form next RHS for cholesky
auxil[idx] = mttkrp[idx] + rho*(x + di);
}
// chunk solve chol
// mat_solve_cholesky(cholesky_mat, &auxil_chunk_mat);
mat_solve_cholesky_with_fallback(cholesky_mat, &auxil_chunk_mat, is_spd);
// form prox and compute new norm
for (idx_t i = 0; i < nrows; ++i) {
for (idx_t j = 0; j < ncols; ++j) {
idx_t idx = j + i*ncols;
val_t x = auxil[idx] - dual[idx];
init[idx] = x;
// TODO: compute colnorm and perform possible thresholding (non-neg)
colnorms[j] += x * x;
}
}
}
#pragma omp barrier
/* check convergence */
if((p_res <= cpd_opts->inner_tolerance * p_norm) &&
(d_res <= cpd_opts->inner_tolerance * d_norm)) {
++it;
break;
}
/* reduce norms */
thread_allreduce(colnorms, rank, SPLATT_REDUCE_SUM);
for (idx_t j=0; j < rank; ++j) {
colnorms[j] = sqrt(colnorms[j]);
colnorms[j] = (colnorms[j] > 1.) ? colnorms[j] : 1.;
}
memcpy(norms, colnorms, rank*sizeof(val_t));
memset(colnorms, 0, rank*sizeof(val_t));
} /* admm iteration */
#pragma omp master
{
niter = it;
}
} /* omp parallel */
return niter;
}
val_t admm_stream(
idx_t mode,
matrix_t * * mats,
val_t * const restrict column_weights,
cpd_ws * const ws,
splatt_cpd_opts const * const cpd_opts,
splatt_global_opts const * const global_opts)
{
idx_t const rank = mats[mode]->J;
splatt_cpd_constraint * con = cpd_opts->constraints[mode];
/* (A^T * A) .* (B^T * B) .* .... ) */
mat_form_gram(ws->aTa, ws->gram, ws->nmodes, mode);
if(con->gram_func != NULL) {
con->gram_func(ws->gram->vals, rank, con->data);
}
/* these can be solved optimally without ADMM iterations */
if(con->solve_type == SPLATT_CON_CLOSEDFORM) {
p_constraint_closedform(mats[mode], ws, con);
/* Absorb columns into column_weights if no constraints are applied */
if(ws->unconstrained) {
mat_normalize(mats[mode], column_weights);
}
return 0.;
}
/* Add penalty to diagonal -- value taken from AO-ADMM paper */
val_t const rho = mat_trace(ws->gram) / (val_t) rank;
mat_add_diag(ws->gram, rho);
/* Compute Cholesky factorization to use for forward/backward solves each
* ADMM iteration */
// mat_cholesky(ws->gram);
/* Compute number of chunks */
idx_t const chunk_size = cpd_opts->chunk_sizes[mode];
idx_t niter = admm_stream_inner_maxcolnorm(
mats[mode], ws->auxil, ws->duals[mode], ws->gram,
ws->mttkrp_buf, ws->mat_init, chunk_size, con, rho, cpd_opts);
/* return #iterations */
return (val_t) niter;
}
/******************************************************************************
* PUBLIC FUNCTIONS
*****************************************************************************/
void closedform_solve(
matrix_t * const primal,
matrix_t * const gram,
cpd_ws * const ws)
{
mat_cholesky(gram);
/* Copy and then solve directly against MTTKRP */
size_t const bytes = primal->I * primal->J * sizeof(*primal->vals);
par_memcpy(primal->vals, ws->mttkrp_buf->vals, bytes);
mat_solve_cholesky(gram, primal);
}
val_t admm_(
idx_t mode,
matrix_t * * mats,
val_t * const restrict column_weights,
cpd_ws * const ws,
splatt_cpd_opts const * const cpd_opts,
splatt_global_opts const * const global_opts)
{
idx_t const rank = mats[mode]->J;
splatt_cpd_constraint * con = cpd_opts->constraints[mode];
/* (A^T * A) .* (B^T * B) .* .... ) */
mat_form_gram(ws->aTa, ws->gram, ws->nmodes, mode);
if(con->gram_func != NULL) {
con->gram_func(ws->gram->vals, rank, con->data);
}
/* these can be solved optimally without ADMM iterations */
if(con->solve_type == SPLATT_CON_CLOSEDFORM) {
p_constraint_closedform(mats[mode], ws, con);
/* Absorb columns into column_weights if no constraints are applied */
if(ws->unconstrained) {
mat_normalize(mats[mode], column_weights);
}
return 0.;
}
/* Add penalty to diagonal -- value taken from AO-ADMM paper */
val_t const rho = mat_trace(ws->gram) / (val_t) rank;
mat_add_diag(ws->gram, rho);
/* Compute Cholesky factorization to use for forward/backward solves each
* ADMM iteration */
// mat_cholesky(ws->gram);
/* Compute number of chunks */
idx_t num_chunks = 1;
idx_t const chunk_size = cpd_opts->chunk_sizes[mode];
if(con->hints.row_separable && chunk_size > 0) {
num_chunks = (mats[mode]->I / chunk_size);
if(mats[mode]->I % chunk_size > 0) {
++num_chunks;
}
}
idx_t it = 0;
#pragma omp parallel for schedule(dynamic) reduction(+:it) if(num_chunks > 1)
for(idx_t c=0; c < num_chunks; ++c) {
idx_t const start = c * chunk_size;
idx_t const stop = (c == num_chunks-1) ? mats[mode]->I : (c+1)*chunk_size;
idx_t const offset = start * rank;
idx_t const nrows = stop - start;
/* sub-matrix chunks */
matrix_t primal;
matrix_t auxil;
matrix_t dual;
matrix_t mttkrp;
matrix_t init_buf;
/* extract all the workspaces */
mat_fillptr(&primal, mats[mode]->vals + offset, nrows, rank,
mats[mode]->rowmajor);
mat_fillptr(&auxil, ws->auxil->vals + offset, nrows, rank,
ws->auxil->rowmajor);
mat_fillptr(&dual, ws->duals[mode]->vals + offset, nrows, rank,
ws->duals[mode]->rowmajor);
mat_fillptr(&mttkrp, ws->mttkrp_buf->vals + offset, nrows, rank,
ws->mttkrp_buf->rowmajor);
mat_fillptr(&init_buf, ws->mat_init->vals + offset, nrows, rank,
ws->mat_init->rowmajor);
/* should the ADMM kernels parallelize themselves? */
bool const should_parallelize = (num_chunks == 1);
/* Run ADMM until convergence and record total ADMM its per row. */
idx_t const chunk_iters = p_admm_iterate_chunk(&primal, &auxil, &dual,
ws->gram, &mttkrp, &init_buf, mode, con, rho, ws, cpd_opts,
global_opts, should_parallelize);
it += chunk_iters * nrows;
} /* foreach chunk */
/* return average # iterations */
return (val_t) it / (val_t) mats[mode]->I;
}
|
utils.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <complex.h>
#include <math.h>
#include <omp.h>
#include <time.h>
#include <mkl.h>
#include <mkl_types.h>
#include "utils.h"
#define PI 3.14159265358979323846
#define CCONST 0.262465831
#define OPSIZE 9
void affine_transform(double* out, double* op, double* inv) {
//0 1 2 3
//4 5 6 7
//8 9 10 11
//12 13 14 15
double in[4] = {inv[0], inv[1], inv[2], 1};
out[0] = op[0]*in[0] + op[1]*in[1] + op[2]*in[2] + op[3]*in[3];
out[1] = op[4]*in[0] + op[5]*in[1] + op[6]*in[2] + op[7]*in[3];
out[2] = op[8]*in[0] + op[9]*in[1] + op[10]*in[2] + op[11]*in[3];
}
void rotation_transform(double* out, double* op, double* inv) {
double in[3] = {inv[0], inv[1], inv[2]};
out[0] = op[0]*in[0] + op[1]*in[1] + op[2]*in[2];
out[1] = op[3]*in[0] + op[4]*in[1] + op[5]*in[2];
out[2] = op[6]*in[0] + op[7]*in[1] + op[8]*in[2];
}
void vcross(double* res, double* top, double* bottom) {
res[0] = top[1] * bottom[2] - top[2] * bottom[1];
res[1] = top[2] * bottom[0] - top[0] * bottom[2];
res[2] = top[0] * bottom[1] - top[1] * bottom[0];
}
double dot(double* x1, double* x2) {
return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2];
}
double mag(double* x1) {
return pow(dot(x1, x1), 0.5);
}
double determinant(double* m) {
return m[0] * m[4] * m[8]
+ m[1] * m[5] * m[6]
+ m[2] * m[3] * m[7]
- m[2] * m[4] * m[6]
- m[1] * m[3] * m[8]
- m[0] * m[5] * m[7];
}
void min_cart_path(double* coord, double* center, double* lattice, double* path, double* r) {
*r = INFINITY;
double testvec[3]= {0,0,0};
double testdist;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
for (int k = -1; k <= 1; k++) {
testvec[0] = coord[0] + i - center[0];
testvec[1] = coord[1] + j - center[1];
testvec[2] = coord[2] + k - center[2];
frac_to_cartesian(testvec, lattice);
testdist = mag(testvec);
if (testdist < *r) {
path[0] = testvec[0];
path[1] = testvec[1];
path[2] = testvec[2];
*r = testdist;
}
}
}
}
}
void frac_from_spherical(double* ion_frac, double r, double theta, double phi,
double* lattice, double* reclattice, double* result) {
double cart[3];
cart[0] = r * sin(theta) * cos(phi);
cart[1] = r * sin(theta) * sin(phi);
cart[2] = r * cos(theta);
cartesian_to_frac(cart, reclattice);
result[0] = fmod(cart[0] + ion_frac[0], 1.00);
result[1] = fmod(cart[1] + ion_frac[1], 1.00);
result[2] = fmod(cart[2] + ion_frac[2], 1.00);
if (result[0] < 0) result[0] += 1;
if (result[1] < 0) result[1] += 1;
if (result[2] < 0) result[2] += 1;
}
void trilinear_interpolate_values(double complex* x, double* frac, int* fftg, double complex* values) {
//values: c000, c001, c010, c011, c100, c101, c110, c111
int i = (int) (frac[0] * fftg[0]);
int j = (int) (frac[1] * fftg[1]);
int k = (int) (frac[2] * fftg[2]);
int ip = (i+1)%fftg[0];
int jp = (j+1)%fftg[1];
int kp = (k+1)%fftg[2];
int ind[8];
ind[0] = i*fftg[1]*fftg[2] + j*fftg[2] + k;
ind[1] = i*fftg[1]*fftg[2] + j*fftg[2] + kp;
ind[2] = i*fftg[1]*fftg[2] + jp*fftg[2] + k;
ind[3] = i*fftg[1]*fftg[2] + jp*fftg[2] + kp;
ind[4] = ip*fftg[1]*fftg[2] + j*fftg[2] + k;
ind[5] = ip*fftg[1]*fftg[2] + j*fftg[2] + kp;
ind[6] = ip*fftg[1]*fftg[2] + jp*fftg[2] + k;
ind[7] = ip*fftg[1]*fftg[2] + jp*fftg[2] + kp;
for (int n = 0; n < 8; n++) values[n] = x[ind[n]];
}
double complex trilinear_interpolate(double complex* c, double* frac, int* fftg) {
//values: c000, c001, c010, c011, c100, c101, c110, c111
double d[3];
d[0] = fmod(frac[0] * fftg[0], 1.0);
d[1] = fmod(frac[1] * fftg[1], 1.0);
d[2] = fmod(frac[2] * fftg[2], 1.0);
//printf("%lf %lf %lf\n", d[0], d[1], d[2]);
double complex c00 = c[0] * (1-d[0]) + c[4] * d[0];
double complex c01 = c[1] * (1-d[0]) + c[5] * d[0];
double complex c10 = c[2] * (1-d[0]) + c[6] * d[0];
double complex c11 = c[3] * (1-d[0]) + c[7] * d[0];
double complex c0 = c00 * (1-d[1]) + c10 * d[1];
double complex c1 = c01 * (1-d[1]) + c11 * d[1];
return c0 * (1-d[2]) + c1 * d[2];
}
double dist_from_frac(double* coords1, double* coords2, double* lattice) {
double f1 = fmin(fabs(coords1[0]-coords2[0]), 1-fabs(coords1[0]-coords2[0]));
double f2 = fmin(fabs(coords1[1]-coords2[1]), 1-fabs(coords1[1]-coords2[1]));
double f3 = fmin(fabs(coords1[2]-coords2[2]), 1-fabs(coords1[2]-coords2[2]));
return pow(pow(f1*lattice[0]+f2*lattice[3]+f3*lattice[6], 2)
+ pow(f1*lattice[1]+f2*lattice[4]+f3*lattice[7], 2)
+ pow(f1*lattice[2]+f2*lattice[5]+f3*lattice[8], 2), 0.5);
}
void frac_to_cartesian(double* coord, double* lattice) {
double temp[3] = {0,0,0};
temp[0] = coord[0] * lattice[0] + coord[1] * lattice[3] + coord[2] * lattice[6];
temp[1] = coord[0] * lattice[1] + coord[1] * lattice[4] + coord[2] * lattice[7];
temp[2] = coord[0] * lattice[2] + coord[1] * lattice[5] + coord[2] * lattice[8];
coord[0] = temp[0];
coord[1] = temp[1];
coord[2] = temp[2];
}
void cartesian_to_frac(double* coord, double* reclattice) {
double temp[3] = {0,0,0};
temp[0] = coord[0] * reclattice[0] + coord[1] * reclattice[1] + coord[2] * reclattice[2];
temp[1] = coord[0] * reclattice[3] + coord[1] * reclattice[4] + coord[2] * reclattice[5];
temp[2] = coord[0] * reclattice[6] + coord[1] * reclattice[7] + coord[2] * reclattice[8];
coord[0] = temp[0] / 2 / PI;
coord[1] = temp[1] / 2 / PI;
coord[2] = temp[2] / 2 / PI;
}
void free_rayleigh_set_list(rayleigh_set_t* sets, int num_projs) {
for (int i = 0; i < num_projs; i++)
free(sets[i].terms);
free(sets);
}
void free_projection_list(projection_t* projlist, int num) {
for (int i = 0; i < num; i++) {
free(projlist[i].ms);
free(projlist[i].ls);
free(projlist[i].ns);
free(projlist[i].overlaps);
}
free(projlist);
}
void clean_wave_projections(pswf_t* wf) {
for (int i = 0; i < wf->nwk * wf->nspin; i++) {
kpoint_t* kpt = wf->kpts[i];
for (int b = 0; b < kpt->num_bands; b++) {
if (kpt->bands[b]->wave_projections != NULL) {
free_projection_list(kpt->bands[b]->wave_projections, wf->wp_num);
kpt->bands[b]->wave_projections = NULL;
}
}
}
}
void free_kpoint(kpoint_t* kpt, int num_elems, int num_sites, int wp_num, int* num_projs) {
for (int b = 0; b < kpt->num_bands; b++) {
band_t* curr_band = kpt->bands[b];
free(curr_band->Cs);
if (curr_band->projections != NULL) {
free_projection_list(curr_band->projections, num_sites);
}
if (curr_band->wave_projections != NULL) {
free_projection_list(curr_band->wave_projections, wp_num);
}
if (curr_band->up_projections != NULL) {
free_projection_list(curr_band->up_projections, num_sites);
}
if (curr_band->down_projections != NULL) {
free_projection_list(curr_band->down_projections, num_sites);
}
if (curr_band->CRs != NULL) {
mkl_free(curr_band->CRs);
}
if (curr_band->CAs != NULL) {
mkl_free(curr_band->CAs);
}
free(curr_band);
}
if (kpt->expansion != NULL) {
for (int i = 0; i < num_elems; i++)
free_rayleigh_set_list(kpt->expansion[i], num_projs[i]);
free(kpt->expansion);
}
free(kpt->Gs);
free(kpt->bands);
free(kpt->k);
free(kpt);
}
void free_ppot(ppot_t* pp) {
for (int i = 0; i < pp->num_projs; i++) {
free(pp->funcs[i].proj);
free(pp->funcs[i].pswave);
free(pp->funcs[i].aewave);
free(pp->funcs[i].diffwave);
free(pp->funcs[i].kwave);
free(pp->funcs[i].smooth_diffwave);
for (int j = 0; j < 3; j++) {
free(pp->funcs[i].proj_spline[j]);
free(pp->funcs[i].aewave_spline[j]);
free(pp->funcs[i].pswave_spline[j]);
free(pp->funcs[i].diffwave_spline[j]);
free(pp->funcs[i].kwave_spline[j]);
free(pp->funcs[i].smooth_diffwave_spline[j]);
}
free(pp->funcs[i].proj_spline);
free(pp->funcs[i].aewave_spline);
free(pp->funcs[i].pswave_spline);
free(pp->funcs[i].diffwave_spline);
free(pp->funcs[i].kwave_spline);
free(pp->funcs[i].smooth_diffwave_spline);
}
free(pp->funcs);
free(pp->wave_grid);
free(pp->kwave_grid);
free(pp->proj_grid);
free(pp->smooth_grid);
free(pp->pspw_overlap_matrix);
free(pp->aepw_overlap_matrix);
free(pp->diff_overlap_matrix);
}
void free_real_proj(real_proj_t* proj) {
free(proj->values);
}
void free_pswf(pswf_t* wf) {
for (int i = 0; i < wf->nwk * wf->nspin; i++)
free_kpoint(wf->kpts[i], wf->num_elems, wf->num_sites, wf->wp_num, wf->num_projs);
if (wf->overlaps != NULL) {
for (int i = 0; i < wf->num_aug_overlap_sites; i++)
free(wf->overlaps[i]);
free(wf->overlaps);
}
if (wf->num_projs != NULL) {
free(wf->num_projs);
}
free(wf->kpts);
free(wf->G_bounds);
free(wf->lattice);
free(wf->reclattice);
if (wf->pps != NULL) {
free_ppot_list(wf->pps, wf->num_elems);
}
if (wf->dcoords != NULL) {
free(wf->dcoords);
}
if (wf->fftg != NULL) {
free(wf->fftg);
}
free(wf);
}
void free_real_proj_site(real_proj_site_t* site) {
for (int i = 0; i < site->total_projs; i++) {
free_real_proj(site->projs + i);
}
free(site->projs);
free(site->indices);
free(site->coord);
free(site->paths);
}
void free_ptr(void* ptr) {
free(ptr);
}
void free_real_proj_site_list(real_proj_site_t* sites, int length) {
for (int i = 0; i < length; i++) {
free_real_proj_site(sites + i);
}
free(sites);
}
void free_ppot_list(ppot_t* pps, int length) {
for (int i = 0; i < length; i++) {
free_ppot(pps + i);
}
free(pps);
}
int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
int max(int a, int b) {
if (a < b)
return b;
else
return a;
}
double* get_occs(pswf_t* wf) {
kpoint_t** kpts = wf->kpts;
double* occs = (double*) malloc(wf->nwk*wf->nband*wf->nspin*sizeof(double));
CHECK_ALLOCATION(occs);
int NUM_KPTS = wf->nwk * wf->nspin;
for (int kpt_num = 0; kpt_num < NUM_KPTS; kpt_num++) {
for (int band_num = 0; band_num < wf->nband; band_num++) {
occs[band_num*NUM_KPTS+kpt_num] = kpts[kpt_num]->bands[band_num]->occ;
}
}
return occs;
}
int get_nband(pswf_t* wf) {
return wf->nband;
}
int get_nwk(pswf_t* wf) {
return wf->nwk;
}
int get_nspin(pswf_t* wf) {
return wf->nspin;
}
double get_encut(pswf_t* wf) {
return wf->encut;
}
int is_ncl(pswf_t* wf) {
return wf->is_ncl;
}
double get_energy(pswf_t* wf, int band, int kpt, int spin) {
return wf->kpts[kpt+spin*wf->nwk]->bands[band]->energy;
}
double get_occ(pswf_t* wf, int band, int kpt, int spin) {
return wf->kpts[kpt+spin*wf->nwk]->bands[band]->occ;
}
void set_num_sites(pswf_t* wf, int nsites) {
wf->num_sites = nsites;
}
double legendre(int l, int m, double x) {
double total = 0;
if (m < 0) return pow(-1.0, m) * fac(l+m) / fac(l-m) * legendre(l, -m, x);
for (int n = l; n >= 0 && 2*n-l-m >= 0; n--) {
total += pow(x, 2*n-l-m) * fac(2*n) / fac(2*n-l-m) / fac(n) / fac(l-n) * pow(-1, l-n);
}
return total * pow(-1, m) * pow(1 - x * x, m/2.0) / pow(2, l);
}
void legendre_coeff(double* ptr, int l, int m) {
// assumes ptr is cleared
double prefac = pow(-1, m) / pow(2, l);
if (m < 0) {
prefac *= pow(-1.0, m) * fac(l+m) / fac(l-m);
}
m = abs(m);
for (int n = l; n >= 0 && 2*n-l-m >= 0; n--) {
ptr[n] = fac(2*n) / fac(2*n-l-m) / fac(n) / fac(l-n) * pow(-1, l-n) * prefac;
}
}
double* legendre_product(int l1, int l2, int m1, int m2) {
int m = m2 - m1;
int maxl = l1 + l2;
double* lp1 = (double*) calloc((l1+1), sizeof(double));
double* lp2 = (double*) calloc((l2+1), sizeof(double));
double* polynomial = (double*) calloc((maxl+1), sizeof(double));
double* test = (double*) calloc((maxl+1), sizeof(double));
double* coeff = (double*) calloc((maxl+1), sizeof(double));
legendre_coeff(lp1, l1, m1);
legendre_coeff(lp2, l2, m2);
for (int n1 = 0; n1 <= l1; n1++) {
for (int n2 = 0; n2 <= l2; n2++) {
polynomial[n1+n2] += lp1[n1] * lp2[n2];
}
}
for (int l = maxl; l >= abs(m); l--) {
legendre_coeff(test, l, m);
coeff[l] = polynomial[l] / test[l];
for (int lp = abs(m); lp <= maxl; lp++) {
polynomial[lp] -= coeff[l] * test[lp];
test[lp] = 0;
}
}
free(lp1);
free(lp2);
free(polynomial);
free(test);
return coeff;
}
double fac(int n) {
int m = 1;
int t = 1;
while (m <= n) {
t *= m;
m++;
}
return (double)t;
}
double complex Ylm(int l, int m, double theta, double phi) {
//printf("%lf %lf %lf\n", pow((2*l+1)/(4*PI)*fac(l-m)/fac(l+m), 0.5), legendre(l, m, cos(theta)),
// creal(cexp(I*m*phi)));
//double complex multiplier = 0;
//if (m == 0) multiplier = 1;
//else if (m < 0) multiplier = pow(2.0, 0.5) * cos(-m*phi);
//else multiplier = pow(-1,m) * pow(2.0, 0.5) * sin(m*phi);
return pow((2*l+1)/(4*PI)*fac(l-m)/fac(l+m), 0.5) *
legendre(l, m, cos(theta))* cexp(I*m*phi);
}
double complex Ylm2(int l, int m, double costheta, double phi) {
//printf("%lf %lf %lf\n", pow((2*l+1)/(4*PI)*fac(l-m)/fac(l+m), 0.5), legendre(l, m, cos(theta)),
// creal(cexp(I*m*phi)));
//double complex multiplier = 0;
//if (m == 0) multiplier = 1;
//else if (m < 0) multiplier = pow(2.0, 0.5) * cos(-m*phi);
//else multiplier = pow(-1,m) * pow(2.0, 0.5) * sin(m*phi);
return pow((2*l+1)/(4*PI)*fac(l-m)/fac(l+m), 0.5) *
legendre(l, m, costheta) * cexp(I*m*phi);
}
double proj_interpolate(double r, double rmax, int size, double* x,
double* proj, double** proj_spline) {
if (r > x[size-1]) return 0;
if (r < x[0]) return proj[0];
int ind = min((int)(r/rmax*size), size-2);
double rem = r - x[ind];
double radval = proj[ind] + rem * (proj_spline[0][ind] +
rem * (proj_spline[1][ind] +
rem * proj_spline[2][ind]));
return radval;
}
double wave_interpolate(double r, int size, double* x, double* f,
double** wave_spline) {
if (r > x[size-1]) return 0;
if (r < x[0]) return f[0];
int ind = min((int) (log(r/x[0]) / log(x[1]/x[0])), size-2);
double rem = r - x[ind];
return f[ind] + rem * (wave_spline[0][ind] +
rem * (wave_spline[1][ind] +
rem * wave_spline[2][ind]));
}
double complex wave_value(funcset_t funcs, int size, double* x, int m,
double* ion_pos, double* pos, double* lattice) {
double temp[3] = {0,0,0};
double r = 0;
min_cart_path(pos, ion_pos, lattice, temp, &r);
double ae_radial_val = wave_interpolate(r, size, x, funcs.aewave, funcs.aewave_spline);
double ps_radial_val = wave_interpolate(r, size, x, funcs.pswave, funcs.pswave_spline);
double radial_val = (ae_radial_val - ps_radial_val);
if (r < x[0])
radial_val /= x[0];
else
radial_val /= r;
if (r==0) return Ylm(funcs.l, m, 0, 0) * radial_val;
double theta = 0, phi = 0;
theta = acos(temp[2]/r);
if (r - fabs(temp[2]) == 0) phi = 0;
else phi = acos(temp[0] / pow(temp[0]*temp[0] + temp[1]*temp[1], 0.5));
if (temp[1] < 0) phi = 2*PI - phi;
double complex sph_val = Ylm(funcs.l, m, theta, phi);
return radial_val * sph_val;
}
double complex wave_value2(double* x, double* wave, double** spline, int size,
int l, int m, double* pos) {
double r = mag(pos);
double radial_val = wave_interpolate(r, size, x, wave, spline);
if (r < x[0])
radial_val /= x[0];
else
radial_val /= r;
if (r==0) return Ylm(l, m, 0, 0) * radial_val;
double theta = 0, phi = 0;
theta = acos(pos[2]/r);
if (r - fabs(pos[2]) == 0) phi = 0;
else phi = acos(pos[0] / pow(pos[0]*pos[0] + pos[1]*pos[1], 0.5));
if (pos[1] < 0) phi = 2*PI - phi;
double complex sph_val = Ylm(l, m, theta, phi);
return radial_val * sph_val;
}
double complex proj_value_helper(double r, double rmax, int size,
double* temp, double* x, double* f, double** s, int l, int m) {
double radial_val = proj_interpolate(r, rmax, size, x, f, s);
if (r == 0) return Ylm(l, m, 0, 0) * radial_val;
double theta = 0, phi = 0;
theta = acos(temp[2]/r);
if (r - fabs(temp[2]) == 0) phi = 0;
else phi = acos(temp[0] / pow(temp[0]*temp[0] + temp[1]*temp[1], 0.5));
if (temp[1] < 0) phi = 2*PI - phi;
double complex sph_val = Ylm(l, m, theta, phi);
return radial_val * sph_val;
}
double complex proj_value(funcset_t funcs, double* x, int m, double rmax,
int size, double* ion_pos, double* pos, double* lattice) {
double temp[3] = {0,0,0};
double r = 0;
min_cart_path(pos, ion_pos, lattice, temp, &r);
return proj_value_helper(r, rmax, size, temp, x, funcs.proj,
funcs.proj_spline, funcs.l, m);
}
double complex smooth_wave_value(funcset_t funcs, double* x, int m, double rmax,
int size, double* ion_pos, double* pos, double* lattice) {
double temp[3] = {0,0,0};
double r = 0;
min_cart_path(pos, ion_pos, lattice, temp, &r);
return proj_value_helper(r, rmax, size, temp, x, funcs.smooth_diffwave,
funcs.smooth_diffwave_spline, funcs.l, m);
}
void setup_site(real_proj_site_t* sites, ppot_t* pps, int num_sites, int* site_nums,
int* labels, double* coords, double* lattice, int* fftg, int pr0_pw1) {
double vol = determinant(lattice);
for (int s = 0; s < num_sites; s++) {
int i = site_nums[s];
sites[s].index = i;
sites[s].elem = labels[i];
sites[s].gridsize = pps[labels[i]].proj_gridsize;
sites[s].num_projs = pps[labels[i]].num_projs;
if (pr0_pw1) sites[s].rmax = pps[labels[i]].wave_rmax;
else sites[s].rmax = pps[labels[i]].rmax;
sites[s].total_projs = pps[labels[i]].total_projs;
sites[s].num_indices = 0;
sites[s].coord = malloc(3 * sizeof(double));
CHECK_ALLOCATION(sites[s].coord);
sites[s].coord[0] = coords[3*i+0];
sites[s].coord[1] = coords[3*i+1];
sites[s].coord[2] = coords[3*i+2];
sites[s].indices = calloc(pps[labels[i]].num_cart_gridpts, sizeof(int));
CHECK_ALLOCATION(sites[s].indices);
sites[s].projs = (real_proj_t*) malloc(sites[s].total_projs * sizeof(real_proj_t));
int p = 0;
sites[s].paths = malloc(3*pps[labels[i]].num_cart_gridpts * sizeof(double));
CHECK_ALLOCATION(sites[s].paths);
for (int j = 0; j < sites[s].num_projs; j++) {
for (int m = -pps[labels[i]].funcs[j].l; m <= pps[labels[i]].funcs[j].l; m++) {
sites[s].projs[p].l = pps[labels[i]].funcs[j].l;
sites[s].projs[p].m = m;
sites[s].projs[p].func_num = j;
sites[s].projs[p].values = malloc(pps[labels[i]].num_cart_gridpts * sizeof(double complex));
CHECK_ALLOCATION(sites[s].projs[p].values);
p++;
}
}
}
//#pragma omp parallel for
for (int s = 0; s < num_sites; s++) {
int p = site_nums[s];
double res[3] = {0,0,0};
double frac[3] = {0,0,0};
double testcoord[3] = {0,0,0};
vcross(res, lattice+3, lattice+6);
int grid1 = (int) (mag(res) * sites[s].rmax / vol * fftg[0]) + 1;
vcross(res, lattice+0, lattice+6);
int grid2 = (int) (mag(res) * sites[s].rmax / vol * fftg[1]) + 1;
vcross(res, lattice+0, lattice+3);
int grid3 = (int) (mag(res) * sites[s].rmax / vol * fftg[2]) + 1;
int center1 = (int) round(coords[3*p+0] * fftg[0]);
int center2 = (int) round(coords[3*p+1] * fftg[1]);
int center3 = (int) round(coords[3*p+2] * fftg[2]);
int ii=0, jj=0, kk=0;
double R0 = (pps[labels[p]].proj_gridsize-1) * sites[s].rmax
/ pps[labels[s]].proj_gridsize;
for (int i = -grid1 + center1; i <= grid1 + center1; i++) {
for (int j = -grid2 + center2; j <= grid2 + center2; j++) {
for (int k = -grid3 + center3; k <= grid3 + center3; k++) {
testcoord[0] = (double) i / fftg[0] - coords[3*p+0];
testcoord[1] = (double) j / fftg[1] - coords[3*p+1];
testcoord[2] = (double) k / fftg[2] - coords[3*p+2];
frac_to_cartesian(testcoord, lattice);
if (mag(testcoord) < R0) {
ii = (i%fftg[0] + fftg[0]) % fftg[0];
jj = (j%fftg[1] + fftg[1]) % fftg[1];
kk = (k%fftg[2] + fftg[2]) % fftg[2];
frac[0] = (double) ii / fftg[0];
frac[1] = (double) jj / fftg[1];
frac[2] = (double) kk / fftg[2];
sites[s].indices[sites[s].num_indices] = ii*fftg[1]*fftg[2] + jj*fftg[2] + kk;
sites[s].paths[3*sites[s].num_indices+0] = testcoord[0];
sites[s].paths[3*sites[s].num_indices+1] = testcoord[1];
sites[s].paths[3*sites[s].num_indices+2] = testcoord[2];
for (int n = 0; n < sites[s].total_projs; n++) {
if (pr0_pw1)
sites[s].projs[n].values[sites[s].num_indices] = smooth_wave_value(
pps[labels[p]].funcs[sites[s].projs[n].func_num],
pps[labels[p]].smooth_grid, sites[s].projs[n].m, sites[s].rmax,
pps[labels[p]].proj_gridsize, coords+3*p, frac, lattice);
else
sites[s].projs[n].values[sites[s].num_indices] = proj_value(
pps[labels[p]].funcs[sites[s].projs[n].func_num],
pps[labels[p]].proj_grid, sites[s].projs[n].m, sites[s].rmax,
pps[labels[p]].proj_gridsize, coords+3*p, frac, lattice);
}
sites[s].num_indices++;
//if (sites[s].num_indices >= pps[labels[p]].num_cart_gridpts)
// printf("SETUP_SITE ERROR %d %d %d\n", sites[s].num_indices, p, pr0_pw1);
}
}
}
}
}
}
//adapted from VASP source code
double** spline_coeff(double* x, double* y, int N) {
double** coeff = (double**) malloc(3 * sizeof(double*));
CHECK_ALLOCATION(coeff);
coeff[0] = (double*) malloc(N * sizeof(double));
coeff[1] = (double*) malloc(N * sizeof(double));
coeff[2] = (double*) malloc(N * sizeof(double));
CHECK_ALLOCATION(coeff[0]);
CHECK_ALLOCATION(coeff[1]);
CHECK_ALLOCATION(coeff[2]);
double d1p1 = (y[1] - y[0]) / (x[1] - x[0]);
if (d1p1 > 0.99E30) {
coeff[1][0] = 0;
coeff[0][0] = 0;
}
else {
coeff[1][0] = -0.5;
coeff[0][0] = (3 / (x[1] - x[0])) * ((y[1] - y[0]) / (x[1] - x[0]) - d1p1);
}
double s = 0, r = 0;
for (int i = 1; i < N - 1; i++) {
s = (x[i] - x[i-1]) / (x[i+1] - x[i-1]);
r = s * coeff[1][i-1] + 2;
coeff[1][i] = (s - 1) / r;
coeff[0][i] = (6 * ( (y[i+1] - y[i]) / (x[i+1] - x[i]) -
(y[i] - y[i-1]) / (x[i] - x[i-1])) /
(x[i+1] - x[i-1]) - s*coeff[0][i-1]) / r;
}
coeff[0][N-1] = 0;
coeff[1][N-1] = 0;
coeff[2][N-1] = 0;
for (int i = N-2; i >= 0; i--) {
coeff[1][i] = coeff[1][i] * coeff[1][i+1] + coeff[0][i];
}
for (int i = 0; i < N-1; i++) {
s = x[i+1] - x[i];
r = (coeff[1][i+1] - coeff[1][i]) / 6;
coeff[2][i] = r / s;
coeff[1][i] = coeff[1][i] / 2;
coeff[0][i] = (y[i+1]-y[i]) / s - (coeff[1][i] + r) * s;
}
return coeff;
}
double spline_integral(double* x, double* a, double** s, int size) {
double* b = s[0];
double* c = s[1];
double* d = s[2];
double dx = 0;
double integral = 0;
for (int i = 0; i < size - 1; i++) {
dx = x[i+1] - x[i];
integral += dx * (a[i] + dx * (b[i]/2 + dx * (c[i]/3 + d[i]*dx/4)));
}
return integral;
}
void frac_from_index(int index, double* coord, int* fftg) {
int t1 = index / (fftg[1] * fftg[2]);
int t2 = index % (fftg[1] * fftg[2]);
int t3 = t2 % fftg[2];
t2 /= fftg[2];
coord[0] = ((double) t1) / fftg[0];
coord[1] = ((double) t2) / fftg[1];
coord[2] = ((double) t3) / fftg[2];
}
void direction(double* cart, double* dir) {
double theta = 0, phi = 0;
double r = mag(cart);
theta = acos(cart[2]/r);
if (r - fabs(cart[2]) == 0) phi = 0;
else phi = acos(cart[0] / pow(cart[0]*cart[0] + cart[1]*cart[1], 0.5));
if (cart[1] < 0) phi = 2*PI - phi;
dir[0] = theta;
dir[1] = phi;
}
double sph_bessel(double k, double r, int l) {
double x = k * r;
if (l == 0)
return sin(x) / x;
else if (l == 1)
return sin(x) / (x*x) - cos(x) / x;
else if (l == 2)
return (3 / (x*x) -1) * sin(x) / x - 3 * cos(x) / (x*x);
else if (l == 3)
return (15 / (x*x*x) - 6 / x) * sin(x) / x - (15 / (x*x) -1) * cos(x) / x;
else {
printf("ERROR: sph_bessel l too high");
return 0;
}
}
double sbf(double x, int l) {
if (x < 10e-6) {
if (l==0) return 1;
else return 0;
}
double jlm1 = sin(x) / x;
double jl = sin(x) / (x*x) - cos(x) / x;
double jlp1 = 0;
if (l == 0) return jlm1;
if (l == 1) return jl;
for (int ll = 1; ll < l; ll++) {
jlp1 = (2*ll+1)/x*jl - jlm1;
jlm1 = jl;
jl = jlp1;
}
return jlp1;
}
pswf_t* expand_symm_wf(pswf_t* rwf, int num_kpts, int* maps,
double* ops, double* drs, double* kws, int* trs) {
double* lattice = rwf->lattice;
double* reclattice = rwf->reclattice;
pswf_t* wf = (pswf_t*) malloc(sizeof(pswf_t));
wf->num_elems = rwf->num_elems;
wf->num_sites = rwf->num_sites;
wf->pps = NULL;
wf->G_bounds = (int*) malloc(6*sizeof(int));
for (int i = 0; i < 6; i++) {
wf->G_bounds[i] = 0;//rwf->G_bounds[i];
}
wf->kpts = (kpoint_t**) malloc(num_kpts * rwf->nspin * sizeof(kpoint_t*));
wf->nspin = rwf->nspin;
wf->nband = rwf->nband;
wf->nwk = num_kpts;
wf->lattice = (double*) malloc(9*sizeof(double));
wf->reclattice = (double*) malloc(9*sizeof(double));
for (int i = 0; i < 9; i++) {
wf->lattice[i] = lattice[i];
wf->reclattice[i] = reclattice[i];
}
wf->fftg = NULL;
wf->is_ncl = rwf->is_ncl;
wf->num_aug_overlap_sites = 0;
wf->dcoords = NULL;
wf->overlaps = NULL;
wf->num_projs = NULL;
wf->wp_num = 0;
//#pragma omp parallel for
for (int knum = 0; knum < num_kpts * wf->nspin; knum++) {
wf->kpts[knum] = (kpoint_t*) malloc(sizeof(kpoint_t));
double pw[3] = {0,0,0};
int rnum = maps[knum%num_kpts];
int tr = trs[knum%num_kpts];
if (knum >= num_kpts && rwf->nspin ==2) {
rnum += rwf->nwk;
}
kpoint_t* kpt = wf->kpts[knum];
kpoint_t* rkpt = rwf->kpts[rnum];
kpt->up = rkpt->up;
kpt->num_waves = rkpt->num_waves;
kpt->k = (double*) malloc(3 * sizeof(double));
rotation_transform(kpt->k, ops+OPSIZE*(knum%num_kpts), rkpt->k);
if (tr == 1) {
kpt->k[0] *= -1;
kpt->k[1] *= -1;
kpt->k[2] *= -1;
}
double kdiff[3] = {round(kpt->k[0]), round(kpt->k[1]), round(kpt->k[2])};
kpt->k[0] -= kdiff[0];
kpt->k[1] -= kdiff[1];
kpt->k[2] -= kdiff[2];
//printf("OLD KPT %lf %lf %lf\n", rkpt->k[0], rkpt->k[1], rkpt->k[2]);
//printf("NEW KPT %lf %lf %lf\n", kpt->k[0], kpt->k[1], kpt->k[2]);
//kpt->Gs = (int*) malloc(3 * kpt->num_waves * sizeof(int));
kpt->weight = kws[knum%num_kpts];
kpt->num_bands = rkpt->num_bands;
kpt->bands = (band_t**) malloc(kpt->num_bands * sizeof(band_t*));
kpt->expansion = NULL;
int* igall = malloc(3*kpt->num_waves*sizeof(int));
if (igall == NULL) {
ALLOCATION_FAILED();
}
int nb1max = rwf->G_bounds[1] - rwf->G_bounds[0] + 2;
int nb2max = rwf->G_bounds[3] - rwf->G_bounds[2] + 2;
int nb3max = rwf->G_bounds[5] - rwf->G_bounds[4] + 2;
double encut = rwf->encut;
double* b1 = reclattice;
double* b2 = reclattice+3;
double* b3 = reclattice+6;
int ncnt = -1;
for (int ig3 = 0; ig3 <= 2 * nb3max; ig3++) {
int ig3p = ig3;
if (ig3 > nb3max) ig3p = ig3 - 2 * nb3max - 1;
for (int ig2 = 0; ig2 <= 2 * nb2max; ig2++) {
int ig2p = ig2;
if (ig2 > nb2max) ig2p = ig2 - 2 * nb2max - 1;
for (int ig1 = 0; ig1 <= 2 * nb1max; ig1++) {
int ig1p = ig1;
if (ig1 > nb1max) ig1p = ig1 - 2 * nb1max - 1;
double sumkg[3];
for (int j = 0; j < 3; j++) {
sumkg[j] = (kpt->k[0]+ig1p) * b1[j]
+ (kpt->k[1]+ig2p) * b2[j]
+ (kpt->k[2]+ig3p) * b3[j];
}
double gtot = mag(sumkg);
double etot = pow(gtot,2.0) / CCONST;
//printf("%lf %lf\n", etot, gtot);
if (etot <= encut) {
ncnt++;
igall[ncnt*3+0] = ig1p;
igall[ncnt*3+1] = ig2p;
igall[ncnt*3+2] = ig3p;
if (ig1p < wf->G_bounds[0]) wf->G_bounds[0] = ig1p;
else if (ig1p > wf->G_bounds[1]) wf->G_bounds[1] = ig1p;
if (ig2p < wf->G_bounds[2]) wf->G_bounds[2] = ig2p;
else if (ig2p > wf->G_bounds[3]) wf->G_bounds[3] = ig2p;
if (ig3p < wf->G_bounds[4]) wf->G_bounds[4] = ig3p;
else if (ig3p > wf->G_bounds[5]) wf->G_bounds[5] = ig3p;
}
}
}
}
ncnt++;
if (ncnt * 2 == rkpt->num_waves) {
printf("This is an NCL wavefunction!\n");
wf->is_ncl = 1;
for (int iplane = 0; iplane < rkpt->num_waves/2; iplane++) {
igall[3*(rkpt->num_waves/2+iplane)+0] = igall[3*iplane+0];
igall[3*(rkpt->num_waves/2+iplane)+1] = igall[3*iplane+1];
igall[3*(rkpt->num_waves/2+iplane)+2] = igall[3*iplane+2];
}
} else if (ncnt != rkpt->num_waves) {
printf("ERROR %d %d %lf %lf %lf %lf\n", ncnt, kpt->num_waves,
kpt->k[0], kpt->k[1], kpt->k[2], CCONST);
}
kpt->Gs = igall;
int ngx = wf->G_bounds[1] - wf->G_bounds[0] + 1;
int gxmin = wf->G_bounds[0];
int ngy = wf->G_bounds[3] - wf->G_bounds[2] + 1;
int gymin = wf->G_bounds[2];
int ngz = wf->G_bounds[5] - wf->G_bounds[4] + 1;
int gzmin = wf->G_bounds[4];
int* kptinds = (int*) malloc(ngx*ngy*ngz * sizeof(int));
for (int w = 0; w < ngx*ngy*ngz; w++) kptinds[w] = -1;
int gx, gy, gz;
int* gmaps = (int*) malloc(kpt->num_waves * sizeof(int));
float complex* factors = (float complex*) malloc(
kpt->num_waves * sizeof(float complex));
for (int w = 0; w < kpt->num_waves; w++) gmaps[w] = -1;
for (int w = 0; w < rkpt->num_waves; w++) {
gx = kpt->Gs[3*w+0];
gy = kpt->Gs[3*w+1];
gz = kpt->Gs[3*w+2];
kptinds[(gx-gxmin)*ngy*ngz + (gy-gymin)*ngz + (gz-gzmin)] = w;
}
double* dr = drs + 3 * (knum%num_kpts);
double* op = ops+OPSIZE*(knum%num_kpts);
for (int g = 0; g < kpt->num_waves; g++) {
//pw[0] = rkpt->k[0] + rkpt->Gs[3*g+0];
//pw[1] = rkpt->k[1] + rkpt->Gs[3*g+1];
//pw[2] = rkpt->k[2] + rkpt->Gs[3*g+2];
pw[0] = rkpt->Gs[3*g+0];
pw[1] = rkpt->Gs[3*g+1];
pw[2] = rkpt->Gs[3*g+2];
rotation_transform(pw, ops+OPSIZE*(knum%num_kpts), pw);
if (tr == 1) {
pw[0] *= -1;
pw[1] *= -1;
pw[2] *= -1;
}
//pw[0] -= kpt->k[0];
//pw[1] -= kpt->k[1];
//pw[2] -= kpt->k[2];
pw[0] += kdiff[0];
pw[1] += kdiff[1];
pw[2] += kdiff[2];
gx = (int) round(pw[0]);
gy = (int) round(pw[1]);
gz = (int) round(pw[2]);
gmaps[kptinds[(gx-gxmin)*ngy*ngz + (gy-gymin)*ngz + (gz-gzmin)]] = g;
if (tr == 0) {
factors[kptinds[(gx-gxmin)*ngy*ngz + (gy-gymin)*ngz + (gz-gzmin)]] = cexpf(
-I * 2 * PI * (dot(kpt->k, dr) + dot(pw, dr)) );
} else {
factors[kptinds[(gx-gxmin)*ngy*ngz + (gy-gymin)*ngz + (gz-gzmin)]] = cexpf(
I * 2 * PI * (dot(kpt->k, dr) + dot(pw, dr)) );
}
if (kptinds[(gx-gxmin)*ngy*ngz + (gy-gymin)*ngz + (gz-gzmin)] < 0) {
printf("ERROR, BAD PLANE WAVE MAPPING %d %d %d %d %d %d %lf %lf %lf\n %lf %lf %lf %lf %lf %lf %lf %lf %lf\n",
rkpt->Gs[3*g+0], rkpt->Gs[3*g+1], rkpt->Gs[3*g+2], gx, gy, gz,
pw[0], pw[1], pw[2], op[0],op[1],op[2],op[3],op[4],op[5],op[6],op[7],op[8]);
}
//printf("OLD G %d %d %d\n", okpt->Gs[3*g+0], okpt->Gs[3*g+1], okpt->Gs[3*g+2]);
//printf("NEW G %d %d %d\n", kpt->Gs[3*g+0], kpt->Gs[3*g+1], kpt->Gs[3*g+2]);
}
for (int b = 0; b < kpt->num_bands; b++) {
kpt->bands[b] = (band_t*) malloc(sizeof(band_t));
kpt->bands[b]->n = rkpt->bands[b]->n;
kpt->bands[b]->num_waves = rkpt->bands[b]->num_waves;
kpt->bands[b]->occ = rkpt->bands[b]->occ;
kpt->bands[b]->energy = rkpt->bands[b]->energy;
kpt->bands[b]->Cs = (float complex*) malloc(
kpt->num_waves * sizeof(float complex));
kpt->bands[b]->CRs = NULL;
kpt->bands[b]->CAs = NULL;
kpt->bands[b]->projections = NULL;
kpt->bands[b]->up_projections = NULL;
kpt->bands[b]->down_projections = NULL;
kpt->bands[b]->wave_projections = NULL;
//double total = 0;
for (int w = 0; w < kpt->num_waves; w++) {
if (gmaps[w] < 0) {
printf("ERROR, INCOMPLETE PLANE WAVE MAPPING\n");
}
kpt->bands[b]->Cs[w] = factors[w] * rkpt->bands[b]->Cs[gmaps[w]];
if (tr == 1) {
kpt->bands[b]->Cs[w] = conj(kpt->bands[b]->Cs[w]);
}
//total += cabs(cabs(kpt->bands[b]->Cs[w]) - cabs(okpt->bands[b]->Cs[w]));
}
//printf("energies %lf %lf %e\n", kpt->bands[b]->energy, okpt->bands[b]->energy, total);
}
free(gmaps);
free(kptinds);
free(factors);
}
wf->encut = rwf->encut;
return wf;
}
void CHECK_ALLOCATION(void* ptr) {
if (ptr == NULL) {
ALLOCATION_FAILED();
}
}
void ALLOCATION_FAILED(void) {
printf("ALLOCATION FAILED\n");
exit(-1);
}
void CHECK_STATUS(int status) {
if (status != 0) {
printf("ROUTINE FAILED WITH STATUS %d:\n", status);
char* message = DftiErrorMessage(status);
printf("%s\n", message);
exit(-1);
}
}
double* get_smooth_wave(ppot_t* lst, int num) {
//return lst[num].funcs[0].smooth_diffwave;
return lst[num].smooth_grid;
}
|
GB_unaryop__abs_int32_fp32.c | //------------------------------------------------------------------------------
// GB_unaryop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// If this file is in the Generated/ folder, do not edit it (auto-generated).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_iterator.h"
#include "GB_unaryop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB_unop__abs_int32_fp32
// op(A') function: GB_tran__abs_int32_fp32
// C type: int32_t
// A type: float
// cast: int32_t cij ; GB_CAST_SIGNED(cij,aij,32)
// unaryop: cij = GB_IABS (aij)
#define GB_ATYPE \
float
#define GB_CTYPE \
int32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
float aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = GB_IABS (x) ;
// casting
#define GB_CASTING(z, x) \
int32_t z ; GB_CAST_SIGNED(z,x,32) ;
// 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_INT32 || GxB_NO_FP32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__abs_int32_fp32
(
int32_t *restrict Cx,
const float *restrict Ax,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int64_t p = 0 ; p < anz ; p++)
{
GB_CAST_OP (p, p) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_tran__abs_int32_fp32
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
DRB067-restrictpointer1-orig-no.c | /*
Copyright (c) 2017, Lawrence Livermore National Security, LLC.
Produced at the Lawrence Livermore National Laboratory
Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund,
Markus Schordan, and Ian Karlin
(email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov,
schordan1@llnl.gov, karlin1@llnl.gov)
LLNL-CODE-732144
All rights reserved.
This file is part of DataRaceBench. For details, see
https://github.com/LLNL/dataracebench. Please also see the LICENSE file
for our additional BSD notice.
Redistribution and use in source and binary forms, with
or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below)
in the documentation and/or other materials provided with the
distribution.
* Neither the name of the LLNS/LLNL nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL
SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
restrict pointers: no aliasing
Array initialization using assignments.
C99 is needed to compile this code
e.g. gcc -std=c99 -c Stress-1.c
*/
#include <stdlib.h>
typedef double real8;
void foo(real8 * restrict newSxx, real8 * restrict newSyy, int length)
{
int i;
#pragma omp parallel for private(i )
for (i = 0; i <= length - 1; i += 1) {
newSxx[i] = 0.0;
newSyy[i] = 0.0;
}
}
void print(real8 * restrict newSxx, real8 * restrict newSyy, int length)
{
int i;
for (i = 0; i <= length - 1; i += 1) {
printf("%lf %lf\n", newSxx[i], newSyy[i]);
}
}
int main()
{
int length=1000;
real8* newSxx = malloc (length* sizeof (real8));
real8* newSyy = malloc (length* sizeof (real8));
foo(newSxx, newSyy, length);
print(newSxx, newSyy, length);
free (newSxx);
free (newSyy);
return 0;
}
|
GB_unop__identity_fc32_bool.c | //------------------------------------------------------------------------------
// GB_unop: hard-coded functions for each built-in unary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef GBCOMPACT
#include "GB_control.h"
#include "GB_atomics.h"
#include "GB_unop__include.h"
// C=unop(A) is defined by the following types and operators:
// op(A) function: GB (_unop_apply__identity_fc32_bool)
// op(A') function: GB (_unop_tran__identity_fc32_bool)
// C type: GxB_FC32_t
// A type: bool
// cast: GxB_FC32_t cij = GxB_CMPLXF ((float) (aij), 0)
// unaryop: cij = aij
#define GB_ATYPE \
bool
#define GB_CTYPE \
GxB_FC32_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
bool aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
bool aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_BOOL)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_fc32_bool)
(
GxB_FC32_t *Cx, // Cx and Ax may be aliased
const bool *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
bool aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
bool aij = Ax [p] ;
GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_fc32_bool)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
3d25pt.lbpar.c | #include <omp.h>
#include <math.h>
#define ceild(n,d) ceil(((double)(n))/((double)(d)))
#define floord(n,d) floor(((double)(n))/((double)(d)))
#define max(x,y) ((x) > (y)? (x) : (y))
#define min(x,y) ((x) < (y)? (x) : (y))
/*
* Order-2, 3D 25 point stencil
* Adapted from PLUTO and Pochoir test bench
*
* Tareq Malas
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#ifdef LIKWID_PERFMON
#include <likwid.h>
#endif
#include "print_utils.h"
#define TESTS 2
#define MAX(a,b) ((a) > (b) ? a : b)
#define MIN(a,b) ((a) < (b) ? a : b)
#ifndef min
#define min(x,y) ((x) < (y)? (x) : (y))
#endif
/* Subtract the `struct timeval' values X and Y,
* storing the result in RESULT.
*
* Return 1 if the difference is negative, otherwise 0.
*/
int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec)
{
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000)
{
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
* tv_usec is certainly positive.
*/
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
/* Return 1 if result is negative. */
return x->tv_sec < y->tv_sec;
}
int main(int argc, char *argv[])
{
int t, i, j, k, test;
int Nx, Ny, Nz, Nt;
if (argc > 3) {
Nx = atoi(argv[1])+8;
Ny = atoi(argv[2])+8;
Nz = atoi(argv[3])+8;
}
if (argc > 4)
Nt = atoi(argv[4]);
double ****A = (double ****) malloc(sizeof(double***)*2);
double ***roc2 = (double ***) malloc(sizeof(double**));
A[0] = (double ***) malloc(sizeof(double**)*Nz);
A[1] = (double ***) malloc(sizeof(double**)*Nz);
roc2 = (double ***) malloc(sizeof(double**)*Nz);
for(i=0; i<Nz; i++){
A[0][i] = (double**) malloc(sizeof(double*)*Ny);
A[1][i] = (double**) malloc(sizeof(double*)*Ny);
roc2[i] = (double**) malloc(sizeof(double*)*Ny);
for(j=0;j<Ny;j++){
A[0][i][j] = (double*) malloc(sizeof(double)*Nx);
A[1][i][j] = (double*) malloc(sizeof(double)*Nx);
roc2[i][j] = (double*) malloc(sizeof(double)*Nx);
}
}
// tile size information, including extra element to decide the list length
int *tile_size = (int*) malloc(sizeof(int));
tile_size[0] = -1;
// The list is modified here before source-to-source transformations
tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5);
tile_size[0] = 24;
tile_size[1] = 24;
tile_size[2] = 8;
tile_size[3] = 64;
tile_size[4] = -1;
// for timekeeping
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0, min_tdiff=1.e100;
const int BASE = 1024;
// initialize variables
//
srand(42);
for (i = 1; i < Nz; i++) {
for (j = 1; j < Ny; j++) {
for (k = 1; k < Nx; k++) {
A[0][i][j][k] = 1.0 * (rand() % BASE);
roc2[i][j][k] = 2.0 * (rand() % BASE);
}
}
}
#ifdef LIKWID_PERFMON
LIKWID_MARKER_INIT;
#pragma omp parallel
{
LIKWID_MARKER_THREADINIT;
#pragma omp barrier
LIKWID_MARKER_START("calc");
}
#endif
int num_threads = 1;
#if defined(_OPENMP)
num_threads = omp_get_max_threads();
#endif
const double coef0 = -0.28472;
const double coef1 = 0.16000;
const double coef2 = -0.02000;
const double coef3 = 0.00254;
const double coef4 = -0.00018;
for(test=0; test<TESTS; test++){
gettimeofday(&start, 0);
// serial execution - Addition: 6 && Multiplication: 2
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
int t1, t2, t3, t4, t5, t6, t7, t8;
int lb, ub, lbp, ubp, lb2, ub2;
register int lbv, ubv;
/* Start of CLooG code */
if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) {
for (t1=-1;t1<=floord(Nt-1,3);t1++) {
lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6));
ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24));
#pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8)
for (t2=lbp;t2<=ubp;t2++) {
for (t3=max(max(max(0,ceild(3*t1,2)),ceild(24*t2-Nz+5,8)),3*t1-3*t2+1);t3<=min(min(min(floord(4*Nt+Ny-9,8),floord(12*t1+Ny+15,8)),floord(24*t2+Ny+11,8)),floord(24*t1-24*t2+Nz+Ny+13,8));t3++) {
for (t4=max(max(max(max(0,ceild(3*t1-3*t2-6,8)),ceild(3*t1-14,16)),ceild(24*t2-Nz-51,64)),ceild(8*t3-Ny-51,64));t4<=min(min(min(min(floord(4*Nt+Nx-9,64),floord(12*t1+Nx+15,64)),floord(24*t2+Nx+11,64)),floord(8*t3+Nx-5,64)),floord(24*t1-24*t2+Nz+Nx+13,64));t4++) {
for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(64*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),2*t3),Nt-1),3*t1+5),6*t2+4),16*t4+14);t5++) {
for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) {
for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) {
lbv=max(64*t4,4*t5+4);
ubv=min(64*t4+63,4*t5+Nx-5);
#pragma ivdep
#pragma vector always
for (t8=lbv;t8<=ubv;t8++) {
A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((2.0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) - A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (roc2[ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (((((coef0 * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef1 * (((((A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef2 * (((((A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef3 * (((((A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef4 * (((((A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4]) + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])))));;
}
}
}
}
}
}
}
}
}
/* End of CLooG code */
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6);
min_tdiff = MIN(min_tdiff, tdiff);
printf("Rank 0 TEST# %d time: %f\n", test, tdiff);
}
PRINT_RESULTS(4, "constant")
#ifdef LIKWID_PERFMON
#pragma omp parallel
{
LIKWID_MARKER_STOP("calc");
}
LIKWID_MARKER_CLOSE;
#endif
// Free allocated arrays
for(i=0; i<Nz; i++){
for(j=0;j<Ny;j++){
free(A[0][i][j]);
free(A[1][i][j]);
free(roc2[i][j]);
}
free(A[0][i]);
free(A[1][i]);
free(roc2[i]);
}
free(A[0]);
free(A[1]);
free(roc2);
return 0;
}
|
convolution_3x3_pack8.h | // Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt)
{
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
__m256 _bias0 = bias ? _mm256_loadu_ps(bias + p * 8) : _mm256_setzero_ps();
out.fill(_bias0);
for (int q = 0; q < inch; q++)
{
float* outptr = out;
const Mat img0 = bottom_blob.channel(q);
const float* r0 = img0.row(0);
const float* r1 = img0.row(1);
const float* r2 = img0.row(2);
const float* kptr = kernel.channel(p).row(q);
int i = 0;
for (; i < outh; i++)
{
int j = 0;
for (; j + 1 < outw; j += 2)
{
__m256 _sum00 = _mm256_loadu_ps(outptr);
__m256 _sum01 = _mm256_setzero_ps();
__m256 _sum10 = _mm256_loadu_ps(outptr + 8);
__m256 _sum11 = _mm256_setzero_ps();
__m256 _r000 = _mm256_broadcast_ss(r0 + 0);
__m256 _r001 = _mm256_broadcast_ss(r0 + 1);
__m256 _r002 = _mm256_broadcast_ss(r0 + 2);
__m256 _r003 = _mm256_broadcast_ss(r0 + 3);
__m256 _r004 = _mm256_broadcast_ss(r0 + 4);
__m256 _r005 = _mm256_broadcast_ss(r0 + 5);
__m256 _r006 = _mm256_broadcast_ss(r0 + 6);
__m256 _r007 = _mm256_broadcast_ss(r0 + 7);
__m256 _k00 = _mm256_loadu_ps(kptr);
__m256 _k01 = _mm256_loadu_ps(kptr + 8);
__m256 _k02 = _mm256_loadu_ps(kptr + 16);
__m256 _k03 = _mm256_loadu_ps(kptr + 24);
__m256 _k04 = _mm256_loadu_ps(kptr + 32);
__m256 _k05 = _mm256_loadu_ps(kptr + 40);
__m256 _k06 = _mm256_loadu_ps(kptr + 48);
__m256 _k07 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r000, _k00, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r001, _k01, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r002, _k02, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r003, _k03, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r004, _k04, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r005, _k05, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r006, _k06, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r007, _k07, _sum01);
__m256 _r010 = _mm256_broadcast_ss(r0 + 8);
__m256 _r011 = _mm256_broadcast_ss(r0 + 9);
__m256 _r012 = _mm256_broadcast_ss(r0 + 10);
__m256 _r013 = _mm256_broadcast_ss(r0 + 11);
__m256 _r014 = _mm256_broadcast_ss(r0 + 12);
__m256 _r015 = _mm256_broadcast_ss(r0 + 13);
__m256 _r016 = _mm256_broadcast_ss(r0 + 14);
__m256 _r017 = _mm256_broadcast_ss(r0 + 15);
_sum10 = _mm256_comp_fmadd_ps(_r010, _k00, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r011, _k01, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r012, _k02, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r013, _k03, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r014, _k04, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r015, _k05, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r016, _k06, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r017, _k07, _sum11);
__m256 _k10 = _mm256_loadu_ps(kptr);
__m256 _k11 = _mm256_loadu_ps(kptr + 8);
__m256 _k12 = _mm256_loadu_ps(kptr + 16);
__m256 _k13 = _mm256_loadu_ps(kptr + 24);
__m256 _k14 = _mm256_loadu_ps(kptr + 32);
__m256 _k15 = _mm256_loadu_ps(kptr + 40);
__m256 _k16 = _mm256_loadu_ps(kptr + 48);
__m256 _k17 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r010, _k10, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r011, _k11, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r012, _k12, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r013, _k13, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r014, _k14, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r015, _k15, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r016, _k16, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r017, _k17, _sum01);
__m256 _r020 = _mm256_broadcast_ss(r0 + 16);
__m256 _r021 = _mm256_broadcast_ss(r0 + 17);
__m256 _r022 = _mm256_broadcast_ss(r0 + 18);
__m256 _r023 = _mm256_broadcast_ss(r0 + 19);
__m256 _r024 = _mm256_broadcast_ss(r0 + 20);
__m256 _r025 = _mm256_broadcast_ss(r0 + 21);
__m256 _r026 = _mm256_broadcast_ss(r0 + 22);
__m256 _r027 = _mm256_broadcast_ss(r0 + 23);
_sum10 = _mm256_comp_fmadd_ps(_r020, _k10, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r021, _k11, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r022, _k12, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r023, _k13, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r024, _k14, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r025, _k15, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r026, _k16, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r027, _k17, _sum11);
__m256 _k20 = _mm256_loadu_ps(kptr);
__m256 _k21 = _mm256_loadu_ps(kptr + 8);
__m256 _k22 = _mm256_loadu_ps(kptr + 16);
__m256 _k23 = _mm256_loadu_ps(kptr + 24);
__m256 _k24 = _mm256_loadu_ps(kptr + 32);
__m256 _k25 = _mm256_loadu_ps(kptr + 40);
__m256 _k26 = _mm256_loadu_ps(kptr + 48);
__m256 _k27 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r020, _k20, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r021, _k21, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r022, _k22, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r023, _k23, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r024, _k24, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r025, _k25, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r026, _k26, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r027, _k27, _sum01);
__m256 _r030 = _mm256_broadcast_ss(r0 + 24);
__m256 _r031 = _mm256_broadcast_ss(r0 + 25);
__m256 _r032 = _mm256_broadcast_ss(r0 + 26);
__m256 _r033 = _mm256_broadcast_ss(r0 + 27);
__m256 _r034 = _mm256_broadcast_ss(r0 + 28);
__m256 _r035 = _mm256_broadcast_ss(r0 + 29);
__m256 _r036 = _mm256_broadcast_ss(r0 + 30);
__m256 _r037 = _mm256_broadcast_ss(r0 + 31);
_sum10 = _mm256_comp_fmadd_ps(_r030, _k20, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r031, _k21, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r032, _k22, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r033, _k23, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r034, _k24, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r035, _k25, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r036, _k26, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r037, _k27, _sum11);
__m256 _r100 = _mm256_broadcast_ss(r1 + 0);
__m256 _r101 = _mm256_broadcast_ss(r1 + 1);
__m256 _r102 = _mm256_broadcast_ss(r1 + 2);
__m256 _r103 = _mm256_broadcast_ss(r1 + 3);
__m256 _r104 = _mm256_broadcast_ss(r1 + 4);
__m256 _r105 = _mm256_broadcast_ss(r1 + 5);
__m256 _r106 = _mm256_broadcast_ss(r1 + 6);
__m256 _r107 = _mm256_broadcast_ss(r1 + 7);
__m256 _k30 = _mm256_loadu_ps(kptr);
__m256 _k31 = _mm256_loadu_ps(kptr + 8);
__m256 _k32 = _mm256_loadu_ps(kptr + 16);
__m256 _k33 = _mm256_loadu_ps(kptr + 24);
__m256 _k34 = _mm256_loadu_ps(kptr + 32);
__m256 _k35 = _mm256_loadu_ps(kptr + 40);
__m256 _k36 = _mm256_loadu_ps(kptr + 48);
__m256 _k37 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r100, _k30, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r101, _k31, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r102, _k32, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r103, _k33, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r104, _k34, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r105, _k35, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r106, _k36, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r107, _k37, _sum01);
__m256 _r110 = _mm256_broadcast_ss(r1 + 8);
__m256 _r111 = _mm256_broadcast_ss(r1 + 9);
__m256 _r112 = _mm256_broadcast_ss(r1 + 10);
__m256 _r113 = _mm256_broadcast_ss(r1 + 11);
__m256 _r114 = _mm256_broadcast_ss(r1 + 12);
__m256 _r115 = _mm256_broadcast_ss(r1 + 13);
__m256 _r116 = _mm256_broadcast_ss(r1 + 14);
__m256 _r117 = _mm256_broadcast_ss(r1 + 15);
_sum10 = _mm256_comp_fmadd_ps(_r110, _k30, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r111, _k31, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r112, _k32, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r113, _k33, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r114, _k34, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r115, _k35, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r116, _k36, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r117, _k37, _sum11);
__m256 _k40 = _mm256_loadu_ps(kptr);
__m256 _k41 = _mm256_loadu_ps(kptr + 8);
__m256 _k42 = _mm256_loadu_ps(kptr + 16);
__m256 _k43 = _mm256_loadu_ps(kptr + 24);
__m256 _k44 = _mm256_loadu_ps(kptr + 32);
__m256 _k45 = _mm256_loadu_ps(kptr + 40);
__m256 _k46 = _mm256_loadu_ps(kptr + 48);
__m256 _k47 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r110, _k40, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r111, _k41, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r112, _k42, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r113, _k43, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r114, _k44, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r115, _k45, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r116, _k46, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r117, _k47, _sum01);
__m256 _r120 = _mm256_broadcast_ss(r1 + 16);
__m256 _r121 = _mm256_broadcast_ss(r1 + 17);
__m256 _r122 = _mm256_broadcast_ss(r1 + 18);
__m256 _r123 = _mm256_broadcast_ss(r1 + 19);
__m256 _r124 = _mm256_broadcast_ss(r1 + 20);
__m256 _r125 = _mm256_broadcast_ss(r1 + 21);
__m256 _r126 = _mm256_broadcast_ss(r1 + 22);
__m256 _r127 = _mm256_broadcast_ss(r1 + 23);
_sum10 = _mm256_comp_fmadd_ps(_r120, _k40, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r121, _k41, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r122, _k42, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r123, _k43, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r124, _k44, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r125, _k45, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r126, _k46, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r127, _k47, _sum11);
__m256 _k50 = _mm256_loadu_ps(kptr);
__m256 _k51 = _mm256_loadu_ps(kptr + 8);
__m256 _k52 = _mm256_loadu_ps(kptr + 16);
__m256 _k53 = _mm256_loadu_ps(kptr + 24);
__m256 _k54 = _mm256_loadu_ps(kptr + 32);
__m256 _k55 = _mm256_loadu_ps(kptr + 40);
__m256 _k56 = _mm256_loadu_ps(kptr + 48);
__m256 _k57 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r120, _k50, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r121, _k51, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r122, _k52, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r123, _k53, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r124, _k54, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r125, _k55, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r126, _k56, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r127, _k57, _sum01);
__m256 _r130 = _mm256_broadcast_ss(r1 + 24);
__m256 _r131 = _mm256_broadcast_ss(r1 + 25);
__m256 _r132 = _mm256_broadcast_ss(r1 + 26);
__m256 _r133 = _mm256_broadcast_ss(r1 + 27);
__m256 _r134 = _mm256_broadcast_ss(r1 + 28);
__m256 _r135 = _mm256_broadcast_ss(r1 + 29);
__m256 _r136 = _mm256_broadcast_ss(r1 + 30);
__m256 _r137 = _mm256_broadcast_ss(r1 + 31);
_sum10 = _mm256_comp_fmadd_ps(_r130, _k50, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r131, _k51, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r132, _k52, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r133, _k53, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r134, _k54, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r135, _k55, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r136, _k56, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r137, _k57, _sum11);
__m256 _r200 = _mm256_broadcast_ss(r2 + 0);
__m256 _r201 = _mm256_broadcast_ss(r2 + 1);
__m256 _r202 = _mm256_broadcast_ss(r2 + 2);
__m256 _r203 = _mm256_broadcast_ss(r2 + 3);
__m256 _r204 = _mm256_broadcast_ss(r2 + 4);
__m256 _r205 = _mm256_broadcast_ss(r2 + 5);
__m256 _r206 = _mm256_broadcast_ss(r2 + 6);
__m256 _r207 = _mm256_broadcast_ss(r2 + 7);
__m256 _k60 = _mm256_loadu_ps(kptr);
__m256 _k61 = _mm256_loadu_ps(kptr + 8);
__m256 _k62 = _mm256_loadu_ps(kptr + 16);
__m256 _k63 = _mm256_loadu_ps(kptr + 24);
__m256 _k64 = _mm256_loadu_ps(kptr + 32);
__m256 _k65 = _mm256_loadu_ps(kptr + 40);
__m256 _k66 = _mm256_loadu_ps(kptr + 48);
__m256 _k67 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r200, _k60, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r201, _k61, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r202, _k62, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r203, _k63, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r204, _k64, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r205, _k65, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r206, _k66, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r207, _k67, _sum01);
__m256 _r210 = _mm256_broadcast_ss(r2 + 8);
__m256 _r211 = _mm256_broadcast_ss(r2 + 9);
__m256 _r212 = _mm256_broadcast_ss(r2 + 10);
__m256 _r213 = _mm256_broadcast_ss(r2 + 11);
__m256 _r214 = _mm256_broadcast_ss(r2 + 12);
__m256 _r215 = _mm256_broadcast_ss(r2 + 13);
__m256 _r216 = _mm256_broadcast_ss(r2 + 14);
__m256 _r217 = _mm256_broadcast_ss(r2 + 15);
_sum10 = _mm256_comp_fmadd_ps(_r210, _k60, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r211, _k61, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r212, _k62, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r213, _k63, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r214, _k64, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r215, _k65, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r216, _k66, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r217, _k67, _sum11);
__m256 _k70 = _mm256_loadu_ps(kptr);
__m256 _k71 = _mm256_loadu_ps(kptr + 8);
__m256 _k72 = _mm256_loadu_ps(kptr + 16);
__m256 _k73 = _mm256_loadu_ps(kptr + 24);
__m256 _k74 = _mm256_loadu_ps(kptr + 32);
__m256 _k75 = _mm256_loadu_ps(kptr + 40);
__m256 _k76 = _mm256_loadu_ps(kptr + 48);
__m256 _k77 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum00 = _mm256_comp_fmadd_ps(_r210, _k70, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r211, _k71, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r212, _k72, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r213, _k73, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r214, _k74, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r215, _k75, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r216, _k76, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r217, _k77, _sum01);
__m256 _r220 = _mm256_broadcast_ss(r2 + 16);
__m256 _r221 = _mm256_broadcast_ss(r2 + 17);
__m256 _r222 = _mm256_broadcast_ss(r2 + 18);
__m256 _r223 = _mm256_broadcast_ss(r2 + 19);
__m256 _r224 = _mm256_broadcast_ss(r2 + 20);
__m256 _r225 = _mm256_broadcast_ss(r2 + 21);
__m256 _r226 = _mm256_broadcast_ss(r2 + 22);
__m256 _r227 = _mm256_broadcast_ss(r2 + 23);
_sum10 = _mm256_comp_fmadd_ps(_r220, _k70, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r221, _k71, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r222, _k72, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r223, _k73, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r224, _k74, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r225, _k75, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r226, _k76, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r227, _k77, _sum11);
__m256 _k80 = _mm256_loadu_ps(kptr);
__m256 _k81 = _mm256_loadu_ps(kptr + 8);
__m256 _k82 = _mm256_loadu_ps(kptr + 16);
__m256 _k83 = _mm256_loadu_ps(kptr + 24);
__m256 _k84 = _mm256_loadu_ps(kptr + 32);
__m256 _k85 = _mm256_loadu_ps(kptr + 40);
__m256 _k86 = _mm256_loadu_ps(kptr + 48);
__m256 _k87 = _mm256_loadu_ps(kptr + 56);
_sum00 = _mm256_comp_fmadd_ps(_r220, _k80, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r221, _k81, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r222, _k82, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r223, _k83, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r224, _k84, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r225, _k85, _sum01);
_sum00 = _mm256_comp_fmadd_ps(_r226, _k86, _sum00);
_sum01 = _mm256_comp_fmadd_ps(_r227, _k87, _sum01);
__m256 _r230 = _mm256_broadcast_ss(r2 + 24);
__m256 _r231 = _mm256_broadcast_ss(r2 + 25);
__m256 _r232 = _mm256_broadcast_ss(r2 + 26);
__m256 _r233 = _mm256_broadcast_ss(r2 + 27);
__m256 _r234 = _mm256_broadcast_ss(r2 + 28);
__m256 _r235 = _mm256_broadcast_ss(r2 + 29);
__m256 _r236 = _mm256_broadcast_ss(r2 + 30);
__m256 _r237 = _mm256_broadcast_ss(r2 + 31);
_sum10 = _mm256_comp_fmadd_ps(_r230, _k80, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r231, _k81, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r232, _k82, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r233, _k83, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r234, _k84, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r235, _k85, _sum11);
_sum10 = _mm256_comp_fmadd_ps(_r236, _k86, _sum10);
_sum11 = _mm256_comp_fmadd_ps(_r237, _k87, _sum11);
kptr -= 64 * 8;
_sum00 = _mm256_add_ps(_sum00, _sum01);
_sum10 = _mm256_add_ps(_sum10, _sum11);
_mm256_storeu_ps(outptr, _sum00);
_mm256_storeu_ps(outptr + 8, _sum10);
r0 += 16;
r1 += 16;
r2 += 16;
outptr += 16;
}
for (; j < outw; j++)
{
__m256 _sum0 = _mm256_loadu_ps(outptr);
__m256 _sum1 = _mm256_setzero_ps();
__m256 _r000 = _mm256_broadcast_ss(r0 + 0);
__m256 _r001 = _mm256_broadcast_ss(r0 + 1);
__m256 _r002 = _mm256_broadcast_ss(r0 + 2);
__m256 _r003 = _mm256_broadcast_ss(r0 + 3);
__m256 _r004 = _mm256_broadcast_ss(r0 + 4);
__m256 _r005 = _mm256_broadcast_ss(r0 + 5);
__m256 _r006 = _mm256_broadcast_ss(r0 + 6);
__m256 _r007 = _mm256_broadcast_ss(r0 + 7);
__m256 _k00 = _mm256_loadu_ps(kptr);
__m256 _k01 = _mm256_loadu_ps(kptr + 8);
__m256 _k02 = _mm256_loadu_ps(kptr + 16);
__m256 _k03 = _mm256_loadu_ps(kptr + 24);
__m256 _k04 = _mm256_loadu_ps(kptr + 32);
__m256 _k05 = _mm256_loadu_ps(kptr + 40);
__m256 _k06 = _mm256_loadu_ps(kptr + 48);
__m256 _k07 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r000, _k00, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r001, _k01, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r002, _k02, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r003, _k03, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r004, _k04, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r005, _k05, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r006, _k06, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r007, _k07, _sum1);
__m256 _r010 = _mm256_broadcast_ss(r0 + 8);
__m256 _r011 = _mm256_broadcast_ss(r0 + 9);
__m256 _r012 = _mm256_broadcast_ss(r0 + 10);
__m256 _r013 = _mm256_broadcast_ss(r0 + 11);
__m256 _r014 = _mm256_broadcast_ss(r0 + 12);
__m256 _r015 = _mm256_broadcast_ss(r0 + 13);
__m256 _r016 = _mm256_broadcast_ss(r0 + 14);
__m256 _r017 = _mm256_broadcast_ss(r0 + 15);
__m256 _k10 = _mm256_loadu_ps(kptr);
__m256 _k11 = _mm256_loadu_ps(kptr + 8);
__m256 _k12 = _mm256_loadu_ps(kptr + 16);
__m256 _k13 = _mm256_loadu_ps(kptr + 24);
__m256 _k14 = _mm256_loadu_ps(kptr + 32);
__m256 _k15 = _mm256_loadu_ps(kptr + 40);
__m256 _k16 = _mm256_loadu_ps(kptr + 48);
__m256 _k17 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r010, _k10, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r011, _k11, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r012, _k12, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r013, _k13, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r014, _k14, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r015, _k15, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r016, _k16, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r017, _k17, _sum1);
__m256 _r020 = _mm256_broadcast_ss(r0 + 16);
__m256 _r021 = _mm256_broadcast_ss(r0 + 17);
__m256 _r022 = _mm256_broadcast_ss(r0 + 18);
__m256 _r023 = _mm256_broadcast_ss(r0 + 19);
__m256 _r024 = _mm256_broadcast_ss(r0 + 20);
__m256 _r025 = _mm256_broadcast_ss(r0 + 21);
__m256 _r026 = _mm256_broadcast_ss(r0 + 22);
__m256 _r027 = _mm256_broadcast_ss(r0 + 23);
__m256 _k20 = _mm256_loadu_ps(kptr);
__m256 _k21 = _mm256_loadu_ps(kptr + 8);
__m256 _k22 = _mm256_loadu_ps(kptr + 16);
__m256 _k23 = _mm256_loadu_ps(kptr + 24);
__m256 _k24 = _mm256_loadu_ps(kptr + 32);
__m256 _k25 = _mm256_loadu_ps(kptr + 40);
__m256 _k26 = _mm256_loadu_ps(kptr + 48);
__m256 _k27 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r020, _k20, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r021, _k21, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r022, _k22, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r023, _k23, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r024, _k24, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r025, _k25, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r026, _k26, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r027, _k27, _sum1);
__m256 _r100 = _mm256_broadcast_ss(r1 + 0);
__m256 _r101 = _mm256_broadcast_ss(r1 + 1);
__m256 _r102 = _mm256_broadcast_ss(r1 + 2);
__m256 _r103 = _mm256_broadcast_ss(r1 + 3);
__m256 _r104 = _mm256_broadcast_ss(r1 + 4);
__m256 _r105 = _mm256_broadcast_ss(r1 + 5);
__m256 _r106 = _mm256_broadcast_ss(r1 + 6);
__m256 _r107 = _mm256_broadcast_ss(r1 + 7);
__m256 _k30 = _mm256_loadu_ps(kptr);
__m256 _k31 = _mm256_loadu_ps(kptr + 8);
__m256 _k32 = _mm256_loadu_ps(kptr + 16);
__m256 _k33 = _mm256_loadu_ps(kptr + 24);
__m256 _k34 = _mm256_loadu_ps(kptr + 32);
__m256 _k35 = _mm256_loadu_ps(kptr + 40);
__m256 _k36 = _mm256_loadu_ps(kptr + 48);
__m256 _k37 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r100, _k30, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r101, _k31, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r102, _k32, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r103, _k33, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r104, _k34, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r105, _k35, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r106, _k36, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r107, _k37, _sum1);
__m256 _r110 = _mm256_broadcast_ss(r1 + 8);
__m256 _r111 = _mm256_broadcast_ss(r1 + 9);
__m256 _r112 = _mm256_broadcast_ss(r1 + 10);
__m256 _r113 = _mm256_broadcast_ss(r1 + 11);
__m256 _r114 = _mm256_broadcast_ss(r1 + 12);
__m256 _r115 = _mm256_broadcast_ss(r1 + 13);
__m256 _r116 = _mm256_broadcast_ss(r1 + 14);
__m256 _r117 = _mm256_broadcast_ss(r1 + 15);
__m256 _k40 = _mm256_loadu_ps(kptr);
__m256 _k41 = _mm256_loadu_ps(kptr + 8);
__m256 _k42 = _mm256_loadu_ps(kptr + 16);
__m256 _k43 = _mm256_loadu_ps(kptr + 24);
__m256 _k44 = _mm256_loadu_ps(kptr + 32);
__m256 _k45 = _mm256_loadu_ps(kptr + 40);
__m256 _k46 = _mm256_loadu_ps(kptr + 48);
__m256 _k47 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r110, _k40, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r111, _k41, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r112, _k42, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r113, _k43, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r114, _k44, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r115, _k45, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r116, _k46, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r117, _k47, _sum1);
__m256 _r120 = _mm256_broadcast_ss(r1 + 16);
__m256 _r121 = _mm256_broadcast_ss(r1 + 17);
__m256 _r122 = _mm256_broadcast_ss(r1 + 18);
__m256 _r123 = _mm256_broadcast_ss(r1 + 19);
__m256 _r124 = _mm256_broadcast_ss(r1 + 20);
__m256 _r125 = _mm256_broadcast_ss(r1 + 21);
__m256 _r126 = _mm256_broadcast_ss(r1 + 22);
__m256 _r127 = _mm256_broadcast_ss(r1 + 23);
__m256 _k50 = _mm256_loadu_ps(kptr);
__m256 _k51 = _mm256_loadu_ps(kptr + 8);
__m256 _k52 = _mm256_loadu_ps(kptr + 16);
__m256 _k53 = _mm256_loadu_ps(kptr + 24);
__m256 _k54 = _mm256_loadu_ps(kptr + 32);
__m256 _k55 = _mm256_loadu_ps(kptr + 40);
__m256 _k56 = _mm256_loadu_ps(kptr + 48);
__m256 _k57 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r120, _k50, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r121, _k51, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r122, _k52, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r123, _k53, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r124, _k54, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r125, _k55, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r126, _k56, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r127, _k57, _sum1);
__m256 _r200 = _mm256_broadcast_ss(r2 + 0);
__m256 _r201 = _mm256_broadcast_ss(r2 + 1);
__m256 _r202 = _mm256_broadcast_ss(r2 + 2);
__m256 _r203 = _mm256_broadcast_ss(r2 + 3);
__m256 _r204 = _mm256_broadcast_ss(r2 + 4);
__m256 _r205 = _mm256_broadcast_ss(r2 + 5);
__m256 _r206 = _mm256_broadcast_ss(r2 + 6);
__m256 _r207 = _mm256_broadcast_ss(r2 + 7);
__m256 _k60 = _mm256_loadu_ps(kptr);
__m256 _k61 = _mm256_loadu_ps(kptr + 8);
__m256 _k62 = _mm256_loadu_ps(kptr + 16);
__m256 _k63 = _mm256_loadu_ps(kptr + 24);
__m256 _k64 = _mm256_loadu_ps(kptr + 32);
__m256 _k65 = _mm256_loadu_ps(kptr + 40);
__m256 _k66 = _mm256_loadu_ps(kptr + 48);
__m256 _k67 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r200, _k60, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r201, _k61, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r202, _k62, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r203, _k63, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r204, _k64, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r205, _k65, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r206, _k66, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r207, _k67, _sum1);
__m256 _r210 = _mm256_broadcast_ss(r2 + 8);
__m256 _r211 = _mm256_broadcast_ss(r2 + 9);
__m256 _r212 = _mm256_broadcast_ss(r2 + 10);
__m256 _r213 = _mm256_broadcast_ss(r2 + 11);
__m256 _r214 = _mm256_broadcast_ss(r2 + 12);
__m256 _r215 = _mm256_broadcast_ss(r2 + 13);
__m256 _r216 = _mm256_broadcast_ss(r2 + 14);
__m256 _r217 = _mm256_broadcast_ss(r2 + 15);
__m256 _k70 = _mm256_loadu_ps(kptr);
__m256 _k71 = _mm256_loadu_ps(kptr + 8);
__m256 _k72 = _mm256_loadu_ps(kptr + 16);
__m256 _k73 = _mm256_loadu_ps(kptr + 24);
__m256 _k74 = _mm256_loadu_ps(kptr + 32);
__m256 _k75 = _mm256_loadu_ps(kptr + 40);
__m256 _k76 = _mm256_loadu_ps(kptr + 48);
__m256 _k77 = _mm256_loadu_ps(kptr + 56);
kptr += 64;
_sum0 = _mm256_comp_fmadd_ps(_r210, _k70, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r211, _k71, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r212, _k72, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r213, _k73, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r214, _k74, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r215, _k75, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r216, _k76, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r217, _k77, _sum1);
__m256 _r220 = _mm256_broadcast_ss(r2 + 16);
__m256 _r221 = _mm256_broadcast_ss(r2 + 17);
__m256 _r222 = _mm256_broadcast_ss(r2 + 18);
__m256 _r223 = _mm256_broadcast_ss(r2 + 19);
__m256 _r224 = _mm256_broadcast_ss(r2 + 20);
__m256 _r225 = _mm256_broadcast_ss(r2 + 21);
__m256 _r226 = _mm256_broadcast_ss(r2 + 22);
__m256 _r227 = _mm256_broadcast_ss(r2 + 23);
__m256 _k80 = _mm256_loadu_ps(kptr);
__m256 _k81 = _mm256_loadu_ps(kptr + 8);
__m256 _k82 = _mm256_loadu_ps(kptr + 16);
__m256 _k83 = _mm256_loadu_ps(kptr + 24);
__m256 _k84 = _mm256_loadu_ps(kptr + 32);
__m256 _k85 = _mm256_loadu_ps(kptr + 40);
__m256 _k86 = _mm256_loadu_ps(kptr + 48);
__m256 _k87 = _mm256_loadu_ps(kptr + 56);
_sum0 = _mm256_comp_fmadd_ps(_r220, _k80, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r221, _k81, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r222, _k82, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r223, _k83, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r224, _k84, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r225, _k85, _sum1);
_sum0 = _mm256_comp_fmadd_ps(_r226, _k86, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_r227, _k87, _sum1);
kptr -= 64 * 8;
_sum0 = _mm256_add_ps(_sum0, _sum1);
_mm256_storeu_ps(outptr, _sum0);
r0 += 8;
r1 += 8;
r2 += 8;
outptr += 8;
}
r0 += 16;
r1 += 16;
r2 += 16;
}
}
}
}
static void conv3x3s1_winograd64_transform_kernel_pack8_avx(const Mat& kernel, Mat& kernel_tm_pack8, int inch, int outch, const Option& opt)
{
// winograd63 transform kernel
Mat kernel_tm;
kernel_tm.create(8 * 8, inch, outch);
const float ktm[8][3] = {
{1.0f, 0.0f, 0.0f},
{-2.0f / 9, -2.0f / 9, -2.0f / 9},
{-2.0f / 9, 2.0f / 9, -2.0f / 9},
{1.0f / 90, 1.0f / 45, 2.0f / 45},
{1.0f / 90, -1.0f / 45, 2.0f / 45},
{1.0f / 45, 1.0f / 90, 1.0f / 180},
{1.0f / 45, -1.0f / 90, 1.0f / 180},
{0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel, transposed
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[8][3];
for (int i = 0; i < 8; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// v
for (int j = 0; j < 8; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 8; i++)
{
kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// interleave
// src = 64-inch-outch
// dst = 8b-8a-inch/8a-64-outch/8b
kernel_tm_pack8.create(inch / 8, 64, outch / 8, (size_t)4u * 64, 64);
int q = 0;
for (; q + 7 < outch; q += 8)
{
const Mat k0 = kernel_tm.channel(q);
const Mat k1 = kernel_tm.channel(q + 1);
const Mat k2 = kernel_tm.channel(q + 2);
const Mat k3 = kernel_tm.channel(q + 3);
const Mat k4 = kernel_tm.channel(q + 4);
const Mat k5 = kernel_tm.channel(q + 5);
const Mat k6 = kernel_tm.channel(q + 6);
const Mat k7 = kernel_tm.channel(q + 7);
Mat g0 = kernel_tm_pack8.channel(q / 8);
for (int k = 0; k < 64; k++)
{
float* g00 = g0.row(k);
for (int p = 0; p + 7 < inch; p += 8)
{
const float* k00 = k0.row(p);
const float* k01 = k0.row(p + 1);
const float* k02 = k0.row(p + 2);
const float* k03 = k0.row(p + 3);
const float* k04 = k0.row(p + 4);
const float* k05 = k0.row(p + 5);
const float* k06 = k0.row(p + 6);
const float* k07 = k0.row(p + 7);
const float* k10 = k1.row(p);
const float* k11 = k1.row(p + 1);
const float* k12 = k1.row(p + 2);
const float* k13 = k1.row(p + 3);
const float* k14 = k1.row(p + 4);
const float* k15 = k1.row(p + 5);
const float* k16 = k1.row(p + 6);
const float* k17 = k1.row(p + 7);
const float* k20 = k2.row(p);
const float* k21 = k2.row(p + 1);
const float* k22 = k2.row(p + 2);
const float* k23 = k2.row(p + 3);
const float* k24 = k2.row(p + 4);
const float* k25 = k2.row(p + 5);
const float* k26 = k2.row(p + 6);
const float* k27 = k2.row(p + 7);
const float* k30 = k3.row(p);
const float* k31 = k3.row(p + 1);
const float* k32 = k3.row(p + 2);
const float* k33 = k3.row(p + 3);
const float* k34 = k3.row(p + 4);
const float* k35 = k3.row(p + 5);
const float* k36 = k3.row(p + 6);
const float* k37 = k3.row(p + 7);
const float* k40 = k4.row(p);
const float* k41 = k4.row(p + 1);
const float* k42 = k4.row(p + 2);
const float* k43 = k4.row(p + 3);
const float* k44 = k4.row(p + 4);
const float* k45 = k4.row(p + 5);
const float* k46 = k4.row(p + 6);
const float* k47 = k4.row(p + 7);
const float* k50 = k5.row(p);
const float* k51 = k5.row(p + 1);
const float* k52 = k5.row(p + 2);
const float* k53 = k5.row(p + 3);
const float* k54 = k5.row(p + 4);
const float* k55 = k5.row(p + 5);
const float* k56 = k5.row(p + 6);
const float* k57 = k5.row(p + 7);
const float* k60 = k6.row(p);
const float* k61 = k6.row(p + 1);
const float* k62 = k6.row(p + 2);
const float* k63 = k6.row(p + 3);
const float* k64 = k6.row(p + 4);
const float* k65 = k6.row(p + 5);
const float* k66 = k6.row(p + 6);
const float* k67 = k6.row(p + 7);
const float* k70 = k7.row(p);
const float* k71 = k7.row(p + 1);
const float* k72 = k7.row(p + 2);
const float* k73 = k7.row(p + 3);
const float* k74 = k7.row(p + 4);
const float* k75 = k7.row(p + 5);
const float* k76 = k7.row(p + 6);
const float* k77 = k7.row(p + 7);
g00[0] = k00[k];
g00[1] = k10[k];
g00[2] = k20[k];
g00[3] = k30[k];
g00[4] = k40[k];
g00[5] = k50[k];
g00[6] = k60[k];
g00[7] = k70[k];
g00[8] = k01[k];
g00[9] = k11[k];
g00[10] = k21[k];
g00[11] = k31[k];
g00[12] = k41[k];
g00[13] = k51[k];
g00[14] = k61[k];
g00[15] = k71[k];
g00[16] = k02[k];
g00[17] = k12[k];
g00[18] = k22[k];
g00[19] = k32[k];
g00[20] = k42[k];
g00[21] = k52[k];
g00[22] = k62[k];
g00[23] = k72[k];
g00[24] = k03[k];
g00[25] = k13[k];
g00[26] = k23[k];
g00[27] = k33[k];
g00[28] = k43[k];
g00[29] = k53[k];
g00[30] = k63[k];
g00[31] = k73[k];
g00[32] = k04[k];
g00[33] = k14[k];
g00[34] = k24[k];
g00[35] = k34[k];
g00[36] = k44[k];
g00[37] = k54[k];
g00[38] = k64[k];
g00[39] = k74[k];
g00[40] = k05[k];
g00[41] = k15[k];
g00[42] = k25[k];
g00[43] = k35[k];
g00[44] = k45[k];
g00[45] = k55[k];
g00[46] = k65[k];
g00[47] = k75[k];
g00[48] = k06[k];
g00[49] = k16[k];
g00[50] = k26[k];
g00[51] = k36[k];
g00[52] = k46[k];
g00[53] = k56[k];
g00[54] = k66[k];
g00[55] = k76[k];
g00[56] = k07[k];
g00[57] = k17[k];
g00[58] = k27[k];
g00[59] = k37[k];
g00[60] = k47[k];
g00[61] = k57[k];
g00[62] = k67[k];
g00[63] = k77[k];
g00 += 64;
}
}
}
}
static void conv3x3s1_winograd64_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 6n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 5) / 6 * 6;
outh = (outh + 5) / 6 * 6;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator);
// const float itm[8][8] = {
// {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f},
//
// {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f},
// {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f},
//
// {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f},
// {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f},
//
// {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f},
// {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f},
//
// {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f}
// };
// 0 = r00 - r06 + (r04 - r02) * 5.25
// 7 = r07 - r01 + (r03 - r05) * 5.25
// 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05)
// 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05)
// 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2)
// reuse r04 * 1.25
// reuse r03 * 2.5
// 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5)
// 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5)
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
#ifdef _MSC_VER
__declspec(align(32))
#else
__attribute__((aligned(32)))
#endif
float tmp[8][8][8];
// tile
for (int i = 0; i < h_tm / 8; i++)
{
for (int j = 0; j < w_tm / 8; j++)
{
const float* r0 = img0.row(i * 6) + (j * 6) * 8;
for (int m = 0; m < 8; m++)
{
__m256 _r00 = _mm256_load_ps(r0);
__m256 _r01 = _mm256_load_ps(r0 + 8);
__m256 _r02 = _mm256_load_ps(r0 + 16);
__m256 _r03 = _mm256_load_ps(r0 + 24);
__m256 _r04 = _mm256_load_ps(r0 + 32);
__m256 _r05 = _mm256_load_ps(r0 + 40);
__m256 _r06 = _mm256_load_ps(r0 + 48);
__m256 _r07 = _mm256_load_ps(r0 + 56);
__m256 _tmp0m = _mm256_comp_fmadd_ps(_mm256_set1_ps(5.25f), _mm256_sub_ps(_r04, _r02), _mm256_sub_ps(_r00, _r06));
__m256 _tmp7m = _mm256_comp_fmadd_ps(_mm256_set1_ps(5.25f), _mm256_sub_ps(_r03, _r05), _mm256_sub_ps(_r07, _r01));
_mm256_store_ps(tmp[0][m], _tmp0m);
_mm256_store_ps(tmp[7][m], _tmp7m);
__m256 _tmp12a = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.25f), _r04, _mm256_add_ps(_r02, _r06));
__m256 _tmp12b = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.25f), _r03, _mm256_add_ps(_r01, _r05));
__m256 _tmp1m = _mm256_add_ps(_tmp12a, _tmp12b);
__m256 _tmp2m = _mm256_sub_ps(_tmp12a, _tmp12b);
_mm256_store_ps(tmp[1][m], _tmp1m);
_mm256_store_ps(tmp[2][m], _tmp2m);
__m256 _tmp34a = _mm256_comp_fmadd_ps(_mm256_set1_ps(-1.25f), _r04, _mm256_comp_fmadd_ps(_mm256_set1_ps(0.25f), _r02, _r06));
__m256 _tmp34b = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _r05, _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.5f), _r03, _mm256_mul_ps(_r01, _mm256_set1_ps(0.5f))));
__m256 _tmp3m = _mm256_add_ps(_tmp34a, _tmp34b);
__m256 _tmp4m = _mm256_sub_ps(_tmp34a, _tmp34b);
_mm256_store_ps(tmp[3][m], _tmp3m);
_mm256_store_ps(tmp[4][m], _tmp4m);
__m256 _tmp56a = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _mm256_comp_fmadd_ps(_mm256_set1_ps(-1.25f), _r04, _r02), _r06);
__m256 _tmp56b = _mm256_comp_fmadd_ps(_mm256_set1_ps(0.5f), _r05, _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.5f), _r03, _mm256_mul_ps(_r01, _mm256_set1_ps(2.f))));
__m256 _tmp5m = _mm256_add_ps(_tmp56a, _tmp56b);
__m256 _tmp6m = _mm256_sub_ps(_tmp56a, _tmp56b);
_mm256_store_ps(tmp[5][m], _tmp5m);
_mm256_store_ps(tmp[6][m], _tmp6m);
r0 += w * 8;
}
float* r0_tm_0 = (float*)img0_tm + (i * w_tm / 8 + j) * 8;
float* r0_tm_1 = r0_tm_0 + tiles * 8;
float* r0_tm_2 = r0_tm_0 + tiles * 16;
float* r0_tm_3 = r0_tm_0 + tiles * 24;
float* r0_tm_4 = r0_tm_0 + tiles * 32;
float* r0_tm_5 = r0_tm_0 + tiles * 40;
float* r0_tm_6 = r0_tm_0 + tiles * 48;
float* r0_tm_7 = r0_tm_0 + tiles * 56;
for (int m = 0; m < 8; m++)
{
__m256 _tmp00 = _mm256_load_ps(tmp[m][0]);
__m256 _tmp01 = _mm256_load_ps(tmp[m][1]);
__m256 _tmp02 = _mm256_load_ps(tmp[m][2]);
__m256 _tmp03 = _mm256_load_ps(tmp[m][3]);
__m256 _tmp04 = _mm256_load_ps(tmp[m][4]);
__m256 _tmp05 = _mm256_load_ps(tmp[m][5]);
__m256 _tmp06 = _mm256_load_ps(tmp[m][6]);
__m256 _tmp07 = _mm256_load_ps(tmp[m][7]);
__m256 _r0tm0 = _mm256_comp_fmadd_ps(_mm256_set1_ps(5.25f), _mm256_sub_ps(_tmp04, _tmp02), _mm256_sub_ps(_tmp00, _tmp06));
__m256 _r0tm7 = _mm256_comp_fmadd_ps(_mm256_set1_ps(5.25f), _mm256_sub_ps(_tmp03, _tmp05), _mm256_sub_ps(_tmp07, _tmp01));
__m256 _tmp12a = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.25f), _tmp04, _mm256_add_ps(_tmp02, _tmp06));
__m256 _tmp12b = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.25f), _tmp03, _mm256_add_ps(_tmp01, _tmp05));
__m256 _r0tm1 = _mm256_add_ps(_tmp12a, _tmp12b);
__m256 _r0tm2 = _mm256_sub_ps(_tmp12a, _tmp12b);
__m256 _tmp34a = _mm256_comp_fmadd_ps(_mm256_set1_ps(-1.25f), _tmp04, _mm256_comp_fmadd_ps(_mm256_set1_ps(0.25f), _tmp02, _tmp06));
__m256 _tmp34b = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp05, _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.5f), _tmp03, _mm256_mul_ps(_tmp01, _mm256_set1_ps(0.5f))));
__m256 _r0tm3 = _mm256_add_ps(_tmp34a, _tmp34b);
__m256 _r0tm4 = _mm256_sub_ps(_tmp34a, _tmp34b);
__m256 _tmp56a = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _mm256_comp_fmadd_ps(_mm256_set1_ps(-1.25f), _tmp04, _tmp02), _tmp06);
__m256 _tmp56b = _mm256_comp_fmadd_ps(_mm256_set1_ps(0.5f), _tmp05, _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.5f), _tmp03, _mm256_mul_ps(_tmp01, _mm256_set1_ps(2.f))));
__m256 _r0tm5 = _mm256_add_ps(_tmp56a, _tmp56b);
__m256 _r0tm6 = _mm256_sub_ps(_tmp56a, _tmp56b);
_mm256_store_ps(r0_tm_0, _r0tm0);
_mm256_store_ps(r0_tm_1, _r0tm1);
_mm256_store_ps(r0_tm_2, _r0tm2);
_mm256_store_ps(r0_tm_3, _r0tm3);
_mm256_store_ps(r0_tm_4, _r0tm4);
_mm256_store_ps(r0_tm_5, _r0tm5);
_mm256_store_ps(r0_tm_6, _r0tm6);
_mm256_store_ps(r0_tm_7, _r0tm7);
r0_tm_0 += tiles * 64;
r0_tm_1 += tiles * 64;
r0_tm_2 += tiles * 64;
r0_tm_3 += tiles * 64;
r0_tm_4 += tiles * 64;
r0_tm_5 += tiles * 64;
r0_tm_6 += tiles * 64;
r0_tm_7 += tiles * 64;
}
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = h_tm / 8 * w_tm / 8;
Mat bottom_blob_tm2;
if (tiles >= 12)
bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 8)
bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator);
else if (tiles >= 2)
bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r = 0; r < 64; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 11 < tiles; i += 12)
{
float* tmpptr = tm2.row(i / 12);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x12
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 16);
__m256 _r3 = _mm256_load_ps(r0 + 24);
__m256 _r4 = _mm256_load_ps(r0 + 32);
__m256 _r5 = _mm256_load_ps(r0 + 40);
__m256 _r6 = _mm256_load_ps(r0 + 48);
__m256 _r7 = _mm256_load_ps(r0 + 56);
__m256 _r8 = _mm256_load_ps(r0 + 64);
__m256 _r9 = _mm256_load_ps(r0 + 72);
__m256 _ra = _mm256_load_ps(r0 + 80);
__m256 _rb = _mm256_load_ps(r0 + 88);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5);
__m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5);
__m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7);
__m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7);
__m256 _tmp8 = _mm256_unpacklo_ps(_r8, _r9);
__m256 _tmp9 = _mm256_unpackhi_ps(_r8, _r9);
__m256 _tmpa = _mm256_unpacklo_ps(_ra, _rb);
__m256 _tmpb = _mm256_unpackhi_ps(_ra, _rb);
__m256 _tmpc = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpd = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpe = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpf = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpg = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmph = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpi = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpj = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpk = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpl = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpm = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpn = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 2, 0, 0));
_r3 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 2, 0, 0));
_r4 = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 2, 0, 0));
_r5 = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 2, 0, 0));
_r6 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 3, 0, 1));
_r7 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 3, 0, 1));
_r8 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 3, 0, 1));
_r9 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 3, 0, 1));
_ra = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 3, 0, 1));
_rb = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
_mm256_store_ps(tmpptr + 8 * 4, _r4);
_mm256_store_ps(tmpptr + 8 * 5, _r5);
_mm256_store_ps(tmpptr + 8 * 6, _r6);
_mm256_store_ps(tmpptr + 8 * 7, _r7);
_mm256_store_ps(tmpptr + 8 * 8, _r8);
_mm256_store_ps(tmpptr + 8 * 9, _r9);
_mm256_store_ps(tmpptr + 8 * 10, _ra);
_mm256_store_ps(tmpptr + 8 * 11, _rb);
tmpptr += 96;
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i + 7 < tiles; i += 8)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x8
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r3 = _mm256_load_ps(r0 + 8 * 3);
__m256 _r4 = _mm256_load_ps(r0 + 8 * 4);
__m256 _r5 = _mm256_load_ps(r0 + 8 * 5);
__m256 _r6 = _mm256_load_ps(r0 + 8 * 6);
__m256 _r7 = _mm256_load_ps(r0 + 8 * 7);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5);
__m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5);
__m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7);
__m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7);
__m256 _tmp8 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp9 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpa = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpb = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpc = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpd = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpe = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpf = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 2, 0, 0));
_r3 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 2, 0, 0));
_r4 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 3, 0, 1));
_r5 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 3, 0, 1));
_r6 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 3, 0, 1));
_r7 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
_mm256_store_ps(tmpptr + 8 * 4, _r4);
_mm256_store_ps(tmpptr + 8 * 5, _r5);
_mm256_store_ps(tmpptr + 8 * 6, _r6);
_mm256_store_ps(tmpptr + 8 * 7, _r7);
tmpptr += 64;
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i + 3 < tiles; i += 4)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x4
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r3 = _mm256_load_ps(r0 + 8 * 3);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp5 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmp6 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp7 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 3, 0, 1));
_r3 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
tmpptr += 32;
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i + 1 < tiles; i += 2)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x2
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
_r0 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
tmpptr += 16;
r0 += bottom_blob_tm.cstep * 8;
}
}
for (; i < tiles; i++)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
__m256 _val = _mm256_load_ps(r0);
_mm256_store_ps(tmpptr, _val);
tmpptr += 8;
r0 += bottom_blob_tm.cstep * 8;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(tiles, 64, outch, elemsize, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* output0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p);
for (int r = 0; r < 64; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
for (; i + 11 < tiles; i += 12)
{
const float* r0 = bb2.row(i / 12);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
__m256 _sum4 = _mm256_setzero_ps();
__m256 _sum5 = _mm256_setzero_ps();
__m256 _sum6 = _mm256_setzero_ps();
__m256 _sum7 = _mm256_setzero_ps();
__m256 _sum8 = _mm256_setzero_ps();
__m256 _sum9 = _mm256_setzero_ps();
__m256 _suma = _mm256_setzero_ps();
__m256 _sumb = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
__m256 _val4 = _mm256_broadcast_ss(r0 + 4);
__m256 _val5 = _mm256_broadcast_ss(r0 + 5);
_sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4);
_sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5);
__m256 _val6 = _mm256_broadcast_ss(r0 + 6);
__m256 _val7 = _mm256_broadcast_ss(r0 + 7);
_sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6);
_sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7);
__m256 _val8 = _mm256_broadcast_ss(r0 + 8);
__m256 _val9 = _mm256_broadcast_ss(r0 + 9);
_sum8 = _mm256_comp_fmadd_ps(_val8, _w0, _sum8);
_sum9 = _mm256_comp_fmadd_ps(_val9, _w0, _sum9);
__m256 _vala = _mm256_broadcast_ss(r0 + 10);
__m256 _valb = _mm256_broadcast_ss(r0 + 11);
_suma = _mm256_comp_fmadd_ps(_vala, _w0, _suma);
_sumb = _mm256_comp_fmadd_ps(_valb, _w0, _sumb);
r0 += 12;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
_mm256_store_ps(output0_tm + 8 * 4, _sum4);
_mm256_store_ps(output0_tm + 8 * 5, _sum5);
_mm256_store_ps(output0_tm + 8 * 6, _sum6);
_mm256_store_ps(output0_tm + 8 * 7, _sum7);
_mm256_store_ps(output0_tm + 8 * 8, _sum8);
_mm256_store_ps(output0_tm + 8 * 9, _sum9);
_mm256_store_ps(output0_tm + 8 * 10, _suma);
_mm256_store_ps(output0_tm + 8 * 11, _sumb);
output0_tm += 8 * 12;
}
for (; i + 7 < tiles; i += 8)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
__m256 _sum4 = _mm256_setzero_ps();
__m256 _sum5 = _mm256_setzero_ps();
__m256 _sum6 = _mm256_setzero_ps();
__m256 _sum7 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
__m256 _val4 = _mm256_broadcast_ss(r0 + 4);
__m256 _val5 = _mm256_broadcast_ss(r0 + 5);
_sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4);
_sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5);
__m256 _val6 = _mm256_broadcast_ss(r0 + 6);
__m256 _val7 = _mm256_broadcast_ss(r0 + 7);
_sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6);
_sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7);
r0 += 8;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
_mm256_store_ps(output0_tm + 8 * 4, _sum4);
_mm256_store_ps(output0_tm + 8 * 5, _sum5);
_mm256_store_ps(output0_tm + 8 * 6, _sum6);
_mm256_store_ps(output0_tm + 8 * 7, _sum7);
output0_tm += 8 * 8;
}
for (; i + 3 < tiles; i += 4)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
r0 += 4;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
output0_tm += 8 * 4;
}
for (; i + 1 < tiles; i += 2)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
r0 += 2;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
output0_tm += 8 * 2;
}
for (; i < tiles; i++)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
r0 += 1;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
output0_tm += 8;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator);
}
{
// const float otm[6][8] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f}
// };
// 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32
// 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16
// 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8
// 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4
// 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2
// 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6)
int w_tm = outw / 6 * 8;
int h_tm = outh / 6 * 8;
const int tiles = w_tm / 8 * h_tm / 8;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
// const float bias0 = bias ? bias[p] : 0.f;
__m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + p * 8) : _mm256_setzero_ps();
#ifdef _MSC_VER
__declspec(align(32))
#else
__attribute__((aligned(32)))
#endif
float tmp[6][8][8];
// tile
for (int i = 0; i < outh / 6; i++)
{
for (int j = 0; j < outw / 6; j++)
{
// top_blob_tm.create(tiles, 64, outch, elemsize, elempack);
const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm / 8 + j) * 8;
const float* output0_tm_1 = output0_tm_0 + tiles * 8;
const float* output0_tm_2 = output0_tm_0 + tiles * 16;
const float* output0_tm_3 = output0_tm_0 + tiles * 24;
const float* output0_tm_4 = output0_tm_0 + tiles * 32;
const float* output0_tm_5 = output0_tm_0 + tiles * 40;
const float* output0_tm_6 = output0_tm_0 + tiles * 48;
const float* output0_tm_7 = output0_tm_0 + tiles * 56;
float* output0 = out0.row(i * 6) + (j * 6) * 8;
// TODO neon optimize
for (int m = 0; m < 8; m++)
{
__m256 _out0tm0 = _mm256_load_ps(output0_tm_0);
__m256 _out0tm1 = _mm256_load_ps(output0_tm_1);
__m256 _out0tm2 = _mm256_load_ps(output0_tm_2);
__m256 _out0tm3 = _mm256_load_ps(output0_tm_3);
__m256 _out0tm4 = _mm256_load_ps(output0_tm_4);
__m256 _out0tm5 = _mm256_load_ps(output0_tm_5);
__m256 _out0tm6 = _mm256_load_ps(output0_tm_6);
__m256 _out0tm7 = _mm256_load_ps(output0_tm_7);
__m256 _tmp024a = _mm256_add_ps(_out0tm1, _out0tm2);
__m256 _tmp135a = _mm256_sub_ps(_out0tm1, _out0tm2);
__m256 _tmp024b = _mm256_add_ps(_out0tm3, _out0tm4);
__m256 _tmp135b = _mm256_sub_ps(_out0tm3, _out0tm4);
__m256 _tmp024c = _mm256_add_ps(_out0tm5, _out0tm6);
__m256 _tmp135c = _mm256_sub_ps(_out0tm5, _out0tm6);
__m256 _tmp0m = _mm256_add_ps(_mm256_add_ps(_out0tm0, _tmp024a), _mm256_comp_fmadd_ps(_mm256_set1_ps(32.f), _tmp024c, _tmp024b));
__m256 _tmp2m = _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp024c, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp024b, _tmp024a));
__m256 _tmp4m = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp024c, _mm256_comp_fmadd_ps(_mm256_set1_ps(16.f), _tmp024b, _tmp024a));
_mm256_store_ps(tmp[0][m], _tmp0m);
_mm256_store_ps(tmp[2][m], _tmp2m);
_mm256_store_ps(tmp[4][m], _tmp4m);
__m256 _tmp1m = _mm256_comp_fmadd_ps(_mm256_set1_ps(16.f), _tmp135c, _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp135b, _tmp135a));
__m256 _tmp3m = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp135c, _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp135b, _tmp135a));
__m256 _tmp5m = _mm256_add_ps(_mm256_add_ps(_out0tm7, _tmp135a), _mm256_comp_fmadd_ps(_mm256_set1_ps(32.f), _tmp135b, _tmp135c));
_mm256_store_ps(tmp[1][m], _tmp1m);
_mm256_store_ps(tmp[3][m], _tmp3m);
_mm256_store_ps(tmp[5][m], _tmp5m);
output0_tm_0 += tiles * 64;
output0_tm_1 += tiles * 64;
output0_tm_2 += tiles * 64;
output0_tm_3 += tiles * 64;
output0_tm_4 += tiles * 64;
output0_tm_5 += tiles * 64;
output0_tm_6 += tiles * 64;
output0_tm_7 += tiles * 64;
}
for (int m = 0; m < 6; m++)
{
__m256 _tmp00 = _mm256_load_ps(tmp[m][0]);
__m256 _tmp01 = _mm256_load_ps(tmp[m][1]);
__m256 _tmp02 = _mm256_load_ps(tmp[m][2]);
__m256 _tmp03 = _mm256_load_ps(tmp[m][3]);
__m256 _tmp04 = _mm256_load_ps(tmp[m][4]);
__m256 _tmp05 = _mm256_load_ps(tmp[m][5]);
__m256 _tmp06 = _mm256_load_ps(tmp[m][6]);
__m256 _tmp07 = _mm256_load_ps(tmp[m][7]);
__m256 _tmp024a = _mm256_add_ps(_tmp01, _tmp02);
__m256 _tmp135a = _mm256_sub_ps(_tmp01, _tmp02);
__m256 _tmp024b = _mm256_add_ps(_tmp03, _tmp04);
__m256 _tmp135b = _mm256_sub_ps(_tmp03, _tmp04);
__m256 _tmp024c = _mm256_add_ps(_tmp05, _tmp06);
__m256 _tmp135c = _mm256_sub_ps(_tmp05, _tmp06);
__m256 _out00 = _mm256_add_ps(_bias0, _mm256_add_ps(_mm256_add_ps(_tmp00, _tmp024a), _mm256_comp_fmadd_ps(_mm256_set1_ps(32.f), _tmp024c, _tmp024b)));
__m256 _out02 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp024c, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp024b, _tmp024a)));
__m256 _out04 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp024c, _mm256_comp_fmadd_ps(_mm256_set1_ps(16.f), _tmp024b, _tmp024a)));
_mm256_store_ps(output0, _out00);
_mm256_store_ps(output0 + 16, _out02);
_mm256_store_ps(output0 + 32, _out04);
__m256 _out01 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(16.f), _tmp135c, _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp135b, _tmp135a)));
__m256 _out03 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp135c, _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp135b, _tmp135a)));
__m256 _out05 = _mm256_add_ps(_bias0, _mm256_add_ps(_mm256_add_ps(_tmp07, _tmp135a), _mm256_comp_fmadd_ps(_mm256_set1_ps(32.f), _tmp135b, _tmp135c)));
_mm256_store_ps(output0 + 8, _out01);
_mm256_store_ps(output0 + 24, _out03);
_mm256_store_ps(output0 + 40, _out05);
output0 += outw * 8;
}
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
static void conv3x3s1_winograd42_transform_kernel_pack8_avx(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch, const Option& opt)
{
// winograd42 transform kernel
Mat kernel_tm(6 * 6, inch, outch);
const float ktm[6][3] = {
{1.0f / 4, 0.0f, 0.0f},
{-1.0f / 6, -1.0f / 6, -1.0f / 6},
{-1.0f / 6, 1.0f / 6, -1.0f / 6},
{1.0f / 24, 1.0f / 12, 1.0f / 6},
{1.0f / 24, -1.0f / 12, 1.0f / 6},
{0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
for (int q = 0; q < inch; q++)
{
const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[6][3];
for (int i = 0; i < 6; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j = 0; j < 6; j++)
{
float* tmpp = &tmp[j][0];
for (int i = 0; i < 6; i++)
{
kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
// interleave
// src = 36-inch-outch
// dst = 8b-8a-inch/8a-36-outch/8b
kernel_tm_pack4.create(inch / 8, 36, outch / 8, (size_t)4u * 64, 64);
for (int q = 0; q + (8 - 1) < outch; q += 8)
{
Mat g0 = kernel_tm_pack4.channel(q / 8);
for (int k = 0; k < 36; k++)
{
float* g00 = g0.row<float>(k);
for (int p = 0; p + (8 - 1) < inch; p += 8)
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
const float* k00 = kernel_tm.channel(q + j).row(p + i);
g00[0] = k00[k];
g00++;
}
}
}
}
}
}
static void conv3x3s1_winograd42_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int elempack = bottom_blob.elempack;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 4n+2
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 3) / 4 * 4;
outh = (outh + 3) / 4 * 4;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = w_tm / 6 * h_tm / 6;
bottom_blob_tm.create(tiles, 36, inch, 4u * elempack, elempack, opt.workspace_allocator);
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r04 + r03
// 2 = 4 * (r01 - r02) + r04 - r03
// 3 = -2 * (r01 - r03) + r04 - r02
// 4 = 2 * (r01 - r03) + r04 - r02
// 5 = 4 * r01 - 5 * r03 + r05
#pragma omp parallel for num_threads(opt.num_threads)
for (int q = 0; q < inch; q++)
{
const Mat img0 = bottom_blob_bordered.channel(q);
Mat img0_tm = bottom_blob_tm.channel(q);
#ifdef _MSC_VER
__declspec(align(32))
#else
__attribute__((aligned(32)))
#endif
float tmp[6][6][8];
// tile
for (int i = 0; i < h_tm / 6; i++)
{
for (int j = 0; j < w_tm / 6; j++)
{
const float* r0 = img0.row(i * 4) + (j * 4) * 8;
for (int m = 0; m < 6; m++)
{
__m256 _r00 = _mm256_load_ps(r0);
__m256 _r01 = _mm256_load_ps(r0 + 8);
__m256 _r02 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r03 = _mm256_load_ps(r0 + 8 * 3);
__m256 _r04 = _mm256_load_ps(r0 + 8 * 4);
__m256 _r05 = _mm256_load_ps(r0 + 8 * 5);
__m256 _tmp0m = _mm256_comp_fmadd_ps(_mm256_set1_ps(-5.f), _r02, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _r00, _r04));
__m256 _tmp1m = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.f), _mm256_add_ps(_r01, _r02), _mm256_add_ps(_r04, _r03));
__m256 _tmp2m = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _mm256_sub_ps(_r01, _r02), _mm256_sub_ps(_r04, _r03));
__m256 _tmp3m = _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.f), _mm256_sub_ps(_r01, _r03), _mm256_sub_ps(_r04, _r02));
__m256 _tmp4m = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _mm256_sub_ps(_r01, _r03), _mm256_sub_ps(_r04, _r02));
__m256 _tmp5m = _mm256_comp_fmadd_ps(_mm256_set1_ps(-5.f), _r03, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _r01, _r05));
_mm256_store_ps(tmp[0][m], _tmp0m);
_mm256_store_ps(tmp[1][m], _tmp1m);
_mm256_store_ps(tmp[2][m], _tmp2m);
_mm256_store_ps(tmp[3][m], _tmp3m);
_mm256_store_ps(tmp[4][m], _tmp4m);
_mm256_store_ps(tmp[5][m], _tmp5m);
r0 += w * 8;
}
float* r0_tm_0 = (float*)img0_tm + (i * w_tm / 6 + j) * 8;
float* r0_tm_1 = r0_tm_0 + tiles * 8;
float* r0_tm_2 = r0_tm_0 + tiles * 8 * 2;
float* r0_tm_3 = r0_tm_0 + tiles * 8 * 3;
float* r0_tm_4 = r0_tm_0 + tiles * 8 * 4;
float* r0_tm_5 = r0_tm_0 + tiles * 8 * 5;
for (int m = 0; m < 6; m++)
{
__m256 _tmp00 = _mm256_load_ps(tmp[m][0]);
__m256 _tmp01 = _mm256_load_ps(tmp[m][1]);
__m256 _tmp02 = _mm256_load_ps(tmp[m][2]);
__m256 _tmp03 = _mm256_load_ps(tmp[m][3]);
__m256 _tmp04 = _mm256_load_ps(tmp[m][4]);
__m256 _tmp05 = _mm256_load_ps(tmp[m][5]);
__m256 _r0tm0 = _mm256_comp_fmadd_ps(_mm256_set1_ps(-5.f), _tmp02, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp00, _tmp04));
__m256 _r0tm1 = _mm256_comp_fmadd_ps(_mm256_set1_ps(-4.f), _mm256_add_ps(_tmp01, _tmp02), _mm256_add_ps(_tmp04, _tmp03));
__m256 _r0tm2 = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _mm256_sub_ps(_tmp01, _tmp02), _mm256_sub_ps(_tmp04, _tmp03));
__m256 _r0tm3 = _mm256_comp_fmadd_ps(_mm256_set1_ps(-2.f), _mm256_sub_ps(_tmp01, _tmp03), _mm256_sub_ps(_tmp04, _tmp02));
__m256 _r0tm4 = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _mm256_sub_ps(_tmp01, _tmp03), _mm256_sub_ps(_tmp04, _tmp02));
__m256 _r0tm5 = _mm256_comp_fmadd_ps(_mm256_set1_ps(-5.f), _tmp03, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp01, _tmp05));
_mm256_store_ps(r0_tm_0, _r0tm0);
_mm256_store_ps(r0_tm_1, _r0tm1);
_mm256_store_ps(r0_tm_2, _r0tm2);
_mm256_store_ps(r0_tm_3, _r0tm3);
_mm256_store_ps(r0_tm_4, _r0tm4);
_mm256_store_ps(r0_tm_5, _r0tm5);
r0_tm_0 += tiles * 8 * 6;
r0_tm_1 += tiles * 8 * 6;
r0_tm_2 += tiles * 8 * 6;
r0_tm_3 += tiles * 8 * 6;
r0_tm_4 += tiles * 8 * 6;
r0_tm_5 += tiles * 8 * 6;
}
}
}
}
}
bottom_blob_bordered = Mat();
// END transform input
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = h_tm / 6 * w_tm / 6;
// permute
// bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator);
Mat bottom_blob_tm2;
if (tiles >= 12)
bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 36, 4u * elempack, elempack, opt.workspace_allocator);
else if (tiles >= 8)
bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator);
else if (tiles >= 4)
bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator);
else if (tiles >= 2)
bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator);
else // if (tiles >= 1)
bottom_blob_tm2.create(1 * inch, tiles, 36, 4u * elempack, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r = 0; r < 36; r++)
{
Mat tm2 = bottom_blob_tm2.channel(r);
// tile
int i = 0;
for (; i + 11 < tiles; i += 12)
{
float* tmpptr = tm2.row(i / 12);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x12
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r3 = _mm256_load_ps(r0 + 8 * 3);
__m256 _r4 = _mm256_load_ps(r0 + 8 * 4);
__m256 _r5 = _mm256_load_ps(r0 + 8 * 5);
__m256 _r6 = _mm256_load_ps(r0 + 8 * 6);
__m256 _r7 = _mm256_load_ps(r0 + 8 * 7);
__m256 _r8 = _mm256_load_ps(r0 + 8 * 8);
__m256 _r9 = _mm256_load_ps(r0 + 8 * 9);
__m256 _ra = _mm256_load_ps(r0 + 8 * 10);
__m256 _rb = _mm256_load_ps(r0 + 8 * 11);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5);
__m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5);
__m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7);
__m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7);
__m256 _tmp8 = _mm256_unpacklo_ps(_r8, _r9);
__m256 _tmp9 = _mm256_unpackhi_ps(_r8, _r9);
__m256 _tmpa = _mm256_unpacklo_ps(_ra, _rb);
__m256 _tmpb = _mm256_unpackhi_ps(_ra, _rb);
__m256 _tmpc = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpd = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpe = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpf = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpg = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmph = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpi = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpj = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpk = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpl = _mm256_shuffle_ps(_tmp8, _tmpa, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpm = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpn = _mm256_shuffle_ps(_tmp9, _tmpb, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 2, 0, 0));
_r3 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 2, 0, 0));
_r4 = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 2, 0, 0));
_r5 = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 2, 0, 0));
_r6 = _mm256_permute2f128_ps(_tmpc, _tmpg, _MM_SHUFFLE(0, 3, 0, 1));
_r7 = _mm256_permute2f128_ps(_tmpk, _tmpd, _MM_SHUFFLE(0, 3, 0, 1));
_r8 = _mm256_permute2f128_ps(_tmph, _tmpl, _MM_SHUFFLE(0, 3, 0, 1));
_r9 = _mm256_permute2f128_ps(_tmpe, _tmpi, _MM_SHUFFLE(0, 3, 0, 1));
_ra = _mm256_permute2f128_ps(_tmpm, _tmpf, _MM_SHUFFLE(0, 3, 0, 1));
_rb = _mm256_permute2f128_ps(_tmpj, _tmpn, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
_mm256_store_ps(tmpptr + 8 * 4, _r4);
_mm256_store_ps(tmpptr + 8 * 5, _r5);
_mm256_store_ps(tmpptr + 8 * 6, _r6);
_mm256_store_ps(tmpptr + 8 * 7, _r7);
_mm256_store_ps(tmpptr + 8 * 8, _r8);
_mm256_store_ps(tmpptr + 8 * 9, _r9);
_mm256_store_ps(tmpptr + 8 * 10, _ra);
_mm256_store_ps(tmpptr + 8 * 11, _rb);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 96;
}
}
for (; i + 7 < tiles; i += 8)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x8
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r3 = _mm256_load_ps(r0 + 8 * 3);
__m256 _r4 = _mm256_load_ps(r0 + 8 * 4);
__m256 _r5 = _mm256_load_ps(r0 + 8 * 5);
__m256 _r6 = _mm256_load_ps(r0 + 8 * 6);
__m256 _r7 = _mm256_load_ps(r0 + 8 * 7);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5);
__m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5);
__m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7);
__m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7);
__m256 _tmp8 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp9 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpa = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpb = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpc = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpd = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmpe = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmpf = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 2, 0, 0));
_r3 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 2, 0, 0));
_r4 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 3, 0, 1));
_r5 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 3, 0, 1));
_r6 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 3, 0, 1));
_r7 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
_mm256_store_ps(tmpptr + 8 * 4, _r4);
_mm256_store_ps(tmpptr + 8 * 5, _r5);
_mm256_store_ps(tmpptr + 8 * 6, _r6);
_mm256_store_ps(tmpptr + 8 * 7, _r7);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 64;
}
}
for (; i + 3 < tiles; i += 4)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x4
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _r2 = _mm256_load_ps(r0 + 8 * 2);
__m256 _r3 = _mm256_load_ps(r0 + 8 * 3);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
__m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3);
__m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3);
__m256 _tmp4 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp5 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2));
__m256 _tmp6 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0));
__m256 _tmp7 = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2));
_r0 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 2, 0, 0));
_r2 = _mm256_permute2f128_ps(_tmp4, _tmp5, _MM_SHUFFLE(0, 3, 0, 1));
_r3 = _mm256_permute2f128_ps(_tmp6, _tmp7, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
_mm256_store_ps(tmpptr + 8 * 2, _r2);
_mm256_store_ps(tmpptr + 8 * 3, _r3);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 32;
}
}
for (; i + 1 < tiles; i += 2)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
// transpose 8x2
__m256 _r0 = _mm256_load_ps(r0);
__m256 _r1 = _mm256_load_ps(r0 + 8);
__m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1);
__m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1);
_r0 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 2, 0, 0));
_r1 = _mm256_permute2f128_ps(_tmp0, _tmp1, _MM_SHUFFLE(0, 3, 0, 1));
_mm256_store_ps(tmpptr, _r0);
_mm256_store_ps(tmpptr + 8, _r1);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 16;
}
}
for (; i < tiles; i++)
{
float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* r0 = bottom_blob_tm;
r0 += (r * tiles + i) * 8;
for (int q = 0; q < inch; q++)
{
__m256 _val = _mm256_load_ps(r0);
_mm256_store_ps(tmpptr, _val);
r0 += bottom_blob_tm.cstep * 8;
tmpptr += 8;
}
}
}
bottom_blob_tm = Mat();
// permute end
top_blob_tm.create(tiles, 36, outch, 4u * elempack, elempack, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
float* output0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p);
for (int r = 0; r < 36; r++)
{
const Mat bb2 = bottom_blob_tm2.channel(r);
int i = 0;
for (; i + 11 < tiles; i += 12)
{
const float* r0 = bb2.row(i / 12);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
__m256 _sum4 = _mm256_setzero_ps();
__m256 _sum5 = _mm256_setzero_ps();
__m256 _sum6 = _mm256_setzero_ps();
__m256 _sum7 = _mm256_setzero_ps();
__m256 _sum8 = _mm256_setzero_ps();
__m256 _sum9 = _mm256_setzero_ps();
__m256 _suma = _mm256_setzero_ps();
__m256 _sumb = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
__m256 _val4 = _mm256_broadcast_ss(r0 + 4);
__m256 _val5 = _mm256_broadcast_ss(r0 + 5);
_sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4);
_sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5);
__m256 _val6 = _mm256_broadcast_ss(r0 + 6);
__m256 _val7 = _mm256_broadcast_ss(r0 + 7);
_sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6);
_sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7);
__m256 _val8 = _mm256_broadcast_ss(r0 + 8);
__m256 _val9 = _mm256_broadcast_ss(r0 + 9);
_sum8 = _mm256_comp_fmadd_ps(_val8, _w0, _sum8);
_sum9 = _mm256_comp_fmadd_ps(_val9, _w0, _sum9);
__m256 _vala = _mm256_broadcast_ss(r0 + 10);
__m256 _valb = _mm256_broadcast_ss(r0 + 11);
_suma = _mm256_comp_fmadd_ps(_vala, _w0, _suma);
_sumb = _mm256_comp_fmadd_ps(_valb, _w0, _sumb);
r0 += 12;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
_mm256_store_ps(output0_tm + 8 * 4, _sum4);
_mm256_store_ps(output0_tm + 8 * 5, _sum5);
_mm256_store_ps(output0_tm + 8 * 6, _sum6);
_mm256_store_ps(output0_tm + 8 * 7, _sum7);
_mm256_store_ps(output0_tm + 8 * 8, _sum8);
_mm256_store_ps(output0_tm + 8 * 9, _sum9);
_mm256_store_ps(output0_tm + 8 * 10, _suma);
_mm256_store_ps(output0_tm + 8 * 11, _sumb);
output0_tm += 8 * 12;
}
for (; i + 7 < tiles; i += 8)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
__m256 _sum4 = _mm256_setzero_ps();
__m256 _sum5 = _mm256_setzero_ps();
__m256 _sum6 = _mm256_setzero_ps();
__m256 _sum7 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
__m256 _val4 = _mm256_broadcast_ss(r0 + 4);
__m256 _val5 = _mm256_broadcast_ss(r0 + 5);
_sum4 = _mm256_comp_fmadd_ps(_val4, _w0, _sum4);
_sum5 = _mm256_comp_fmadd_ps(_val5, _w0, _sum5);
__m256 _val6 = _mm256_broadcast_ss(r0 + 6);
__m256 _val7 = _mm256_broadcast_ss(r0 + 7);
_sum6 = _mm256_comp_fmadd_ps(_val6, _w0, _sum6);
_sum7 = _mm256_comp_fmadd_ps(_val7, _w0, _sum7);
r0 += 8;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
_mm256_store_ps(output0_tm + 8 * 4, _sum4);
_mm256_store_ps(output0_tm + 8 * 5, _sum5);
_mm256_store_ps(output0_tm + 8 * 6, _sum6);
_mm256_store_ps(output0_tm + 8 * 7, _sum7);
output0_tm += 8 * 8;
}
for (; i + 3 < tiles; i += 4)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
__m256 _sum2 = _mm256_setzero_ps();
__m256 _sum3 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
__m256 _val2 = _mm256_broadcast_ss(r0 + 2);
__m256 _val3 = _mm256_broadcast_ss(r0 + 3);
_sum2 = _mm256_comp_fmadd_ps(_val2, _w0, _sum2);
_sum3 = _mm256_comp_fmadd_ps(_val3, _w0, _sum3);
r0 += 4;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
_mm256_store_ps(output0_tm + 8 * 2, _sum2);
_mm256_store_ps(output0_tm + 8 * 3, _sum3);
output0_tm += 8 * 4;
}
for (; i + 1 < tiles; i += 2)
{
const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2);
const float* k0 = kernel0_tm.row(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
__m256 _sum1 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
__m256 _val1 = _mm256_broadcast_ss(r0 + 1);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
_sum1 = _mm256_comp_fmadd_ps(_val1, _w0, _sum1);
r0 += 2;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
_mm256_store_ps(output0_tm + 8, _sum1);
output0_tm += 8 * 2;
}
for (; i < tiles; i++)
{
const float* r0 = bb2.row<const float>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2);
const float* k0 = kernel0_tm.row<const float>(r);
int nn = inch * 8; // inch always > 0
__m256 _sum0 = _mm256_setzero_ps();
for (int j = 0; j < nn; j++)
{
__m256 _w0 = _mm256_load_ps(k0);
__m256 _val0 = _mm256_broadcast_ss(r0);
_sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0);
r0 += 1;
k0 += 8;
}
_mm256_store_ps(output0_tm, _sum0);
output0_tm += 8;
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
if (outw == top_blob.w && outh == top_blob.h)
{
top_blob_bordered = top_blob;
}
else
{
top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator);
}
{
// const float otm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + (r01 + r02) + (r03 + r04)
// 1 = (r01 - r02) + (r03 - r04) * 2
// 2 = (r01 + r02) + (r03 + r04) * 4
// 3 = r05 + (r01 - r02) + (r03 - r04) * 8
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
const int tiles = w_tm / 6 * h_tm / 6;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
const Mat out0_tm = top_blob_tm.channel(p);
Mat out0 = top_blob_bordered.channel(p);
// const float bias0 = bias ? bias[p] : 0.f;
__m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + p * 8) : _mm256_setzero_ps();
#ifdef _MSC_VER
__declspec(align(32))
#else
__attribute__((aligned(32)))
#endif
float tmp[4][6][8];
// tile
for (int i = 0; i < outh / 4; i++)
{
for (int j = 0; j < outw / 4; j++)
{
// top_blob_tm.create(tiles, 36, outch, elemsize, elempack);
const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm / 6 + j) * 8;
const float* output0_tm_1 = output0_tm_0 + tiles * 8;
const float* output0_tm_2 = output0_tm_0 + tiles * 8 * 2;
const float* output0_tm_3 = output0_tm_0 + tiles * 8 * 3;
const float* output0_tm_4 = output0_tm_0 + tiles * 8 * 4;
const float* output0_tm_5 = output0_tm_0 + tiles * 8 * 5;
float* output0 = out0.row<float>(i * 4) + (j * 4) * 8;
// TODO msa optimize
for (int m = 0; m < 6; m++)
{
__m256 _out0tm0 = _mm256_load_ps(output0_tm_0);
__m256 _out0tm1 = _mm256_load_ps(output0_tm_1);
__m256 _out0tm2 = _mm256_load_ps(output0_tm_2);
__m256 _out0tm3 = _mm256_load_ps(output0_tm_3);
__m256 _out0tm4 = _mm256_load_ps(output0_tm_4);
__m256 _out0tm5 = _mm256_load_ps(output0_tm_5);
__m256 _tmp02a = _mm256_add_ps(_out0tm1, _out0tm2);
__m256 _tmp13a = _mm256_sub_ps(_out0tm1, _out0tm2);
__m256 _tmp02b = _mm256_add_ps(_out0tm3, _out0tm4);
__m256 _tmp13b = _mm256_sub_ps(_out0tm3, _out0tm4);
__m256 _tmp0m = _mm256_add_ps(_mm256_add_ps(_out0tm0, _tmp02a), _tmp02b);
__m256 _tmp1m = _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp13b, _tmp13a);
__m256 _tmp2m = _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp02b, _tmp02a);
__m256 _tmp3m = _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp13b, _mm256_add_ps(_out0tm5, _tmp13a));
_mm256_store_ps(tmp[0][m], _tmp0m);
_mm256_store_ps(tmp[1][m], _tmp1m);
_mm256_store_ps(tmp[2][m], _tmp2m);
_mm256_store_ps(tmp[3][m], _tmp3m);
output0_tm_0 += tiles * 8 * 6;
output0_tm_1 += tiles * 8 * 6;
output0_tm_2 += tiles * 8 * 6;
output0_tm_3 += tiles * 8 * 6;
output0_tm_4 += tiles * 8 * 6;
output0_tm_5 += tiles * 8 * 6;
}
for (int m = 0; m < 4; m++)
{
__m256 _tmp00 = _mm256_load_ps(tmp[m][0]);
__m256 _tmp01 = _mm256_load_ps(tmp[m][1]);
__m256 _tmp02 = _mm256_load_ps(tmp[m][2]);
__m256 _tmp03 = _mm256_load_ps(tmp[m][3]);
__m256 _tmp04 = _mm256_load_ps(tmp[m][4]);
__m256 _tmp05 = _mm256_load_ps(tmp[m][5]);
__m256 _tmp02a = _mm256_add_ps(_tmp01, _tmp02);
__m256 _tmp13a = _mm256_sub_ps(_tmp01, _tmp02);
__m256 _tmp02b = _mm256_add_ps(_tmp03, _tmp04);
__m256 _tmp13b = _mm256_sub_ps(_tmp03, _tmp04);
__m256 _out00 = _mm256_add_ps(_bias0, _mm256_add_ps(_mm256_add_ps(_tmp00, _tmp02a), _tmp02b));
__m256 _out01 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(2.f), _tmp13b, _tmp13a));
__m256 _out02 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(4.f), _tmp02b, _tmp02a));
__m256 _out03 = _mm256_add_ps(_bias0, _mm256_comp_fmadd_ps(_mm256_set1_ps(8.f), _tmp13b, _mm256_add_ps(_tmp05, _tmp13a)));
_mm256_store_ps(output0, _out00);
_mm256_store_ps(output0 + 8, _out01);
_mm256_store_ps(output0 + 8 * 2, _out02);
_mm256_store_ps(output0 + 8 * 3, _out03);
output0 += outw * 8;
}
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt);
}
|
GB_unaryop__minv_uint8_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__minv_uint8_uint8
// op(A') function: GB_tran__minv_uint8_uint8
// C type: uint8_t
// A type: uint8_t
// cast: uint8_t cij = (uint8_t) aij
// unaryop: cij = GB_IMINV_UNSIGNED (aij, 8)
#define GB_ATYPE \
uint8_t
#define GB_CTYPE \
uint8_t
// 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 = GB_IMINV_UNSIGNED (x, 8) ;
// casting
#define GB_CASTING(z, x) \
uint8_t z = (uint8_t) x ;
// cij = op (cast (aij))
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GB_GETA (aij, Ax, pA) ; \
/* Cx [pC] = op (cast (aij)) */ \
GB_CASTING (x, aij) ; \
GB_OP (GB_CX (pC), x) ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_MINV || GxB_NO_UINT8)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB_unop__minv_uint8_uint8
(
uint8_t *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__minv_uint8_uint8
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t **Rowcounts,
GBI_single_iterator Iter,
const int64_t *restrict A_slice,
int naslice
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#define GB_PHASE_2_OF_2
#include "GB_unaryop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
dds.c | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD DDDD SSSSS %
% D D D D SS %
% D D D D SSS %
% D D D D SS %
% DDDD DDDD SSSSS %
% %
% %
% Read/Write Microsoft Direct Draw Surface Image Format %
% %
% Software Design %
% Bianca van Schaik %
% March 2008 %
% Dirk Lemstra %
% September 2013 %
% %
% %
% Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/attribute.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/colorspace-private.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/log.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/pixel-accessor.h"
#include "magick/profile.h"
#include "magick/quantum.h"
#include "magick/quantum-private.h"
#include "magick/resource_.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/string-private.h"
#include "magick/module.h"
#include "magick/transform.h"
/*
Definitions
*/
#define DDSD_CAPS 0x00000001
#define DDSD_HEIGHT 0x00000002
#define DDSD_WIDTH 0x00000004
#define DDSD_PITCH 0x00000008
#define DDSD_PIXELFORMAT 0x00001000
#define DDSD_MIPMAPCOUNT 0x00020000
#define DDSD_LINEARSIZE 0x00080000
#define DDSD_DEPTH 0x00800000
#define DDPF_ALPHAPIXELS 0x00000001
#define DDPF_FOURCC 0x00000004
#define DDPF_RGB 0x00000040
#define DDPF_LUMINANCE 0x00020000
#define FOURCC_DXT1 0x31545844
#define FOURCC_DXT3 0x33545844
#define FOURCC_DXT5 0x35545844
#define DDSCAPS_COMPLEX 0x00000008
#define DDSCAPS_TEXTURE 0x00001000
#define DDSCAPS_MIPMAP 0x00400000
#define DDSCAPS2_CUBEMAP 0x00000200
#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400
#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800
#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000
#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000
#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000
#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000
#define DDSCAPS2_VOLUME 0x00200000
#ifndef SIZE_MAX
#define SIZE_MAX ((size_t) -1)
#endif
/*
Structure declarations.
*/
typedef struct _DDSPixelFormat
{
size_t
flags,
fourcc,
rgb_bitcount,
r_bitmask,
g_bitmask,
b_bitmask,
alpha_bitmask;
} DDSPixelFormat;
typedef struct _DDSInfo
{
size_t
flags,
height,
width,
pitchOrLinearSize,
depth,
mipmapcount,
ddscaps1,
ddscaps2;
DDSPixelFormat
pixelformat;
} DDSInfo;
typedef struct _DDSColors
{
unsigned char
r[4],
g[4],
b[4],
a[4];
} DDSColors;
typedef struct _DDSVector4
{
float
x,
y,
z,
w;
} DDSVector4;
typedef struct _DDSVector3
{
float
x,
y,
z;
} DDSVector3;
typedef struct _DDSSourceBlock
{
unsigned char
start,
end,
error;
} DDSSourceBlock;
typedef struct _DDSSingleColourLookup
{
DDSSourceBlock sources[2];
} DDSSingleColourLookup;
typedef MagickBooleanType
DDSDecoder(Image *, DDSInfo *, ExceptionInfo *);
static const DDSSingleColourLookup DDSLookup_5_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 1 } } },
{ { { 0, 0, 2 }, { 0, 1, 0 } } },
{ { { 0, 0, 3 }, { 0, 1, 1 } } },
{ { { 0, 0, 4 }, { 0, 2, 1 } } },
{ { { 1, 0, 3 }, { 0, 2, 0 } } },
{ { { 1, 0, 2 }, { 0, 2, 1 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 1, 2, 1 } } },
{ { { 1, 0, 2 }, { 1, 2, 0 } } },
{ { { 1, 0, 3 }, { 0, 4, 0 } } },
{ { { 1, 0, 4 }, { 0, 5, 1 } } },
{ { { 2, 0, 3 }, { 0, 5, 0 } } },
{ { { 2, 0, 2 }, { 0, 5, 1 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 2, 3, 1 } } },
{ { { 2, 0, 2 }, { 2, 3, 0 } } },
{ { { 2, 0, 3 }, { 0, 7, 0 } } },
{ { { 2, 0, 4 }, { 1, 6, 1 } } },
{ { { 3, 0, 3 }, { 1, 6, 0 } } },
{ { { 3, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 2 }, { 0, 10, 1 } } },
{ { { 3, 0, 3 }, { 0, 10, 0 } } },
{ { { 3, 0, 4 }, { 2, 7, 1 } } },
{ { { 4, 0, 4 }, { 2, 7, 0 } } },
{ { { 4, 0, 3 }, { 0, 11, 0 } } },
{ { { 4, 0, 2 }, { 1, 10, 1 } } },
{ { { 4, 0, 1 }, { 1, 10, 0 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 1 } } },
{ { { 4, 0, 2 }, { 0, 13, 0 } } },
{ { { 4, 0, 3 }, { 0, 13, 1 } } },
{ { { 4, 0, 4 }, { 0, 14, 1 } } },
{ { { 5, 0, 3 }, { 0, 14, 0 } } },
{ { { 5, 0, 2 }, { 2, 11, 1 } } },
{ { { 5, 0, 1 }, { 2, 11, 0 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 1, 14, 1 } } },
{ { { 5, 0, 2 }, { 1, 14, 0 } } },
{ { { 5, 0, 3 }, { 0, 16, 0 } } },
{ { { 5, 0, 4 }, { 0, 17, 1 } } },
{ { { 6, 0, 3 }, { 0, 17, 0 } } },
{ { { 6, 0, 2 }, { 0, 17, 1 } } },
{ { { 6, 0, 1 }, { 0, 18, 1 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 2, 15, 1 } } },
{ { { 6, 0, 2 }, { 2, 15, 0 } } },
{ { { 6, 0, 3 }, { 0, 19, 0 } } },
{ { { 6, 0, 4 }, { 1, 18, 1 } } },
{ { { 7, 0, 3 }, { 1, 18, 0 } } },
{ { { 7, 0, 2 }, { 0, 20, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 21, 1 } } },
{ { { 7, 0, 2 }, { 0, 22, 1 } } },
{ { { 7, 0, 3 }, { 0, 22, 0 } } },
{ { { 7, 0, 4 }, { 2, 19, 1 } } },
{ { { 8, 0, 4 }, { 2, 19, 0 } } },
{ { { 8, 0, 3 }, { 0, 23, 0 } } },
{ { { 8, 0, 2 }, { 1, 22, 1 } } },
{ { { 8, 0, 1 }, { 1, 22, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 1 } } },
{ { { 8, 0, 2 }, { 0, 25, 0 } } },
{ { { 8, 0, 3 }, { 0, 25, 1 } } },
{ { { 8, 0, 4 }, { 0, 26, 1 } } },
{ { { 9, 0, 3 }, { 0, 26, 0 } } },
{ { { 9, 0, 2 }, { 2, 23, 1 } } },
{ { { 9, 0, 1 }, { 2, 23, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 1, 26, 1 } } },
{ { { 9, 0, 2 }, { 1, 26, 0 } } },
{ { { 9, 0, 3 }, { 0, 28, 0 } } },
{ { { 9, 0, 4 }, { 0, 29, 1 } } },
{ { { 10, 0, 3 }, { 0, 29, 0 } } },
{ { { 10, 0, 2 }, { 0, 29, 1 } } },
{ { { 10, 0, 1 }, { 0, 30, 1 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 2, 27, 1 } } },
{ { { 10, 0, 2 }, { 2, 27, 0 } } },
{ { { 10, 0, 3 }, { 0, 31, 0 } } },
{ { { 10, 0, 4 }, { 1, 30, 1 } } },
{ { { 11, 0, 3 }, { 1, 30, 0 } } },
{ { { 11, 0, 2 }, { 4, 24, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 0 }, { 1, 31, 0 } } },
{ { { 11, 0, 1 }, { 1, 31, 1 } } },
{ { { 11, 0, 2 }, { 2, 30, 1 } } },
{ { { 11, 0, 3 }, { 2, 30, 0 } } },
{ { { 11, 0, 4 }, { 2, 31, 1 } } },
{ { { 12, 0, 4 }, { 2, 31, 0 } } },
{ { { 12, 0, 3 }, { 4, 27, 0 } } },
{ { { 12, 0, 2 }, { 3, 30, 1 } } },
{ { { 12, 0, 1 }, { 3, 30, 0 } } },
{ { { 12, 0, 0 }, { 4, 28, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 1 } } },
{ { { 12, 0, 2 }, { 3, 31, 0 } } },
{ { { 12, 0, 3 }, { 3, 31, 1 } } },
{ { { 12, 0, 4 }, { 4, 30, 1 } } },
{ { { 13, 0, 3 }, { 4, 30, 0 } } },
{ { { 13, 0, 2 }, { 6, 27, 1 } } },
{ { { 13, 0, 1 }, { 6, 27, 0 } } },
{ { { 13, 0, 0 }, { 4, 31, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 1 } } },
{ { { 13, 0, 2 }, { 5, 30, 0 } } },
{ { { 13, 0, 3 }, { 8, 24, 0 } } },
{ { { 13, 0, 4 }, { 5, 31, 1 } } },
{ { { 14, 0, 3 }, { 5, 31, 0 } } },
{ { { 14, 0, 2 }, { 5, 31, 1 } } },
{ { { 14, 0, 1 }, { 6, 30, 1 } } },
{ { { 14, 0, 0 }, { 6, 30, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 1 } } },
{ { { 14, 0, 2 }, { 6, 31, 0 } } },
{ { { 14, 0, 3 }, { 8, 27, 0 } } },
{ { { 14, 0, 4 }, { 7, 30, 1 } } },
{ { { 15, 0, 3 }, { 7, 30, 0 } } },
{ { { 15, 0, 2 }, { 8, 28, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 0 }, { 7, 31, 0 } } },
{ { { 15, 0, 1 }, { 7, 31, 1 } } },
{ { { 15, 0, 2 }, { 8, 30, 1 } } },
{ { { 15, 0, 3 }, { 8, 30, 0 } } },
{ { { 15, 0, 4 }, { 10, 27, 1 } } },
{ { { 16, 0, 4 }, { 10, 27, 0 } } },
{ { { 16, 0, 3 }, { 8, 31, 0 } } },
{ { { 16, 0, 2 }, { 9, 30, 1 } } },
{ { { 16, 0, 1 }, { 9, 30, 0 } } },
{ { { 16, 0, 0 }, { 12, 24, 0 } } },
{ { { 16, 0, 1 }, { 9, 31, 1 } } },
{ { { 16, 0, 2 }, { 9, 31, 0 } } },
{ { { 16, 0, 3 }, { 9, 31, 1 } } },
{ { { 16, 0, 4 }, { 10, 30, 1 } } },
{ { { 17, 0, 3 }, { 10, 30, 0 } } },
{ { { 17, 0, 2 }, { 10, 31, 1 } } },
{ { { 17, 0, 1 }, { 10, 31, 0 } } },
{ { { 17, 0, 0 }, { 12, 27, 0 } } },
{ { { 17, 0, 1 }, { 11, 30, 1 } } },
{ { { 17, 0, 2 }, { 11, 30, 0 } } },
{ { { 17, 0, 3 }, { 12, 28, 0 } } },
{ { { 17, 0, 4 }, { 11, 31, 1 } } },
{ { { 18, 0, 3 }, { 11, 31, 0 } } },
{ { { 18, 0, 2 }, { 11, 31, 1 } } },
{ { { 18, 0, 1 }, { 12, 30, 1 } } },
{ { { 18, 0, 0 }, { 12, 30, 0 } } },
{ { { 18, 0, 1 }, { 14, 27, 1 } } },
{ { { 18, 0, 2 }, { 14, 27, 0 } } },
{ { { 18, 0, 3 }, { 12, 31, 0 } } },
{ { { 18, 0, 4 }, { 13, 30, 1 } } },
{ { { 19, 0, 3 }, { 13, 30, 0 } } },
{ { { 19, 0, 2 }, { 16, 24, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 0 }, { 13, 31, 0 } } },
{ { { 19, 0, 1 }, { 13, 31, 1 } } },
{ { { 19, 0, 2 }, { 14, 30, 1 } } },
{ { { 19, 0, 3 }, { 14, 30, 0 } } },
{ { { 19, 0, 4 }, { 14, 31, 1 } } },
{ { { 20, 0, 4 }, { 14, 31, 0 } } },
{ { { 20, 0, 3 }, { 16, 27, 0 } } },
{ { { 20, 0, 2 }, { 15, 30, 1 } } },
{ { { 20, 0, 1 }, { 15, 30, 0 } } },
{ { { 20, 0, 0 }, { 16, 28, 0 } } },
{ { { 20, 0, 1 }, { 15, 31, 1 } } },
{ { { 20, 0, 2 }, { 15, 31, 0 } } },
{ { { 20, 0, 3 }, { 15, 31, 1 } } },
{ { { 20, 0, 4 }, { 16, 30, 1 } } },
{ { { 21, 0, 3 }, { 16, 30, 0 } } },
{ { { 21, 0, 2 }, { 18, 27, 1 } } },
{ { { 21, 0, 1 }, { 18, 27, 0 } } },
{ { { 21, 0, 0 }, { 16, 31, 0 } } },
{ { { 21, 0, 1 }, { 17, 30, 1 } } },
{ { { 21, 0, 2 }, { 17, 30, 0 } } },
{ { { 21, 0, 3 }, { 20, 24, 0 } } },
{ { { 21, 0, 4 }, { 17, 31, 1 } } },
{ { { 22, 0, 3 }, { 17, 31, 0 } } },
{ { { 22, 0, 2 }, { 17, 31, 1 } } },
{ { { 22, 0, 1 }, { 18, 30, 1 } } },
{ { { 22, 0, 0 }, { 18, 30, 0 } } },
{ { { 22, 0, 1 }, { 18, 31, 1 } } },
{ { { 22, 0, 2 }, { 18, 31, 0 } } },
{ { { 22, 0, 3 }, { 20, 27, 0 } } },
{ { { 22, 0, 4 }, { 19, 30, 1 } } },
{ { { 23, 0, 3 }, { 19, 30, 0 } } },
{ { { 23, 0, 2 }, { 20, 28, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 0 }, { 19, 31, 0 } } },
{ { { 23, 0, 1 }, { 19, 31, 1 } } },
{ { { 23, 0, 2 }, { 20, 30, 1 } } },
{ { { 23, 0, 3 }, { 20, 30, 0 } } },
{ { { 23, 0, 4 }, { 22, 27, 1 } } },
{ { { 24, 0, 4 }, { 22, 27, 0 } } },
{ { { 24, 0, 3 }, { 20, 31, 0 } } },
{ { { 24, 0, 2 }, { 21, 30, 1 } } },
{ { { 24, 0, 1 }, { 21, 30, 0 } } },
{ { { 24, 0, 0 }, { 24, 24, 0 } } },
{ { { 24, 0, 1 }, { 21, 31, 1 } } },
{ { { 24, 0, 2 }, { 21, 31, 0 } } },
{ { { 24, 0, 3 }, { 21, 31, 1 } } },
{ { { 24, 0, 4 }, { 22, 30, 1 } } },
{ { { 25, 0, 3 }, { 22, 30, 0 } } },
{ { { 25, 0, 2 }, { 22, 31, 1 } } },
{ { { 25, 0, 1 }, { 22, 31, 0 } } },
{ { { 25, 0, 0 }, { 24, 27, 0 } } },
{ { { 25, 0, 1 }, { 23, 30, 1 } } },
{ { { 25, 0, 2 }, { 23, 30, 0 } } },
{ { { 25, 0, 3 }, { 24, 28, 0 } } },
{ { { 25, 0, 4 }, { 23, 31, 1 } } },
{ { { 26, 0, 3 }, { 23, 31, 0 } } },
{ { { 26, 0, 2 }, { 23, 31, 1 } } },
{ { { 26, 0, 1 }, { 24, 30, 1 } } },
{ { { 26, 0, 0 }, { 24, 30, 0 } } },
{ { { 26, 0, 1 }, { 26, 27, 1 } } },
{ { { 26, 0, 2 }, { 26, 27, 0 } } },
{ { { 26, 0, 3 }, { 24, 31, 0 } } },
{ { { 26, 0, 4 }, { 25, 30, 1 } } },
{ { { 27, 0, 3 }, { 25, 30, 0 } } },
{ { { 27, 0, 2 }, { 28, 24, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 0 }, { 25, 31, 0 } } },
{ { { 27, 0, 1 }, { 25, 31, 1 } } },
{ { { 27, 0, 2 }, { 26, 30, 1 } } },
{ { { 27, 0, 3 }, { 26, 30, 0 } } },
{ { { 27, 0, 4 }, { 26, 31, 1 } } },
{ { { 28, 0, 4 }, { 26, 31, 0 } } },
{ { { 28, 0, 3 }, { 28, 27, 0 } } },
{ { { 28, 0, 2 }, { 27, 30, 1 } } },
{ { { 28, 0, 1 }, { 27, 30, 0 } } },
{ { { 28, 0, 0 }, { 28, 28, 0 } } },
{ { { 28, 0, 1 }, { 27, 31, 1 } } },
{ { { 28, 0, 2 }, { 27, 31, 0 } } },
{ { { 28, 0, 3 }, { 27, 31, 1 } } },
{ { { 28, 0, 4 }, { 28, 30, 1 } } },
{ { { 29, 0, 3 }, { 28, 30, 0 } } },
{ { { 29, 0, 2 }, { 30, 27, 1 } } },
{ { { 29, 0, 1 }, { 30, 27, 0 } } },
{ { { 29, 0, 0 }, { 28, 31, 0 } } },
{ { { 29, 0, 1 }, { 29, 30, 1 } } },
{ { { 29, 0, 2 }, { 29, 30, 0 } } },
{ { { 29, 0, 3 }, { 29, 30, 1 } } },
{ { { 29, 0, 4 }, { 29, 31, 1 } } },
{ { { 30, 0, 3 }, { 29, 31, 0 } } },
{ { { 30, 0, 2 }, { 29, 31, 1 } } },
{ { { 30, 0, 1 }, { 30, 30, 1 } } },
{ { { 30, 0, 0 }, { 30, 30, 0 } } },
{ { { 30, 0, 1 }, { 30, 31, 1 } } },
{ { { 30, 0, 2 }, { 30, 31, 0 } } },
{ { { 30, 0, 3 }, { 30, 31, 1 } } },
{ { { 30, 0, 4 }, { 31, 30, 1 } } },
{ { { 31, 0, 3 }, { 31, 30, 0 } } },
{ { { 31, 0, 2 }, { 31, 30, 1 } } },
{ { { 31, 0, 1 }, { 31, 31, 1 } } },
{ { { 31, 0, 0 }, { 31, 31, 0 } } }
};
static const DDSSingleColourLookup DDSLookup_6_4[] =
{
{ { { 0, 0, 0 }, { 0, 0, 0 } } },
{ { { 0, 0, 1 }, { 0, 1, 0 } } },
{ { { 0, 0, 2 }, { 0, 2, 0 } } },
{ { { 1, 0, 1 }, { 0, 3, 1 } } },
{ { { 1, 0, 0 }, { 0, 3, 0 } } },
{ { { 1, 0, 1 }, { 0, 4, 0 } } },
{ { { 1, 0, 2 }, { 0, 5, 0 } } },
{ { { 2, 0, 1 }, { 0, 6, 1 } } },
{ { { 2, 0, 0 }, { 0, 6, 0 } } },
{ { { 2, 0, 1 }, { 0, 7, 0 } } },
{ { { 2, 0, 2 }, { 0, 8, 0 } } },
{ { { 3, 0, 1 }, { 0, 9, 1 } } },
{ { { 3, 0, 0 }, { 0, 9, 0 } } },
{ { { 3, 0, 1 }, { 0, 10, 0 } } },
{ { { 3, 0, 2 }, { 0, 11, 0 } } },
{ { { 4, 0, 1 }, { 0, 12, 1 } } },
{ { { 4, 0, 0 }, { 0, 12, 0 } } },
{ { { 4, 0, 1 }, { 0, 13, 0 } } },
{ { { 4, 0, 2 }, { 0, 14, 0 } } },
{ { { 5, 0, 1 }, { 0, 15, 1 } } },
{ { { 5, 0, 0 }, { 0, 15, 0 } } },
{ { { 5, 0, 1 }, { 0, 16, 0 } } },
{ { { 5, 0, 2 }, { 1, 15, 0 } } },
{ { { 6, 0, 1 }, { 0, 17, 0 } } },
{ { { 6, 0, 0 }, { 0, 18, 0 } } },
{ { { 6, 0, 1 }, { 0, 19, 0 } } },
{ { { 6, 0, 2 }, { 3, 14, 0 } } },
{ { { 7, 0, 1 }, { 0, 20, 0 } } },
{ { { 7, 0, 0 }, { 0, 21, 0 } } },
{ { { 7, 0, 1 }, { 0, 22, 0 } } },
{ { { 7, 0, 2 }, { 4, 15, 0 } } },
{ { { 8, 0, 1 }, { 0, 23, 0 } } },
{ { { 8, 0, 0 }, { 0, 24, 0 } } },
{ { { 8, 0, 1 }, { 0, 25, 0 } } },
{ { { 8, 0, 2 }, { 6, 14, 0 } } },
{ { { 9, 0, 1 }, { 0, 26, 0 } } },
{ { { 9, 0, 0 }, { 0, 27, 0 } } },
{ { { 9, 0, 1 }, { 0, 28, 0 } } },
{ { { 9, 0, 2 }, { 7, 15, 0 } } },
{ { { 10, 0, 1 }, { 0, 29, 0 } } },
{ { { 10, 0, 0 }, { 0, 30, 0 } } },
{ { { 10, 0, 1 }, { 0, 31, 0 } } },
{ { { 10, 0, 2 }, { 9, 14, 0 } } },
{ { { 11, 0, 1 }, { 0, 32, 0 } } },
{ { { 11, 0, 0 }, { 0, 33, 0 } } },
{ { { 11, 0, 1 }, { 2, 30, 0 } } },
{ { { 11, 0, 2 }, { 0, 34, 0 } } },
{ { { 12, 0, 1 }, { 0, 35, 0 } } },
{ { { 12, 0, 0 }, { 0, 36, 0 } } },
{ { { 12, 0, 1 }, { 3, 31, 0 } } },
{ { { 12, 0, 2 }, { 0, 37, 0 } } },
{ { { 13, 0, 1 }, { 0, 38, 0 } } },
{ { { 13, 0, 0 }, { 0, 39, 0 } } },
{ { { 13, 0, 1 }, { 5, 30, 0 } } },
{ { { 13, 0, 2 }, { 0, 40, 0 } } },
{ { { 14, 0, 1 }, { 0, 41, 0 } } },
{ { { 14, 0, 0 }, { 0, 42, 0 } } },
{ { { 14, 0, 1 }, { 6, 31, 0 } } },
{ { { 14, 0, 2 }, { 0, 43, 0 } } },
{ { { 15, 0, 1 }, { 0, 44, 0 } } },
{ { { 15, 0, 0 }, { 0, 45, 0 } } },
{ { { 15, 0, 1 }, { 8, 30, 0 } } },
{ { { 15, 0, 2 }, { 0, 46, 0 } } },
{ { { 16, 0, 2 }, { 0, 47, 0 } } },
{ { { 16, 0, 1 }, { 1, 46, 0 } } },
{ { { 16, 0, 0 }, { 0, 48, 0 } } },
{ { { 16, 0, 1 }, { 0, 49, 0 } } },
{ { { 16, 0, 2 }, { 0, 50, 0 } } },
{ { { 17, 0, 1 }, { 2, 47, 0 } } },
{ { { 17, 0, 0 }, { 0, 51, 0 } } },
{ { { 17, 0, 1 }, { 0, 52, 0 } } },
{ { { 17, 0, 2 }, { 0, 53, 0 } } },
{ { { 18, 0, 1 }, { 4, 46, 0 } } },
{ { { 18, 0, 0 }, { 0, 54, 0 } } },
{ { { 18, 0, 1 }, { 0, 55, 0 } } },
{ { { 18, 0, 2 }, { 0, 56, 0 } } },
{ { { 19, 0, 1 }, { 5, 47, 0 } } },
{ { { 19, 0, 0 }, { 0, 57, 0 } } },
{ { { 19, 0, 1 }, { 0, 58, 0 } } },
{ { { 19, 0, 2 }, { 0, 59, 0 } } },
{ { { 20, 0, 1 }, { 7, 46, 0 } } },
{ { { 20, 0, 0 }, { 0, 60, 0 } } },
{ { { 20, 0, 1 }, { 0, 61, 0 } } },
{ { { 20, 0, 2 }, { 0, 62, 0 } } },
{ { { 21, 0, 1 }, { 8, 47, 0 } } },
{ { { 21, 0, 0 }, { 0, 63, 0 } } },
{ { { 21, 0, 1 }, { 1, 62, 0 } } },
{ { { 21, 0, 2 }, { 1, 63, 0 } } },
{ { { 22, 0, 1 }, { 10, 46, 0 } } },
{ { { 22, 0, 0 }, { 2, 62, 0 } } },
{ { { 22, 0, 1 }, { 2, 63, 0 } } },
{ { { 22, 0, 2 }, { 3, 62, 0 } } },
{ { { 23, 0, 1 }, { 11, 47, 0 } } },
{ { { 23, 0, 0 }, { 3, 63, 0 } } },
{ { { 23, 0, 1 }, { 4, 62, 0 } } },
{ { { 23, 0, 2 }, { 4, 63, 0 } } },
{ { { 24, 0, 1 }, { 13, 46, 0 } } },
{ { { 24, 0, 0 }, { 5, 62, 0 } } },
{ { { 24, 0, 1 }, { 5, 63, 0 } } },
{ { { 24, 0, 2 }, { 6, 62, 0 } } },
{ { { 25, 0, 1 }, { 14, 47, 0 } } },
{ { { 25, 0, 0 }, { 6, 63, 0 } } },
{ { { 25, 0, 1 }, { 7, 62, 0 } } },
{ { { 25, 0, 2 }, { 7, 63, 0 } } },
{ { { 26, 0, 1 }, { 16, 45, 0 } } },
{ { { 26, 0, 0 }, { 8, 62, 0 } } },
{ { { 26, 0, 1 }, { 8, 63, 0 } } },
{ { { 26, 0, 2 }, { 9, 62, 0 } } },
{ { { 27, 0, 1 }, { 16, 48, 0 } } },
{ { { 27, 0, 0 }, { 9, 63, 0 } } },
{ { { 27, 0, 1 }, { 10, 62, 0 } } },
{ { { 27, 0, 2 }, { 10, 63, 0 } } },
{ { { 28, 0, 1 }, { 16, 51, 0 } } },
{ { { 28, 0, 0 }, { 11, 62, 0 } } },
{ { { 28, 0, 1 }, { 11, 63, 0 } } },
{ { { 28, 0, 2 }, { 12, 62, 0 } } },
{ { { 29, 0, 1 }, { 16, 54, 0 } } },
{ { { 29, 0, 0 }, { 12, 63, 0 } } },
{ { { 29, 0, 1 }, { 13, 62, 0 } } },
{ { { 29, 0, 2 }, { 13, 63, 0 } } },
{ { { 30, 0, 1 }, { 16, 57, 0 } } },
{ { { 30, 0, 0 }, { 14, 62, 0 } } },
{ { { 30, 0, 1 }, { 14, 63, 0 } } },
{ { { 30, 0, 2 }, { 15, 62, 0 } } },
{ { { 31, 0, 1 }, { 16, 60, 0 } } },
{ { { 31, 0, 0 }, { 15, 63, 0 } } },
{ { { 31, 0, 1 }, { 24, 46, 0 } } },
{ { { 31, 0, 2 }, { 16, 62, 0 } } },
{ { { 32, 0, 2 }, { 16, 63, 0 } } },
{ { { 32, 0, 1 }, { 17, 62, 0 } } },
{ { { 32, 0, 0 }, { 25, 47, 0 } } },
{ { { 32, 0, 1 }, { 17, 63, 0 } } },
{ { { 32, 0, 2 }, { 18, 62, 0 } } },
{ { { 33, 0, 1 }, { 18, 63, 0 } } },
{ { { 33, 0, 0 }, { 27, 46, 0 } } },
{ { { 33, 0, 1 }, { 19, 62, 0 } } },
{ { { 33, 0, 2 }, { 19, 63, 0 } } },
{ { { 34, 0, 1 }, { 20, 62, 0 } } },
{ { { 34, 0, 0 }, { 28, 47, 0 } } },
{ { { 34, 0, 1 }, { 20, 63, 0 } } },
{ { { 34, 0, 2 }, { 21, 62, 0 } } },
{ { { 35, 0, 1 }, { 21, 63, 0 } } },
{ { { 35, 0, 0 }, { 30, 46, 0 } } },
{ { { 35, 0, 1 }, { 22, 62, 0 } } },
{ { { 35, 0, 2 }, { 22, 63, 0 } } },
{ { { 36, 0, 1 }, { 23, 62, 0 } } },
{ { { 36, 0, 0 }, { 31, 47, 0 } } },
{ { { 36, 0, 1 }, { 23, 63, 0 } } },
{ { { 36, 0, 2 }, { 24, 62, 0 } } },
{ { { 37, 0, 1 }, { 24, 63, 0 } } },
{ { { 37, 0, 0 }, { 32, 47, 0 } } },
{ { { 37, 0, 1 }, { 25, 62, 0 } } },
{ { { 37, 0, 2 }, { 25, 63, 0 } } },
{ { { 38, 0, 1 }, { 26, 62, 0 } } },
{ { { 38, 0, 0 }, { 32, 50, 0 } } },
{ { { 38, 0, 1 }, { 26, 63, 0 } } },
{ { { 38, 0, 2 }, { 27, 62, 0 } } },
{ { { 39, 0, 1 }, { 27, 63, 0 } } },
{ { { 39, 0, 0 }, { 32, 53, 0 } } },
{ { { 39, 0, 1 }, { 28, 62, 0 } } },
{ { { 39, 0, 2 }, { 28, 63, 0 } } },
{ { { 40, 0, 1 }, { 29, 62, 0 } } },
{ { { 40, 0, 0 }, { 32, 56, 0 } } },
{ { { 40, 0, 1 }, { 29, 63, 0 } } },
{ { { 40, 0, 2 }, { 30, 62, 0 } } },
{ { { 41, 0, 1 }, { 30, 63, 0 } } },
{ { { 41, 0, 0 }, { 32, 59, 0 } } },
{ { { 41, 0, 1 }, { 31, 62, 0 } } },
{ { { 41, 0, 2 }, { 31, 63, 0 } } },
{ { { 42, 0, 1 }, { 32, 61, 0 } } },
{ { { 42, 0, 0 }, { 32, 62, 0 } } },
{ { { 42, 0, 1 }, { 32, 63, 0 } } },
{ { { 42, 0, 2 }, { 41, 46, 0 } } },
{ { { 43, 0, 1 }, { 33, 62, 0 } } },
{ { { 43, 0, 0 }, { 33, 63, 0 } } },
{ { { 43, 0, 1 }, { 34, 62, 0 } } },
{ { { 43, 0, 2 }, { 42, 47, 0 } } },
{ { { 44, 0, 1 }, { 34, 63, 0 } } },
{ { { 44, 0, 0 }, { 35, 62, 0 } } },
{ { { 44, 0, 1 }, { 35, 63, 0 } } },
{ { { 44, 0, 2 }, { 44, 46, 0 } } },
{ { { 45, 0, 1 }, { 36, 62, 0 } } },
{ { { 45, 0, 0 }, { 36, 63, 0 } } },
{ { { 45, 0, 1 }, { 37, 62, 0 } } },
{ { { 45, 0, 2 }, { 45, 47, 0 } } },
{ { { 46, 0, 1 }, { 37, 63, 0 } } },
{ { { 46, 0, 0 }, { 38, 62, 0 } } },
{ { { 46, 0, 1 }, { 38, 63, 0 } } },
{ { { 46, 0, 2 }, { 47, 46, 0 } } },
{ { { 47, 0, 1 }, { 39, 62, 0 } } },
{ { { 47, 0, 0 }, { 39, 63, 0 } } },
{ { { 47, 0, 1 }, { 40, 62, 0 } } },
{ { { 47, 0, 2 }, { 48, 46, 0 } } },
{ { { 48, 0, 2 }, { 40, 63, 0 } } },
{ { { 48, 0, 1 }, { 41, 62, 0 } } },
{ { { 48, 0, 0 }, { 41, 63, 0 } } },
{ { { 48, 0, 1 }, { 48, 49, 0 } } },
{ { { 48, 0, 2 }, { 42, 62, 0 } } },
{ { { 49, 0, 1 }, { 42, 63, 0 } } },
{ { { 49, 0, 0 }, { 43, 62, 0 } } },
{ { { 49, 0, 1 }, { 48, 52, 0 } } },
{ { { 49, 0, 2 }, { 43, 63, 0 } } },
{ { { 50, 0, 1 }, { 44, 62, 0 } } },
{ { { 50, 0, 0 }, { 44, 63, 0 } } },
{ { { 50, 0, 1 }, { 48, 55, 0 } } },
{ { { 50, 0, 2 }, { 45, 62, 0 } } },
{ { { 51, 0, 1 }, { 45, 63, 0 } } },
{ { { 51, 0, 0 }, { 46, 62, 0 } } },
{ { { 51, 0, 1 }, { 48, 58, 0 } } },
{ { { 51, 0, 2 }, { 46, 63, 0 } } },
{ { { 52, 0, 1 }, { 47, 62, 0 } } },
{ { { 52, 0, 0 }, { 47, 63, 0 } } },
{ { { 52, 0, 1 }, { 48, 61, 0 } } },
{ { { 52, 0, 2 }, { 48, 62, 0 } } },
{ { { 53, 0, 1 }, { 56, 47, 0 } } },
{ { { 53, 0, 0 }, { 48, 63, 0 } } },
{ { { 53, 0, 1 }, { 49, 62, 0 } } },
{ { { 53, 0, 2 }, { 49, 63, 0 } } },
{ { { 54, 0, 1 }, { 58, 46, 0 } } },
{ { { 54, 0, 0 }, { 50, 62, 0 } } },
{ { { 54, 0, 1 }, { 50, 63, 0 } } },
{ { { 54, 0, 2 }, { 51, 62, 0 } } },
{ { { 55, 0, 1 }, { 59, 47, 0 } } },
{ { { 55, 0, 0 }, { 51, 63, 0 } } },
{ { { 55, 0, 1 }, { 52, 62, 0 } } },
{ { { 55, 0, 2 }, { 52, 63, 0 } } },
{ { { 56, 0, 1 }, { 61, 46, 0 } } },
{ { { 56, 0, 0 }, { 53, 62, 0 } } },
{ { { 56, 0, 1 }, { 53, 63, 0 } } },
{ { { 56, 0, 2 }, { 54, 62, 0 } } },
{ { { 57, 0, 1 }, { 62, 47, 0 } } },
{ { { 57, 0, 0 }, { 54, 63, 0 } } },
{ { { 57, 0, 1 }, { 55, 62, 0 } } },
{ { { 57, 0, 2 }, { 55, 63, 0 } } },
{ { { 58, 0, 1 }, { 56, 62, 1 } } },
{ { { 58, 0, 0 }, { 56, 62, 0 } } },
{ { { 58, 0, 1 }, { 56, 63, 0 } } },
{ { { 58, 0, 2 }, { 57, 62, 0 } } },
{ { { 59, 0, 1 }, { 57, 63, 1 } } },
{ { { 59, 0, 0 }, { 57, 63, 0 } } },
{ { { 59, 0, 1 }, { 58, 62, 0 } } },
{ { { 59, 0, 2 }, { 58, 63, 0 } } },
{ { { 60, 0, 1 }, { 59, 62, 1 } } },
{ { { 60, 0, 0 }, { 59, 62, 0 } } },
{ { { 60, 0, 1 }, { 59, 63, 0 } } },
{ { { 60, 0, 2 }, { 60, 62, 0 } } },
{ { { 61, 0, 1 }, { 60, 63, 1 } } },
{ { { 61, 0, 0 }, { 60, 63, 0 } } },
{ { { 61, 0, 1 }, { 61, 62, 0 } } },
{ { { 61, 0, 2 }, { 61, 63, 0 } } },
{ { { 62, 0, 1 }, { 62, 62, 1 } } },
{ { { 62, 0, 0 }, { 62, 62, 0 } } },
{ { { 62, 0, 1 }, { 62, 63, 0 } } },
{ { { 62, 0, 2 }, { 63, 62, 0 } } },
{ { { 63, 0, 1 }, { 63, 63, 1 } } },
{ { { 63, 0, 0 }, { 63, 63, 0 } } }
};
static const DDSSingleColourLookup*
DDS_LOOKUP[] =
{
DDSLookup_5_4,
DDSLookup_6_4,
DDSLookup_5_4
};
/*
Macros
*/
#define C565_r(x) (((x) & 0xF800) >> 11)
#define C565_g(x) (((x) & 0x07E0) >> 5)
#define C565_b(x) ((x) & 0x001F)
#define C565_red(x) ( (C565_r(x) << 3 | C565_r(x) >> 2))
#define C565_green(x) ( (C565_g(x) << 2 | C565_g(x) >> 4))
#define C565_blue(x) ( (C565_b(x) << 3 | C565_b(x) >> 2))
#define DIV2(x) ((x) > 1 ? ((x) >> 1) : 1)
#define FixRange(min, max, steps) \
if (min > max) \
min = max; \
if ((ssize_t) max - min < steps) \
max = MagickMin(min + steps, 255); \
if ((ssize_t) max - min < steps) \
min = MagickMax(0, (ssize_t) max - steps)
#define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z)
#define VectorInit(vector, value) vector.x = vector.y = vector.z = vector.w \
= value
#define VectorInit3(vector, value) vector.x = vector.y = vector.z = value
#define IsBitMask(mask, r, g, b, a) (mask.r_bitmask == r && mask.g_bitmask == \
g && mask.b_bitmask == b && mask.alpha_bitmask == a)
/*
Forward declarations
*/
static MagickBooleanType
ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3,
DDSVector4 *,DDSVector4 *,unsigned char *,size_t),
ReadDDSInfo(Image *,DDSInfo *),
ReadDXT1(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT3(Image *,DDSInfo *,ExceptionInfo *),
ReadDXT5(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *),
ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *),
SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *),
WriteDDSImage(const ImageInfo *,Image *),
WriteMipmaps(Image *,const size_t,const size_t,const size_t,
const MagickBooleanType,const MagickBooleanType,ExceptionInfo *);
static void
RemapIndices(const ssize_t *,const unsigned char *,unsigned char *),
WriteDDSInfo(Image *,const size_t,const size_t,const size_t),
WriteFourCC(Image *,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType,
const MagickBooleanType,ExceptionInfo *),
WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *),
WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *),
WriteUncompressed(Image *,ExceptionInfo *);
static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right,
DDSVector4 *destination)
{
destination->x = left.x + right.x;
destination->y = left.y + right.y;
destination->z = left.z + right.z;
destination->w = left.w + right.w;
}
static inline void VectorClamp(DDSVector4 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
value->w = MagickMin(1.0f,MagickMax(0.0f,value->w));
}
static inline void VectorClamp3(DDSVector3 *value)
{
value->x = MagickMin(1.0f,MagickMax(0.0f,value->x));
value->y = MagickMin(1.0f,MagickMax(0.0f,value->y));
value->z = MagickMin(1.0f,MagickMax(0.0f,value->z));
}
static inline void VectorCopy43(const DDSVector4 source,
DDSVector3 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void VectorCopy44(const DDSVector4 source,
DDSVector4 *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
destination->w = source.w;
}
static inline void VectorNegativeMultiplySubtract(const DDSVector4 a,
const DDSVector4 b, const DDSVector4 c, DDSVector4 *destination)
{
destination->x = c.x - (a.x * b.x);
destination->y = c.y - (a.y * b.y);
destination->z = c.z - (a.z * b.z);
destination->w = c.w - (a.w * b.w);
}
static inline void VectorMultiply(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
destination->w = left.w * right.w;
}
static inline void VectorMultiply3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x * right.x;
destination->y = left.y * right.y;
destination->z = left.z * right.z;
}
static inline void VectorMultiplyAdd(const DDSVector4 a, const DDSVector4 b,
const DDSVector4 c, DDSVector4 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
destination->w = (a.w * b.w) + c.w;
}
static inline void VectorMultiplyAdd3(const DDSVector3 a, const DDSVector3 b,
const DDSVector3 c, DDSVector3 *destination)
{
destination->x = (a.x * b.x) + c.x;
destination->y = (a.y * b.y) + c.y;
destination->z = (a.z * b.z) + c.z;
}
static inline void VectorReciprocal(const DDSVector4 value,
DDSVector4 *destination)
{
destination->x = 1.0f / value.x;
destination->y = 1.0f / value.y;
destination->z = 1.0f / value.z;
destination->w = 1.0f / value.w;
}
static inline void VectorSubtract(const DDSVector4 left,
const DDSVector4 right, DDSVector4 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
destination->w = left.w - right.w;
}
static inline void VectorSubtract3(const DDSVector3 left,
const DDSVector3 right, DDSVector3 *destination)
{
destination->x = left.x - right.x;
destination->y = left.y - right.y;
destination->z = left.z - right.z;
}
static inline void VectorTruncate(DDSVector4 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
value->w = value->w > 0.0f ? floor(value->w) : ceil(value->w);
}
static inline void VectorTruncate3(DDSVector3 *value)
{
value->x = value->x > 0.0f ? floor(value->x) : ceil(value->x);
value->y = value->y > 0.0f ? floor(value->y) : ceil(value->y);
value->z = value->z > 0.0f ? floor(value->z) : ceil(value->z);
}
static void CalculateColors(unsigned short c0, unsigned short c1,
DDSColors *c, MagickBooleanType ignoreAlpha)
{
c->a[0] = c->a[1] = c->a[2] = c->a[3] = 0;
c->r[0] = (unsigned char) C565_red(c0);
c->g[0] = (unsigned char) C565_green(c0);
c->b[0] = (unsigned char) C565_blue(c0);
c->r[1] = (unsigned char) C565_red(c1);
c->g[1] = (unsigned char) C565_green(c1);
c->b[1] = (unsigned char) C565_blue(c1);
if (ignoreAlpha != MagickFalse || c0 > c1)
{
c->r[2] = (unsigned char) ((2 * c->r[0] + c->r[1]) / 3);
c->g[2] = (unsigned char) ((2 * c->g[0] + c->g[1]) / 3);
c->b[2] = (unsigned char) ((2 * c->b[0] + c->b[1]) / 3);
c->r[3] = (unsigned char) ((c->r[0] + 2 * c->r[1]) / 3);
c->g[3] = (unsigned char) ((c->g[0] + 2 * c->g[1]) / 3);
c->b[3] = (unsigned char) ((c->b[0] + 2 * c->b[1]) / 3);
}
else
{
c->r[2] = (unsigned char) ((c->r[0] + c->r[1]) / 2);
c->g[2] = (unsigned char) ((c->g[0] + c->g[1]) / 2);
c->b[2] = (unsigned char) ((c->b[0] + c->b[1]) / 2);
c->r[3] = c->g[3] = c->b[3] = 0;
c->a[3] = 255;
}
}
static size_t CompressAlpha(const size_t min, const size_t max,
const size_t steps, const ssize_t *alphas, unsigned char* indices)
{
unsigned char
codes[8];
register ssize_t
i;
size_t
error,
index,
j,
least,
value;
codes[0] = (unsigned char) min;
codes[1] = (unsigned char) max;
codes[6] = 0;
codes[7] = 255;
for (i=1; i < (ssize_t) steps; i++)
codes[i+1] = (unsigned char) (((steps-i)*min + i*max) / steps);
error = 0;
for (i=0; i<16; i++)
{
if (alphas[i] == -1)
{
indices[i] = 0;
continue;
}
value = alphas[i];
least = SIZE_MAX;
index = 0;
for (j=0; j<8; j++)
{
size_t
dist;
dist = value - (size_t)codes[j];
dist *= dist;
if (dist < least)
{
least = dist;
index = j;
}
}
indices[i] = (unsigned char)index;
error += least;
}
return error;
}
static void CompressClusterFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
DDSVector3
axis;
DDSVector4
grid,
gridrcp,
half,
onethird_onethird2,
pointsWeights[16],
two,
twonineths,
twothirds_twothirds2,
xSumwSum;
float
bestError = 1e+37f;
size_t
bestIteration = 0,
besti = 0,
bestj = 0,
bestk = 0,
iterationIndex;
ssize_t
i;
unsigned char
*o,
order[128],
unordered[16];
VectorInit(half,0.5f);
VectorInit(two,2.0f);
VectorInit(onethird_onethird2,1.0f/3.0f);
onethird_onethird2.w = 1.0f/9.0f;
VectorInit(twothirds_twothirds2,2.0f/3.0f);
twothirds_twothirds2.w = 4.0f/9.0f;
VectorInit(twonineths,2.0f/9.0f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
grid.w = 0.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
gridrcp.w = 0.0f;
xSumwSum.x = 0.0f;
xSumwSum.y = 0.0f;
xSumwSum.z = 0.0f;
xSumwSum.w = 0.0f;
ConstructOrdering(count,points,principle,pointsWeights,&xSumwSum,order,0);
for (iterationIndex = 0;;)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(dynamic,1) \
num_threads(GetMagickResourceLimit(ThreadResource))
#endif
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
part0,
part1,
part2;
size_t
ii,
j,
k,
kmin;
VectorInit(part0,0.0f);
for(ii=0; ii < (size_t) i; ii++)
VectorAdd(pointsWeights[ii],part0,&part0);
VectorInit(part1,0.0f);
for (j=(size_t) i;;)
{
if (j == 0)
{
VectorCopy44(pointsWeights[0],&part2);
kmin = 1;
}
else
{
VectorInit(part2,0.0f);
kmin = j;
}
for (k=kmin;;)
{
DDSVector4
a,
alpha2_sum,
alphax_sum,
alphabeta_sum,
b,
beta2_sum,
betax_sum,
e1,
e2,
factor,
part3;
float
error;
VectorSubtract(xSumwSum,part2,&part3);
VectorSubtract(part3,part1,&part3);
VectorSubtract(part3,part0,&part3);
VectorMultiplyAdd(part1,twothirds_twothirds2,part0,&alphax_sum);
VectorMultiplyAdd(part2,onethird_onethird2,alphax_sum,&alphax_sum);
VectorInit(alpha2_sum,alphax_sum.w);
VectorMultiplyAdd(part2,twothirds_twothirds2,part3,&betax_sum);
VectorMultiplyAdd(part1,onethird_onethird2,betax_sum,&betax_sum);
VectorInit(beta2_sum,betax_sum.w);
VectorAdd(part1,part2,&alphabeta_sum);
VectorInit(alphabeta_sum,alphabeta_sum.w);
VectorMultiply(twonineths,alphabeta_sum,&alphabeta_sum);
VectorMultiply(alpha2_sum,beta2_sum,&factor);
VectorNegativeMultiplySubtract(alphabeta_sum,alphabeta_sum,factor,
&factor);
VectorReciprocal(factor,&factor);
VectorMultiply(alphax_sum,beta2_sum,&a);
VectorNegativeMultiplySubtract(betax_sum,alphabeta_sum,a,&a);
VectorMultiply(a,factor,&a);
VectorMultiply(betax_sum,alpha2_sum,&b);
VectorNegativeMultiplySubtract(alphax_sum,alphabeta_sum,b,&b);
VectorMultiply(b,factor,&b);
VectorClamp(&a);
VectorMultiplyAdd(grid,a,half,&a);
VectorTruncate(&a);
VectorMultiply(a,gridrcp,&a);
VectorClamp(&b);
VectorMultiplyAdd(grid,b,half,&b);
VectorTruncate(&b);
VectorMultiply(b,gridrcp,&b);
VectorMultiply(b,b,&e1);
VectorMultiply(e1,beta2_sum,&e1);
VectorMultiply(a,a,&e2);
VectorMultiplyAdd(e2,alpha2_sum,e1,&e1);
VectorMultiply(a,b,&e2);
VectorMultiply(e2,alphabeta_sum,&e2);
VectorNegativeMultiplySubtract(a,alphax_sum,e2,&e2);
VectorNegativeMultiplySubtract(b,betax_sum,e2,&e2);
VectorMultiplyAdd(two,e2,e1,&e2);
VectorMultiply(e2,metric,&e2);
error = e2.x + e2.y + e2.z;
if (error < bestError)
{
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp critical (DDS_CompressClusterFit)
#endif
{
if (error < bestError)
{
VectorCopy43(a,start);
VectorCopy43(b,end);
bestError = error;
besti = i;
bestj = j;
bestk = k;
bestIteration = iterationIndex;
}
}
}
if (k == count)
break;
VectorAdd(pointsWeights[k],part2,&part2);
k++;
}
if (j == count)
break;
VectorAdd(pointsWeights[j],part1,&part1);
j++;
}
}
if (bestIteration != iterationIndex)
break;
iterationIndex++;
if (iterationIndex == 8)
break;
VectorSubtract3(*end,*start,&axis);
if (ConstructOrdering(count,points,axis,pointsWeights,&xSumwSum,order,
iterationIndex) == MagickFalse)
break;
}
o = order + (16*bestIteration);
for (i=0; i < (ssize_t) besti; i++)
unordered[o[i]] = 0;
for (i=besti; i < (ssize_t) bestj; i++)
unordered[o[i]] = 2;
for (i=bestj; i < (ssize_t) bestk; i++)
unordered[o[i]] = 3;
for (i=bestk; i < (ssize_t) count; i++)
unordered[o[i]] = 1;
RemapIndices(map,unordered,indices);
}
static void CompressRangeFit(const size_t count,
const DDSVector4 *points, const ssize_t *map, const DDSVector3 principle,
const DDSVector4 metric, DDSVector3 *start, DDSVector3 *end,
unsigned char *indices)
{
float
d,
bestDist,
max,
min,
val;
DDSVector3
codes[4],
grid,
gridrcp,
half,
dist;
register ssize_t
i;
size_t
bestj,
j;
unsigned char
closest[16];
VectorInit3(half,0.5f);
grid.x = 31.0f;
grid.y = 63.0f;
grid.z = 31.0f;
gridrcp.x = 1.0f/31.0f;
gridrcp.y = 1.0f/63.0f;
gridrcp.z = 1.0f/31.0f;
if (count > 0)
{
VectorCopy43(points[0],start);
VectorCopy43(points[0],end);
min = max = Dot(points[0],principle);
for (i=1; i < (ssize_t) count; i++)
{
val = Dot(points[i],principle);
if (val < min)
{
VectorCopy43(points[i],start);
min = val;
}
else if (val > max)
{
VectorCopy43(points[i],end);
max = val;
}
}
}
VectorClamp3(start);
VectorMultiplyAdd3(grid,*start,half,start);
VectorTruncate3(start);
VectorMultiply3(*start,gridrcp,start);
VectorClamp3(end);
VectorMultiplyAdd3(grid,*end,half,end);
VectorTruncate3(end);
VectorMultiply3(*end,gridrcp,end);
codes[0] = *start;
codes[1] = *end;
codes[2].x = (start->x * (2.0f/3.0f)) + (end->x * (1.0f/3.0f));
codes[2].y = (start->y * (2.0f/3.0f)) + (end->y * (1.0f/3.0f));
codes[2].z = (start->z * (2.0f/3.0f)) + (end->z * (1.0f/3.0f));
codes[3].x = (start->x * (1.0f/3.0f)) + (end->x * (2.0f/3.0f));
codes[3].y = (start->y * (1.0f/3.0f)) + (end->y * (2.0f/3.0f));
codes[3].z = (start->z * (1.0f/3.0f)) + (end->z * (2.0f/3.0f));
for (i=0; i < (ssize_t) count; i++)
{
bestDist = 1e+37f;
bestj = 0;
for (j=0; j < 4; j++)
{
dist.x = (points[i].x - codes[j].x) * metric.x;
dist.y = (points[i].y - codes[j].y) * metric.y;
dist.z = (points[i].z - codes[j].z) * metric.z;
d = Dot(dist,dist);
if (d < bestDist)
{
bestDist = d;
bestj = j;
}
}
closest[i] = (unsigned char) bestj;
}
RemapIndices(map, closest, indices);
}
static void ComputeEndPoints(const DDSSingleColourLookup *lookup[],
const unsigned char *color, DDSVector3 *start, DDSVector3 *end,
unsigned char *index)
{
register ssize_t
i;
size_t
c,
maxError = SIZE_MAX;
for (i=0; i < 2; i++)
{
const DDSSourceBlock*
sources[3];
size_t
error = 0;
for (c=0; c < 3; c++)
{
sources[c] = &lookup[c][color[c]].sources[i];
error += ((size_t) sources[c]->error) * ((size_t) sources[c]->error);
}
if (error > maxError)
continue;
start->x = (float) sources[0]->start / 31.0f;
start->y = (float) sources[1]->start / 63.0f;
start->z = (float) sources[2]->start / 31.0f;
end->x = (float) sources[0]->end / 31.0f;
end->y = (float) sources[1]->end / 63.0f;
end->z = (float) sources[2]->end / 31.0f;
*index = (unsigned char) (2*i);
maxError = error;
}
}
static void ComputePrincipleComponent(const float *covariance,
DDSVector3 *principle)
{
DDSVector4
row0,
row1,
row2,
v;
register ssize_t
i;
row0.x = covariance[0];
row0.y = covariance[1];
row0.z = covariance[2];
row0.w = 0.0f;
row1.x = covariance[1];
row1.y = covariance[3];
row1.z = covariance[4];
row1.w = 0.0f;
row2.x = covariance[2];
row2.y = covariance[4];
row2.z = covariance[5];
row2.w = 0.0f;
VectorInit(v,1.0f);
for (i=0; i < 8; i++)
{
DDSVector4
w;
float
a;
w.x = row0.x * v.x;
w.y = row0.y * v.x;
w.z = row0.z * v.x;
w.w = row0.w * v.x;
w.x = (row1.x * v.y) + w.x;
w.y = (row1.y * v.y) + w.y;
w.z = (row1.z * v.y) + w.z;
w.w = (row1.w * v.y) + w.w;
w.x = (row2.x * v.z) + w.x;
w.y = (row2.y * v.z) + w.y;
w.z = (row2.z * v.z) + w.z;
w.w = (row2.w * v.z) + w.w;
a = (float) PerceptibleReciprocal(MagickMax(w.x,MagickMax(w.y,w.z)));
v.x = w.x * a;
v.y = w.y * a;
v.z = w.z * a;
v.w = w.w * a;
}
VectorCopy43(v,principle);
}
static void ComputeWeightedCovariance(const size_t count,
const DDSVector4 *points, float *covariance)
{
DDSVector3
centroid;
float
total;
size_t
i;
total = 0.0f;
VectorInit3(centroid,0.0f);
for (i=0; i < count; i++)
{
total += points[i].w;
centroid.x += (points[i].x * points[i].w);
centroid.y += (points[i].y * points[i].w);
centroid.z += (points[i].z * points[i].w);
}
if( total > 1.192092896e-07F)
{
centroid.x /= total;
centroid.y /= total;
centroid.z /= total;
}
for (i=0; i < 6; i++)
covariance[i] = 0.0f;
for (i = 0; i < count; i++)
{
DDSVector3
a,
b;
a.x = points[i].x - centroid.x;
a.y = points[i].y - centroid.y;
a.z = points[i].z - centroid.z;
b.x = points[i].w * a.x;
b.y = points[i].w * a.y;
b.z = points[i].w * a.z;
covariance[0] += a.x*b.x;
covariance[1] += a.x*b.y;
covariance[2] += a.x*b.z;
covariance[3] += a.y*b.y;
covariance[4] += a.y*b.z;
covariance[5] += a.z*b.z;
}
}
static MagickBooleanType ConstructOrdering(const size_t count,
const DDSVector4 *points, const DDSVector3 axis, DDSVector4 *pointsWeights,
DDSVector4 *xSumwSum, unsigned char *order, size_t iteration)
{
float
dps[16],
f;
register ssize_t
i;
size_t
j;
unsigned char
c,
*o,
*p;
o = order + (16*iteration);
for (i=0; i < (ssize_t) count; i++)
{
dps[i] = Dot(points[i],axis);
o[i] = (unsigned char)i;
}
for (i=0; i < (ssize_t) count; i++)
{
for (j=i; j > 0 && dps[j] < dps[j - 1]; j--)
{
f = dps[j];
dps[j] = dps[j - 1];
dps[j - 1] = f;
c = o[j];
o[j] = o[j - 1];
o[j - 1] = c;
}
}
for (i=0; i < (ssize_t) iteration; i++)
{
MagickBooleanType
same;
p = order + (16*i);
same = MagickTrue;
for (j=0; j < count; j++)
{
if (o[j] != p[j])
{
same = MagickFalse;
break;
}
}
if (same != MagickFalse)
return MagickFalse;
}
xSumwSum->x = 0;
xSumwSum->y = 0;
xSumwSum->z = 0;
xSumwSum->w = 0;
for (i=0; i < (ssize_t) count; i++)
{
DDSVector4
v;
j = (size_t) o[i];
v.x = points[j].w * points[j].x;
v.y = points[j].w * points[j].y;
v.z = points[j].w * points[j].z;
v.w = points[j].w * 1.0f;
VectorCopy44(v,&pointsWeights[i]);
VectorAdd(*xSumwSum,v,xSumwSum);
}
return MagickTrue;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s D D S %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsDDS() returns MagickTrue if the image format type, identified by the
% magick string, is DDS.
%
% The format of the IsDDS method is:
%
% MagickBooleanType IsDDS(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: compare image format pattern against these bytes.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsDDS(const unsigned char *magick, const size_t length)
{
if (length < 4)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"DDS ", 4) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadDDSImage() reads a DirectDraw Surface image file and returns it. It
% allocates the memory necessary for the new Image structure and returns a
% pointer to the new image.
%
% The format of the ReadDDSImage method is:
%
% Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: The image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
Image
*image;
MagickBooleanType
status,
cubemap = MagickFalse,
volume = MagickFalse,
matte;
CompressionType
compression;
DDSInfo
dds_info;
DDSDecoder
*decoder;
size_t
n,
num_images;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Initialize image structure.
*/
if (ReadDDSInfo(image, &dds_info) != MagickTrue)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP)
cubemap = MagickTrue;
if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0)
volume = MagickTrue;
(void) SeekBlob(image, 128, SEEK_SET);
/*
Determine pixel format
*/
if (dds_info.pixelformat.flags & DDPF_RGB)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
matte = MagickTrue;
decoder = ReadUncompressedRGBA;
}
else
{
matte = MagickTrue;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_LUMINANCE)
{
compression = NoCompression;
if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS)
{
/* Not sure how to handle this */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
else
{
matte = MagickFalse;
decoder = ReadUncompressedRGB;
}
}
else if (dds_info.pixelformat.flags & DDPF_FOURCC)
{
switch (dds_info.pixelformat.fourcc)
{
case FOURCC_DXT1:
{
matte = MagickFalse;
compression = DXT1Compression;
decoder = ReadDXT1;
break;
}
case FOURCC_DXT3:
{
matte = MagickTrue;
compression = DXT3Compression;
decoder = ReadDXT3;
break;
}
case FOURCC_DXT5:
{
matte = MagickTrue;
compression = DXT5Compression;
decoder = ReadDXT5;
break;
}
default:
{
/* Unknown FOURCC */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
}
}
else
{
/* Neither compressed nor uncompressed... thus unsupported */
ThrowReaderException(CorruptImageError, "ImageTypeNotSupported");
}
num_images = 1;
if (cubemap)
{
/*
Determine number of faces defined in the cubemap
*/
num_images = 0;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++;
if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++;
}
if (volume)
num_images = dds_info.depth;
if ((num_images == 0) || (num_images > GetBlobSize(image)))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (AcquireMagickResource(ListLengthResource,num_images) == MagickFalse)
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
for (n = 0; n < num_images; n++)
{
if (n != 0)
{
if (EOFBlob(image) != MagickFalse)
ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile");
/* Start a new image */
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
return(DestroyImageList(image));
image=SyncNextImageInList(image);
}
image->matte = matte;
image->compression = compression;
image->columns = dds_info.width;
image->rows = dds_info.height;
image->storage_class = DirectClass;
image->endian = LSBEndian;
image->depth = 8;
if (image_info->ping != MagickFalse)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image);
if ((decoder)(image, &dds_info, exception) != MagickTrue)
{
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
}
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
static MagickBooleanType ReadDDSInfo(Image *image, DDSInfo *dds_info)
{
size_t
hdr_size,
required;
/* Seek to start of header */
(void) SeekBlob(image, 4, SEEK_SET);
/* Check header field */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 124)
return MagickFalse;
/* Fill in DDS info struct */
dds_info->flags = ReadBlobLSBLong(image);
/* Check required flags */
required=(size_t) (DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT);
if ((dds_info->flags & required) != required)
return MagickFalse;
dds_info->height = ReadBlobLSBLong(image);
dds_info->width = ReadBlobLSBLong(image);
dds_info->pitchOrLinearSize = ReadBlobLSBLong(image);
dds_info->depth = ReadBlobLSBLong(image);
dds_info->mipmapcount = ReadBlobLSBLong(image);
(void) SeekBlob(image, 44, SEEK_CUR); /* reserved region of 11 DWORDs */
/* Read pixel format structure */
hdr_size = ReadBlobLSBLong(image);
if (hdr_size != 32)
return MagickFalse;
dds_info->pixelformat.flags = ReadBlobLSBLong(image);
dds_info->pixelformat.fourcc = ReadBlobLSBLong(image);
dds_info->pixelformat.rgb_bitcount = ReadBlobLSBLong(image);
dds_info->pixelformat.r_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.g_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.b_bitmask = ReadBlobLSBLong(image);
dds_info->pixelformat.alpha_bitmask = ReadBlobLSBLong(image);
dds_info->ddscaps1 = ReadBlobLSBLong(image);
dds_info->ddscaps2 = ReadBlobLSBLong(image);
(void) SeekBlob(image, 12, SEEK_CUR); /* 3 reserved DWORDs */
return MagickTrue;
}
static MagickBooleanType ReadDXT1(Image *image,DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
PixelPacket
*q;
register ssize_t
i,
x;
size_t
bits;
ssize_t
j,
y;
unsigned char
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) image->rows; y += 4)
{
for (x = 0; x < (ssize_t) image->columns; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q=QueueAuthenticPixels(image,x,y,MagickMin(4,image->columns-x),
MagickMin(4,image->rows-y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickFalse);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (((x + i) < (ssize_t) image->columns) &&
((y + j) < (ssize_t) image->rows))
{
code=(unsigned char) ((bits >> ((j*4+i)*2)) & 0x3);
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
SetPixelOpacity(q,ScaleCharToQuantum(colors.a[code]));
if ((colors.a[code] != 0) && (image->matte == MagickFalse))
image->matte=MagickTrue; /* Correct matte */
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,8,exception));
}
static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
alpha;
size_t
a0,
a1,
bits,
code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = ReadBlobLSBLong(image);
a1 = ReadBlobLSBLong(image);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/*
Extract alpha value: multiply 0..15 by 17 to get range 0..255
*/
if (j < 2)
alpha = 17U * (unsigned char) ((a0 >> (4*(4*j+i))) & 0xf);
else
alpha = 17U * (unsigned char) ((a1 >> (4*(4*(j-2)+i))) & 0xf);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
DDSColors
colors;
ssize_t
j,
y;
MagickSizeType
alpha_bits;
PixelPacket
*q;
register ssize_t
i,
x;
unsigned char
a0,
a1;
size_t
alpha,
bits,
code,
alpha_code;
unsigned short
c0,
c1;
for (y = 0; y < (ssize_t) dds_info->height; y += 4)
{
for (x = 0; x < (ssize_t) dds_info->width; x += 4)
{
/* Get 4x4 patch of pixels to write on */
q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x),
MagickMin(4, dds_info->height - y),exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
/* Read alpha values (8 bytes) */
a0 = (unsigned char) ReadBlobByte(image);
a1 = (unsigned char) ReadBlobByte(image);
alpha_bits = (MagickSizeType)ReadBlobLSBLong(image);
alpha_bits = alpha_bits | ((MagickSizeType)ReadBlobLSBShort(image) << 32);
/* Read 8 bytes of data from the image */
c0 = ReadBlobLSBShort(image);
c1 = ReadBlobLSBShort(image);
bits = ReadBlobLSBLong(image);
CalculateColors(c0, c1, &colors, MagickTrue);
if (EOFBlob(image) != MagickFalse)
break;
/* Write the pixels */
for (j = 0; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if ((x + i) < (ssize_t) dds_info->width && (y + j) < (ssize_t) dds_info->height)
{
code = (bits >> ((4*j+i)*2)) & 0x3;
SetPixelRed(q,ScaleCharToQuantum(colors.r[code]));
SetPixelGreen(q,ScaleCharToQuantum(colors.g[code]));
SetPixelBlue(q,ScaleCharToQuantum(colors.b[code]));
/* Extract alpha value */
alpha_code = (size_t) (alpha_bits >> (3*(4*j+i))) & 0x7;
if (alpha_code == 0)
alpha = a0;
else if (alpha_code == 1)
alpha = a1;
else if (a0 > a1)
alpha = ((8-alpha_code) * a0 + (alpha_code-1) * a1) / 7;
else if (alpha_code == 6)
alpha = 0;
else if (alpha_code == 7)
alpha = 255;
else
alpha = (((6-alpha_code) * a0 + (alpha_code-1) * a1) / 5);
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
alpha));
q++;
}
}
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
if (EOFBlob(image) != MagickFalse)
break;
}
return(SkipDXTMipmaps(image,dds_info,16,exception));
}
static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
x, y;
unsigned short
color;
if (dds_info->pixelformat.rgb_bitcount == 8)
(void) SetImageType(image,GrayscaleType);
else if (dds_info->pixelformat.rgb_bitcount == 16 && !IsBitMask(
dds_info->pixelformat,0xf800,0x07e0,0x001f,0x0000))
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 8)
SetPixelGray(q,ScaleCharToQuantum(ReadBlobByte(image)));
else if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
(((color >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 5) >> 10)/63.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
if (dds_info->pixelformat.rgb_bitcount == 32)
(void) ReadBlobByte(image);
}
SetPixelAlpha(q,QuantumRange);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,3,exception));
}
static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info,
ExceptionInfo *exception)
{
PixelPacket
*q;
ssize_t
alphaBits,
x,
y;
unsigned short
color;
alphaBits=0;
if (dds_info->pixelformat.rgb_bitcount == 16)
{
if (IsBitMask(dds_info->pixelformat,0x7c00,0x03e0,0x001f,0x8000))
alphaBits=1;
else if (IsBitMask(dds_info->pixelformat,0x00ff,0x00ff,0x00ff,0xff00))
{
alphaBits=2;
(void) SetImageType(image,GrayscaleMatteType);
}
else if (IsBitMask(dds_info->pixelformat,0x0f00,0x00f0,0x000f,0xf000))
alphaBits=4;
else
ThrowBinaryException(CorruptImageError,"ImageTypeNotSupported",
image->filename);
}
for (y = 0; y < (ssize_t) dds_info->height; y++)
{
q = QueueAuthenticPixels(image, 0, y, dds_info->width, 1,exception);
if (q == (PixelPacket *) NULL)
return MagickFalse;
for (x = 0; x < (ssize_t) dds_info->width; x++)
{
if (dds_info->pixelformat.rgb_bitcount == 16)
{
color=ReadBlobShort(image);
if (alphaBits == 1)
{
SetPixelAlpha(q,(color & (1 << 15)) ? QuantumRange : 0);
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 1) >> 11)/31.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 6) >> 11)/31.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 11) >> 11)/31.0)*255)));
}
else if (alphaBits == 2)
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(color >> 8)));
SetPixelGray(q,ScaleCharToQuantum((unsigned char)color));
}
else
{
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
(((color >> 12)/15.0)*255)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 4) >> 12)/15.0)*255)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 8) >> 12)/15.0)*255)));
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
((((unsigned short)(color << 12) >> 12)/15.0)*255)));
}
}
else
{
SetPixelBlue(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelGreen(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelRed(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
SetPixelAlpha(q,ScaleCharToQuantum((unsigned char)
ReadBlobByte(image)));
}
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
return MagickFalse;
}
return(SkipRGBMipmaps(image,dds_info,4,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterDDSImage() adds attributes for the DDS image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterDDSImage method is:
%
% RegisterDDSImage(void)
%
*/
ModuleExport size_t RegisterDDSImage(void)
{
MagickInfo
*entry;
entry = SetMagickInfo("DDS");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->magick_module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT1");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->magick_module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
entry = SetMagickInfo("DXT5");
entry->decoder = (DecodeImageHandler *) ReadDDSImage;
entry->encoder = (EncodeImageHandler *) WriteDDSImage;
entry->magick = (IsImageFormatHandler *) IsDDS;
entry->seekable_stream=MagickTrue;
entry->description = ConstantString("Microsoft DirectDraw Surface");
entry->magick_module = ConstantString("DDS");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
static void RemapIndices(const ssize_t *map, const unsigned char *source,
unsigned char *target)
{
register ssize_t
i;
for (i = 0; i < 16; i++)
{
if (map[i] == -1)
target[i] = 3;
else
target[i] = source[map[i]];
}
}
/*
Skip the mipmap images for compressed (DXTn) dds files
*/
static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info,
int texel_size,ExceptionInfo *exception)
{
register ssize_t
i;
MagickOffsetType
offset;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageWarning,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i = 1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) ((w + 3) / 4) * ((h + 3) / 4) * texel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
if ((w == 1) && (h == 1))
break;
w = DIV2(w);
h = DIV2(h);
}
}
return(MagickTrue);
}
/*
Skip the mipmap images for uncompressed (RGB or RGBA) dds files
*/
static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info,
int pixel_size,ExceptionInfo *exception)
{
MagickOffsetType
offset;
register ssize_t
i;
size_t
h,
w;
/*
Only skip mipmaps for textures and cube maps
*/
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
return(MagickFalse);
}
if (dds_info->ddscaps1 & DDSCAPS_MIPMAP
&& (dds_info->ddscaps1 & DDSCAPS_TEXTURE
|| dds_info->ddscaps2 & DDSCAPS2_CUBEMAP))
{
w = DIV2(dds_info->width);
h = DIV2(dds_info->height);
/*
Mipmapcount includes the main image, so start from one
*/
for (i=1; (i < (ssize_t) dds_info->mipmapcount) && w && h; i++)
{
offset = (MagickOffsetType) w * h * pixel_size;
if (SeekBlob(image,offset,SEEK_CUR) < 0)
break;
w = DIV2(w);
h = DIV2(h);
if ((w == 1) && (h == 1))
break;
}
}
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterDDSImage() removes format registrations made by the
% DDS module from the list of supported formats.
%
% The format of the UnregisterDDSImage method is:
%
% UnregisterDDSImage(void)
%
*/
ModuleExport void UnregisterDDSImage(void)
{
(void) UnregisterMagickInfo("DDS");
(void) UnregisterMagickInfo("DXT1");
(void) UnregisterMagickInfo("DXT5");
}
static void WriteAlphas(Image *image, const ssize_t* alphas, size_t min5,
size_t max5, size_t min7, size_t max7)
{
register ssize_t
i;
size_t
err5,
err7,
j;
unsigned char
indices5[16],
indices7[16];
FixRange(min5,max5,5);
err5 = CompressAlpha(min5,max5,5,alphas,indices5);
FixRange(min7,max7,7);
err7 = CompressAlpha(min7,max7,7,alphas,indices7);
if (err7 < err5)
{
for (i=0; i < 16; i++)
{
unsigned char
index;
index = indices7[i];
if( index == 0 )
indices5[i] = 1;
else if (index == 1)
indices5[i] = 0;
else
indices5[i] = 9 - index;
}
min5 = max7;
max5 = min7;
}
(void) WriteBlobByte(image,(unsigned char) min5);
(void) WriteBlobByte(image,(unsigned char) max5);
for(i=0; i < 2; i++)
{
size_t
value = 0;
for (j=0; j < 8; j++)
{
size_t index = (size_t) indices5[j + i*8];
value |= ( index << 3*j );
}
for (j=0; j < 3; j++)
{
size_t byte = (value >> 8*j) & 0xff;
(void) WriteBlobByte(image,(unsigned char) byte);
}
}
}
static void WriteCompressed(Image *image, const size_t count,
DDSVector4* points, const ssize_t* map, const MagickBooleanType clusterFit)
{
float
covariance[16];
DDSVector3
end,
principle,
start;
DDSVector4
metric;
unsigned char
indices[16];
VectorInit(metric,1.0f);
VectorInit3(start,0.0f);
VectorInit3(end,0.0f);
ComputeWeightedCovariance(count,points,covariance);
ComputePrincipleComponent(covariance,&principle);
if (clusterFit == MagickFalse || count == 0)
CompressRangeFit(count,points,map,principle,metric,&start,&end,indices);
else
CompressClusterFit(count,points,map,principle,metric,&start,&end,indices);
WriteIndices(image,start,end,indices);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e D D S I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteDDSImage() writes a DirectDraw Surface image file in the DXT5 format.
%
% The format of the WriteBMPImage method is:
%
% MagickBooleanType WriteDDSImage(const ImageInfo *image_info,Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteDDSImage(const ImageInfo *image_info,
Image *image)
{
const char
*option;
size_t
compression,
columns,
maxMipmaps,
mipmaps,
pixelFormat,
rows;
MagickBooleanType
clusterFit,
status,
weightByAlpha;
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
(void) TransformImageColorspace(image,sRGBColorspace);
pixelFormat=DDPF_FOURCC;
compression=FOURCC_DXT5;
if (!image->matte)
compression=FOURCC_DXT1;
if (LocaleCompare(image_info->magick,"dxt1") == 0)
compression=FOURCC_DXT1;
option=GetImageOption(image_info,"dds:compression");
if (option != (char *) NULL)
{
if (LocaleCompare(option,"dxt1") == 0)
compression=FOURCC_DXT1;
if (LocaleCompare(option,"none") == 0)
pixelFormat=DDPF_RGB;
}
clusterFit=MagickFalse;
weightByAlpha=MagickFalse;
if (pixelFormat == DDPF_FOURCC)
{
option=GetImageOption(image_info,"dds:cluster-fit");
if (IsStringTrue(option) != MagickFalse)
{
clusterFit=MagickTrue;
if (compression != FOURCC_DXT1)
{
option=GetImageOption(image_info,"dds:weight-by-alpha");
if (IsStringTrue(option) != MagickFalse)
weightByAlpha=MagickTrue;
}
}
}
maxMipmaps=SIZE_MAX;
mipmaps=0;
if ((image->columns & (image->columns - 1)) == 0 &&
(image->rows & (image->rows - 1)) == 0)
{
option=GetImageOption(image_info,"dds:mipmaps");
if (option != (char *) NULL)
maxMipmaps=StringToUnsignedLong(option);
if (maxMipmaps != 0)
{
columns=image->columns;
rows=image->rows;
while ((columns != 1 || rows != 1) && mipmaps != maxMipmaps)
{
columns=DIV2(columns);
rows=DIV2(rows);
mipmaps++;
}
}
}
WriteDDSInfo(image,pixelFormat,compression,mipmaps);
WriteImageData(image,pixelFormat,compression,clusterFit,weightByAlpha,
&image->exception);
if (mipmaps > 0 && WriteMipmaps(image,pixelFormat,compression,mipmaps,
clusterFit,weightByAlpha,&image->exception) == MagickFalse)
return(MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
static void WriteDDSInfo(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps)
{
char
software[MaxTextExtent];
register ssize_t
i;
unsigned int
format,
caps,
flags;
flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT |
DDSD_PIXELFORMAT);
caps=(unsigned int) DDSCAPS_TEXTURE;
format=(unsigned int) pixelFormat;
if (format == DDPF_FOURCC)
flags=flags | DDSD_LINEARSIZE;
else
flags=flags | DDSD_PITCH;
if (mipmaps > 0)
{
flags=flags | (unsigned int) DDSD_MIPMAPCOUNT;
caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX);
}
if (format != DDPF_FOURCC && image->matte)
format=format | DDPF_ALPHAPIXELS;
(void) WriteBlob(image,4,(unsigned char *) "DDS ");
(void) WriteBlobLSBLong(image,124);
(void) WriteBlobLSBLong(image,flags);
(void) WriteBlobLSBLong(image,(unsigned int) image->rows);
(void) WriteBlobLSBLong(image,(unsigned int) image->columns);
if (pixelFormat == DDPF_FOURCC)
{
/* Compressed DDS requires linear compressed size of first image */
if (compression == FOURCC_DXT1)
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*8));
else /* DXT5 */
(void) WriteBlobLSBLong(image,(unsigned int) (MagickMax(1,
(image->columns+3)/4)*MagickMax(1,(image->rows+3)/4)*16));
}
else
{
/* Uncompressed DDS requires byte pitch of first image */
if (image->matte != MagickFalse)
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 4));
else
(void) WriteBlobLSBLong(image,(unsigned int) (image->columns * 3));
}
(void) WriteBlobLSBLong(image,0x00);
(void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);
(void) memset(software,0,sizeof(software));
(void) CopyMagickString(software,"IMAGEMAGICK",MaxTextExtent);
(void) WriteBlob(image,44,(unsigned char *) software);
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,format);
if (pixelFormat == DDPF_FOURCC)
{
(void) WriteBlobLSBLong(image,(unsigned int) compression);
for(i=0;i < 5;i++) /* bitcount / masks */
(void) WriteBlobLSBLong(image,0x00);
}
else
{
(void) WriteBlobLSBLong(image,0x00);
if (image->matte != MagickFalse)
{
(void) WriteBlobLSBLong(image,32);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0xff000000);
}
else
{
(void) WriteBlobLSBLong(image,24);
(void) WriteBlobLSBLong(image,0xff0000);
(void) WriteBlobLSBLong(image,0xff00);
(void) WriteBlobLSBLong(image,0xff);
(void) WriteBlobLSBLong(image,0x00);
}
}
(void) WriteBlobLSBLong(image,caps);
for(i=0;i < 4;i++) /* ddscaps2 + reserved region */
(void) WriteBlobLSBLong(image,0x00);
}
static void WriteFourCC(Image *image, const size_t compression,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
i,
y,
bx,
by;
for (y=0; y < (ssize_t) image->rows; y+=4)
{
for (x=0; x < (ssize_t) image->columns; x+=4)
{
MagickBooleanType
match;
DDSVector4
point,
points[16];
size_t
count = 0,
max5 = 0,
max7 = 0,
min5 = 255,
min7 = 255,
columns = 4,
rows = 4;
ssize_t
alphas[16],
map[16];
unsigned char
alpha;
if (x + columns >= image->columns)
columns = image->columns - x;
if (y + rows >= image->rows)
rows = image->rows - y;
p=GetVirtualPixels(image,x,y,columns,rows,exception);
if (p == (const PixelPacket *) NULL)
break;
for (i=0; i<16; i++)
{
map[i] = -1;
alphas[i] = -1;
}
for (by=0; by < (ssize_t) rows; by++)
{
for (bx=0; bx < (ssize_t) columns; bx++)
{
if (compression == FOURCC_DXT5)
alpha = ScaleQuantumToChar(GetPixelAlpha(p));
else
alpha = 255;
if (compression == FOURCC_DXT5)
{
if (alpha < min7)
min7 = alpha;
if (alpha > max7)
max7 = alpha;
if (alpha != 0 && alpha < min5)
min5 = alpha;
if (alpha != 255 && alpha > max5)
max5 = alpha;
}
alphas[4*by + bx] = (size_t)alpha;
point.x = (float)ScaleQuantumToChar(GetPixelRed(p)) / 255.0f;
point.y = (float)ScaleQuantumToChar(GetPixelGreen(p)) / 255.0f;
point.z = (float)ScaleQuantumToChar(GetPixelBlue(p)) / 255.0f;
point.w = weightByAlpha ? (float)(alpha + 1) / 256.0f : 1.0f;
p++;
match = MagickFalse;
for (i=0; i < (ssize_t) count; i++)
{
if ((points[i].x == point.x) &&
(points[i].y == point.y) &&
(points[i].z == point.z) &&
(alpha >= 128 || compression == FOURCC_DXT5))
{
points[i].w += point.w;
map[4*by + bx] = i;
match = MagickTrue;
break;
}
}
if (match != MagickFalse)
continue;
points[count].x = point.x;
points[count].y = point.y;
points[count].z = point.z;
points[count].w = point.w;
map[4*by + bx] = count;
count++;
}
}
for (i=0; i < (ssize_t) count; i++)
points[i].w = sqrt(points[i].w);
if (compression == FOURCC_DXT5)
WriteAlphas(image,alphas,min5,max5,min7,max7);
if (count == 1)
WriteSingleColorFit(image,points,map);
else
WriteCompressed(image,count,points,map,clusterFit);
}
}
}
static void WriteImageData(Image *image, const size_t pixelFormat,
const size_t compression, const MagickBooleanType clusterFit,
const MagickBooleanType weightByAlpha, ExceptionInfo *exception)
{
if (pixelFormat == DDPF_FOURCC)
WriteFourCC(image,compression,clusterFit,weightByAlpha,exception);
else
WriteUncompressed(image,exception);
}
static inline size_t ClampToLimit(const float value,
const size_t limit)
{
size_t
result = (int) (value + 0.5f);
if (result < 0.0f)
return(0);
if (result > limit)
return(limit);
return result;
}
static inline size_t ColorTo565(const DDSVector3 point)
{
size_t r = ClampToLimit(31.0f*point.x,31);
size_t g = ClampToLimit(63.0f*point.y,63);
size_t b = ClampToLimit(31.0f*point.z,31);
return (r << 11) | (g << 5) | b;
}
static void WriteIndices(Image *image, const DDSVector3 start,
const DDSVector3 end, unsigned char* indices)
{
register ssize_t
i;
size_t
a,
b;
unsigned char
remapped[16];
const unsigned char
*ind;
a = ColorTo565(start);
b = ColorTo565(end);
for (i=0; i<16; i++)
{
if( a < b )
remapped[i] = (indices[i] ^ 0x1) & 0x3;
else if( a == b )
remapped[i] = 0;
else
remapped[i] = indices[i];
}
if( a < b )
Swap(a,b);
(void) WriteBlobByte(image,(unsigned char) (a & 0xff));
(void) WriteBlobByte(image,(unsigned char) (a >> 8));
(void) WriteBlobByte(image,(unsigned char) (b & 0xff));
(void) WriteBlobByte(image,(unsigned char) (b >> 8));
for (i=0; i<4; i++)
{
ind = remapped + 4*i;
(void) WriteBlobByte(image,ind[0] | (ind[1] << 2) | (ind[2] << 4) |
(ind[3] << 6));
}
}
static MagickBooleanType WriteMipmaps(Image *image, const size_t pixelFormat,
const size_t compression, const size_t mipmaps,
const MagickBooleanType clusterFit, const MagickBooleanType weightByAlpha,
ExceptionInfo *exception)
{
Image*
resize_image;
register ssize_t
i;
size_t
columns,
rows;
columns = image->columns;
rows = image->rows;
for (i=0; i< (ssize_t) mipmaps; i++)
{
resize_image = ResizeImage(image,DIV2(columns),DIV2(rows),TriangleFilter,1.0,
exception);
if (resize_image == (Image *) NULL)
return(MagickFalse);
DestroyBlob(resize_image);
resize_image->blob=ReferenceBlob(image->blob);
WriteImageData(resize_image,pixelFormat,compression,weightByAlpha,
clusterFit,exception);
resize_image=DestroyImage(resize_image);
columns = DIV2(columns);
rows = DIV2(rows);
}
return(MagickTrue);
}
static void WriteSingleColorFit(Image *image, const DDSVector4* points,
const ssize_t* map)
{
DDSVector3
start,
end;
register ssize_t
i;
unsigned char
color[3],
index,
indexes[16],
indices[16];
color[0] = (unsigned char) ClampToLimit(255.0f*points->x,255);
color[1] = (unsigned char) ClampToLimit(255.0f*points->y,255);
color[2] = (unsigned char) ClampToLimit(255.0f*points->z,255);
index=0;
ComputeEndPoints(DDS_LOOKUP,color,&start,&end,&index);
for (i=0; i< 16; i++)
indexes[i]=index;
RemapIndices(map,indexes,indices);
WriteIndices(image,start,end,indices);
}
static void WriteUncompressed(Image *image, ExceptionInfo *exception)
{
register const PixelPacket
*p;
register ssize_t
x;
ssize_t
y;
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelBlue(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelGreen(p)));
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelRed(p)));
if (image->matte)
(void) WriteBlobByte(image,ScaleQuantumToChar(GetPixelAlpha(p)));
p++;
}
}
}
|
critical.c | #include <stdio.h>
#include <omp.h>
int main()
{
#pragma omp parallel
{
printf("Start of Secret\n");
#pragma omp critical
{
printf("SECRET\n");
}
printf("Secret Delivered\n");
}
} |
stopgp32.c | /* Copyright © 2018-2019 Jakub Wilk <jwilk@jwilk.net>
* SPDX-License-Identifier: MIT
*/
#include <arpa/inet.h>
#include <assert.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include <openssl/bn.h>
#include <openssl/bio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#define PROGRAM_NAME "stopgp32"
#define DEFAULT_USER "<user@example.org>"
static const int rsa_bits = 1024;
static const uint32_t ts_min = 1136073600; /* 2006-01-01 */
static const uint32_t ts_max = 1609459200; /* 2021-01-01 */
static size_t bignum2mpi(const BIGNUM *n, unsigned char *to)
{
int nbits = BN_num_bits(n);
assert(nbits <= 0xFFFF);
to[0] = nbits >> 8;
to[1] = nbits & 0xFF;
size_t size = 2 + BN_bn2bin(n, to + 2);
return size;
}
struct openpgp_packet
{
unsigned char data[0x10000];
};
#if OPENSSL_VERSION_NUMBER < 0x10100000
static void RSA_get0_key(const RSA *rsa, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
{
if (n != NULL)
*n = rsa->n;
if (e != NULL)
*e = rsa->e;
if (d != NULL)
*d = rsa->d;
}
#endif
static void openpgp_from_rsa(struct openpgp_packet *pkt, const RSA *rsa)
{
unsigned char *data = pkt->data;
data[0] = 0x99;
data[3] = 0x04;
data[8] = 0x01;
const BIGNUM *n, *e;
RSA_get0_key(rsa, &n, &e, NULL);
size_t size = 9;
size += bignum2mpi(n, data + size);
size += bignum2mpi(e, data + size);
assert(size <= 0xFFFF);
uint16_t len = htons(size - 3);
memcpy(data + 1, &len, sizeof len);
}
static void openpgp_set_timestamp(struct openpgp_packet *pkt, uint32_t timestamp)
{
timestamp = htonl(timestamp);
memcpy(pkt->data + 4, ×tamp, sizeof timestamp);
}
static void openpgp_fingerprint(const struct openpgp_packet *pkt, unsigned char *sha)
{
size_t size = 3 + (pkt->data[1] << 8) + pkt->data[2];
SHA1(pkt->data, size, sha);
}
static void posix_error(const char *context)
{
int orig_errno = errno;
fprintf(stderr, "%s: ", PROGRAM_NAME);
errno = orig_errno;
perror(context);
exit(EXIT_FAILURE);
}
static void fprintsh(FILE *fp, const char *s)
{
bool escape = true;
for (const char *p = s; *p; p++) {
char c = *p;
if (c >= 'a' && c <= 'z')
escape = false;
else if (c >= 'A' && c <= 'Z')
escape = false;
else if (c >= '0' && c <= '9')
escape = false;
else if (c == '/' || c == '.' || c == ',' || c == '+' || c == '-' || c == '_')
escape = false;
else {
escape = true;
break;
}
}
if (!escape) {
fprintf(fp, "%s", s);
return;
}
fprintf(fp, "'");
for (const char *p = s; *p; p++)
if (*p == '\'')
fprintf(fp, "'\\''");
else
putc(*p, fp);
fprintf(fp, "'");
}
static void printsh(const char *s)
{
fprintsh(stdout, s);
}
struct cache_dir
{
char path[PATH_MAX];
const char *home_path;
DIR *handle;
int fd;
};
static void cache_dir_init(struct cache_dir *o, const char *path, bool real)
{
const char *home = getenv("HOME");
const char *cache_home = getenv("XDG_CACHE_HOME");
if (cache_home && cache_home[0] != '/')
cache_home = NULL;
o->home_path = NULL;
if (path != NULL) {
size_t size = strnlen(path, sizeof o->path);
if (size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error(path);
}
strcpy(o->path, path);
} else if (cache_home) {
int size = snprintf(o->path, sizeof o->path, "%s/" PROGRAM_NAME, cache_home);
if (size < 0)
posix_error(NULL);
if ((size_t) size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error("$XDG_CACHE_HOME/" PROGRAM_NAME);
}
} else {
if ((home == NULL) || (*home == '\0')) {
errno = ENOTDIR;
posix_error("$HOME");
}
int size = snprintf(o->path, sizeof o->path, "%s/.cache/" PROGRAM_NAME, home);
if (size < 0)
posix_error(NULL);
if ((size_t) size >= sizeof o->path) {
errno = ENAMETOOLONG;
posix_error("$HOME/.cache/" PROGRAM_NAME);
}
}
if ((home != NULL) && (*home != '\0')) {
size_t home_len = strlen(home);
if ((strncmp(o->path, home, home_len) == 0) && (o->path[home_len] == '/'))
o->home_path = o->path + home_len + 1;
}
if (!real) {
o->handle = NULL;
o->fd = -1;
return;
}
if (path == NULL) {
char *p = strrchr(o->path, '/');
assert(p != NULL);
*p = '\0';
int rc = mkdir(o->path, 0700);
if (rc < 0 && errno != EEXIST)
posix_error(o->path);
*p = '/';
}
int rc = mkdir(o->path, 0700);
if (rc < 0 && errno != EEXIST)
posix_error(o->path);
o->handle = opendir(o->path);
if (o->handle == NULL)
posix_error(o->path);
o->fd = dirfd(o->handle);
if (o->fd < 0)
posix_error(o->path);
rc = flock(o->fd, LOCK_EX | LOCK_NB);
if (rc < 0)
posix_error(o->path);
}
static void cache_dir_close(struct cache_dir *o)
{
o->path[0] = '\0';
o->home_path = NULL;
if (o->handle != NULL) {
int rc = closedir(o->handle);
if (rc < 0)
posix_error(o->path);
o->handle = NULL;
o->fd = -1;
}
}
static void openssl_error()
{
fprintf(stderr, "%s: ", PROGRAM_NAME);
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
}
static int genrsa_callback(int a, int b, BN_GENCB *cb)
{
(void) a; (void) b; (void) cb;
fprintf(stderr, ".");
return 1;
}
#if OPENSSL_VERSION_NUMBER < 0x10100000
static BN_GENCB *BN_GENCB_new(void)
{
BN_GENCB *cb = malloc(sizeof (BN_GENCB));
if (cb == NULL)
perror(NULL);
return cb;
}
static void BN_GENCB_free(BN_GENCB *cb)
{
free(cb);
}
#endif
static void get_rsa_name(RSA *rsa, char *name)
{
static const char alphabet[] = "ybndrfg8ejkmcpqxot1uwisza345h769";
unsigned char sha[SHA_DIGEST_LENGTH];
struct openpgp_packet pkt;
openpgp_from_rsa(&pkt, rsa);
openpgp_set_timestamp(&pkt, 0);
openpgp_fingerprint(&pkt, sha);
uint64_t rsaid;
memcpy(&rsaid, sha, sizeof rsaid);
strcpy(name, "rsa-");
for (int i = 0; i < 8; i++) {
name[i + 4] = alphabet[rsaid % 32];
rsaid /= 32;
}
strcpy(name + 12, ".pem");
}
static void retrieve_key(struct openpgp_packet *pkt, struct cache_dir *cache_dir, char *name)
{
BIO *io = NULL;
RSA *rsa = NULL;
errno = 0;
struct dirent *ent;
while (true) {
errno = 0;
ent = readdir(cache_dir->handle);
if (ent == NULL)
break;
size_t len = strlen(ent->d_name);
if (len < 5)
continue;
if (strcmp(ent->d_name + (len - 4), ".pem") == 0)
break;
else
continue;
}
if (ent) {
strcpy(name, ent->d_name);
fprintf(stderr, "%s: retrieving RSA key ", PROGRAM_NAME);
fprintsh(stderr, name);
fprintf(stderr, " from cache\n");
int fd = openat(cache_dir->fd, name, O_RDONLY);
if (fd < 0)
posix_error(name);
FILE *fp = fdopen(fd, "r");
if (fp == NULL)
posix_error(name);
io = BIO_new_fp(fp, BIO_CLOSE);
if (io == NULL)
openssl_error();
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(io, NULL, NULL, NULL);
if (pkey == NULL)
openssl_error();
rsa = EVP_PKEY_get1_RSA(pkey);
if (rsa == NULL)
openssl_error();
EVP_PKEY_free(pkey);
} else if (errno == 0) {
fprintf(stderr, "%s: generating new RSA key: ", PROGRAM_NAME);
rsa = RSA_new();
if (rsa == NULL)
openssl_error();
BIGNUM *exp = BN_new();
if (exp == NULL)
openssl_error();
if (!BN_set_word(exp, 0x10001))
openssl_error();
BN_GENCB *cb = BN_GENCB_new();
if (cb == NULL)
openssl_error();
BN_GENCB_set(cb, genrsa_callback, NULL);
if (!RSA_generate_key_ex(rsa, rsa_bits, exp, cb))
openssl_error();
BN_GENCB_free(cb);
BN_free(exp);
get_rsa_name(rsa, name);
fprintf(stderr, " ");
fprintsh(stderr, name);
fprintf(stderr, "\n");
int fd = openat(cache_dir->fd, name, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (fd < 0)
posix_error(name);
FILE *fp = fdopen(fd, "w");
if (fp == NULL)
posix_error(name);
io = BIO_new_fp(fp, BIO_CLOSE);
if (io == NULL)
openssl_error();
if (!PEM_write_bio_RSAPrivateKey(io, rsa, NULL, NULL, 0, NULL, NULL))
openssl_error();
} else
posix_error(cache_dir->path);
assert(rsa != NULL);
openpgp_from_rsa(pkt, rsa);
RSA_free(rsa);
BIO_free_all(io);
}
static double xtime()
{
struct timespec ts;
int rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if (rc < 0)
posix_error("clock_gettime()");
return ts.tv_sec + ts.tv_nsec * 1E-9;
}
struct progress
{
double time;
uint64_t count;
};
static void progress_start(struct progress *obj)
{
obj->time = xtime();
obj->count = 0;
fprintf(stderr, "%s: searching...", PROGRAM_NAME);
}
static void progress_update(struct progress *obj)
{
double t0 = obj->time;
double t = xtime();
if (t > t0) {
double v = obj->count / 1.0E6 / (t - t0);
fprintf(stderr, "\r\033[2K%s: searching... %.2f Mkeys/s", PROGRAM_NAME, v);
}
}
static void progress_stop(struct progress *obj)
{
fprintf(stderr, "\r\033[2K%s: searching...", PROGRAM_NAME);
double t0 = obj->time;
double t = xtime();
if (t > t0) {
double v = obj->count / 1.0E6 / (t - t0);
fprintf(stderr, " %.2f Mkeys/s", v);
}
fprintf(stderr, "\n");
}
static void show_usage(FILE *fp)
{
fprintf(fp, "Usage: %s [-u USERID] [-p] [-d DIR] [-j N] KEYID [KEYID...]\n", PROGRAM_NAME);
if (fp != stdout)
return;
char *cd_path = NULL;
struct cache_dir cd;
cache_dir_init(&cd, NULL, false);
if (cd.home_path != NULL) {
assert(cd.home_path >= cd.path + 2);
cd_path = cd.path + (cd.home_path - cd.path) - 2;
cd_path[0] = '~';
cd_path[1] = '/';
} else
cd_path = cd.path;
fprintf(fp,
"\n"
"Options:\n"
" -u USERID add this user ID (default: " DEFAULT_USER ")\n"
" -p only print pem2openpgp(1) commands; don't run them\n"
" -d DIR cache RSA keys in DIR (default: %s)\n"
" -j N use N threads (default: 1)\n"
" -j auto use as many threads as possible\n"
" -h, --help show this help message and exit\n",
cd_path
);
cache_dir_close(&cd);
}
struct keyidlist
{
size_t len;
size_t count;
uint32_t *keys;
char *found;
};
static struct keyidlist kil_new(size_t len)
{
struct keyidlist obj;
obj.len = obj.count = len;
obj.keys = calloc(len, sizeof (uint32_t));
if (obj.keys == NULL)
posix_error(NULL);
obj.found = calloc(len, 1);
if (obj.found == NULL)
posix_error(NULL);
return obj;
}
static bool kil_crude_check(const struct keyidlist *obj, uint32_t keyid)
{
for (size_t i = 0; i < obj->len; i++)
if (obj->keys[i] == keyid)
return true;
return false;
}
static bool kil_pop(struct keyidlist *obj, uint32_t keyid)
{
for (size_t i = 0; i < obj->len; i++)
if (obj->keys[i] == keyid && obj->found[i] == 0) {
obj->found[i] = 1;
obj->count--;
return true;
}
return false;
}
static void kil_free(struct keyidlist *obj)
{
obj->len = obj->count = 0;
free(obj->keys);
obj->keys = NULL;
free(obj->found);
obj->found = NULL;
}
static void pem2openpgp_print(uint32_t keyid, uint32_t ts, const char *user, const struct cache_dir *cache_dir, const char *pem_name)
{
printf("PEM2OPENPGP_TIMESTAMP=%" PRIu32 " pem2openpgp ", ts);
printsh(user);
printf(" < ");
if (cache_dir->home_path) {
printf("~/");
printsh(cache_dir->home_path);
} else
printsh(cache_dir->path);
printf("/");
printsh(pem_name);
printf(" > %08" PRIX32 ".pgp\n", keyid);
int rc;
if (ferror(stdout)) {
errno = EIO;
rc = EOF;
} else
rc = fflush(stdout);
if (rc == EOF)
posix_error("/dev/stdout");
}
static void xpipe(int pipefd[2])
{
int rc = pipe(pipefd);
if (rc < 0)
posix_error("pipe()");
for (int i = 0; i < 2; i++) {
int flags = fcntl(pipefd[i], F_GETFD);
if (flags < 0)
posix_error("fcntl(..., F_GETFD)");
flags |= FD_CLOEXEC;
int rc = fcntl(pipefd[i], F_SETFD, flags);
if (rc < 0)
posix_error("fcntl(..., F_SETFD, ...)");
}
}
static void serialize_error(int fd, const char *context)
{
int xerrno = errno;
ssize_t n = write(fd, &xerrno, sizeof xerrno);
if (n < 0)
return;
if ((size_t) n != sizeof xerrno)
return;
assert(context != NULL);
n = write(fd, context, strlen(context));
(void) n;
}
static int deserialize_error(int fd, char context[BUFSIZ])
{
int xerrno = 0;
ssize_t n = read(fd, &xerrno, sizeof xerrno);
if (n < 0)
posix_error("read()");
if ((n > 0) && (size_t) n != sizeof xerrno) {
errno = EIO;
posix_error("read()");
}
n = read(fd, context, BUFSIZ - 1);
if (n < 0)
posix_error("read()");
context[n] = '\0';
return xerrno;
}
static void pem2openpgp_exec(uint32_t keyid, uint32_t ts, const char *user, const struct cache_dir *cache_dir, const char *pem_name)
{
bool dry_run = (pem_name == NULL);
char * const argv[] = { "pem2openpgp", (char*) user, (char*) NULL };
int in_fd;
if (dry_run)
in_fd = open("/dev/null", O_RDONLY);
else
in_fd = openat(cache_dir->fd, pem_name, O_RDONLY);
if (in_fd < 0)
posix_error(pem_name);
char tmp_path[13], path[13];
int size = sprintf(tmp_path, "%08" PRIX32 ".tmp", keyid);
if (size < 0)
posix_error(NULL);
size = sprintf(path, "%08" PRIX32 ".pgp", keyid);
if (size < 0)
posix_error(NULL);
if (dry_run) {
strcpy(tmp_path, "/dev/null");
strcpy(path, "/dev/null");
}
int out_fd = open(tmp_path, O_WRONLY | O_TRUNC | O_CREAT, 0600);
if (out_fd < 0)
posix_error(path);
char ts_str[11];
size = sprintf(ts_str, "%" PRIu32, ts);
if (size < 0)
posix_error(NULL);
int rc = setenv("PEM2OPENPGP_TIMESTAMP", ts_str, true);
if (rc < 0)
posix_error("setenv()");
int pipefd[2];
xpipe(pipefd);
pid_t pid = fork();
if (pid < 0)
posix_error("fork()");
if (pid == 0) {
/* child: */
int fd = dup2(in_fd, STDIN_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
close(in_fd);
fd = dup2(out_fd, STDOUT_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
if (dry_run) {
fd = dup2(out_fd, STDERR_FILENO);
if (fd < 0) {
serialize_error(pipefd[1], "dup2()");
abort();
}
}
close(out_fd);
execvp(argv[0], argv);
serialize_error(pipefd[1], argv[0]);
abort();
}
/* parent: */
rc = unsetenv("PEM2OPENPGP_TIMESTAMP");
if (rc < 0)
posix_error("unsetenv()");
rc = close(in_fd);
if (rc < 0)
posix_error("close()");
rc = close(out_fd);
if (rc < 0)
posix_error("close()");
rc = close(pipefd[1]);
if (rc < 0)
posix_error("close()");
int wstatus;
pid = wait(&wstatus);
if (pid < 0)
posix_error("wait()");
char context[BUFSIZ];
int xerrno = deserialize_error(pipefd[0], context);
rc = close(pipefd[0]);
if (rc < 0)
posix_error("close");
if (dry_run && WIFEXITED(wstatus) && (WEXITSTATUS(wstatus) != 0))
return;
else if (!dry_run && WIFEXITED(wstatus) && (WEXITSTATUS(wstatus) == 0)) {
rc = rename(tmp_path, path);
if (rc < 0)
posix_error("rename");
} else if (xerrno == 0) {
if (WIFEXITED(wstatus)) {
int status = WEXITSTATUS(wstatus);
fprintf(stderr, "%s: %s exited with status %d\n", PROGRAM_NAME, argv[0], status);
} else if (WIFSIGNALED(wstatus)) {
int signo = WTERMSIG(wstatus);
fprintf(stderr, "%s: %s was terminated with signal %d (%s)\n", PROGRAM_NAME, argv[0], signo, strsignal(signo));
} else
assert("unexpected wait(2) status" == NULL);
exit(EXIT_FAILURE);
} else {
errno = xerrno;
posix_error(context);
}
}
int main(int argc, char **argv)
{
const char *user = DEFAULT_USER;
const char *cache_path = NULL;
int num_threads = 1;
bool only_print = false;
int opt;
while ((opt = getopt(argc, argv, "u:pd:j:h-:")) != -1)
switch (opt) {
case 'u':
user = optarg;
break;
case 'p':
only_print = true;
break;
case 'd':
cache_path = optarg;
break;
case 'j':
if (strcmp(optarg, "auto") == 0)
num_threads = -1;
else {
char *endarg;
long int l = strtol(optarg, &endarg, 10);
if (*endarg != '\0') {
errno = EINVAL;
posix_error("-j");
}
if (l <= 0 || l >= INT_MAX) {
errno = ERANGE;
posix_error("-j");
}
num_threads = (int) l;
}
break;
case 'h':
show_usage(stdout);
exit(EXIT_SUCCESS);
break;
case '-':
if (strcmp(optarg, "help") == 0) {
show_usage(stdout);
exit(EXIT_SUCCESS);
}
/* fall through */
default:
show_usage(stderr);
exit(EXIT_FAILURE);
}
if (optind >= argc) {
show_usage(stderr);
exit(EXIT_FAILURE);
}
argc -= optind;
argv += optind;
#ifdef _OPENMP
if (num_threads >= 1)
omp_set_num_threads(num_threads);
#else
if (num_threads != 1) {
errno = ENOSYS;
posix_error("-j");
}
#endif
struct keyidlist keyidlist = kil_new(argc);
for (size_t i = 0; i < keyidlist.len; i++) {
const char *arg = argv[i];
for (size_t j = 0; j < 8; j++) {
uint32_t d = arg[j];
if (d >= '0' && d <= '9') {
d -= '0';
} else if (d >= 'a' && d <= 'f') {
d -= 'a' - 10;
} else if (d >= 'A' && d <= 'F') {
d -= 'A' - 10;
} else if (d == '\0') {
fprintf(stderr, "%s: key ID too short: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
} else {
fprintf(stderr, "%s: bad key ID: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
}
keyidlist.keys[i] |= d << ((7 - j) * 4);
}
if (arg[8] != '\0') {
fprintf(stderr, "%s: key ID too long: %s\n", PROGRAM_NAME, arg);
exit(EXIT_FAILURE);
}
}
struct cache_dir cache_dir;
cache_dir_init(&cache_dir, cache_path, true);
if (!only_print)
pem2openpgp_exec(0, 0, "dummy", NULL, NULL);
struct openpgp_packet pkt;
while (true) {
char pem_name[NAME_MAX + 1];
retrieve_key(&pkt, &cache_dir, pem_name);
struct progress progress;
progress_start(&progress);
unsigned int lcount = 0;
#pragma omp parallel for firstprivate(pkt, lcount)
for (uint32_t ts = ts_min; ts < ts_max; ts++) {
lcount++;
unsigned char sha[SHA_DIGEST_LENGTH];
openpgp_set_timestamp(&pkt, ts);
openpgp_fingerprint(&pkt, sha);
uint32_t keyid;
memcpy(&keyid, sha + SHA_DIGEST_LENGTH - sizeof keyid, sizeof keyid);
keyid = ntohl(keyid);
if (kil_crude_check(&keyidlist, keyid))
#pragma omp critical
if (kil_pop(&keyidlist, keyid)) {
progress_stop(&progress);
if (only_print)
pem2openpgp_print(keyid, ts, user, &cache_dir, pem_name);
else {
fprintf(stderr, "%s: found %08" PRIX32 "\n", PROGRAM_NAME, keyid);
pem2openpgp_exec(keyid, ts, user, &cache_dir, pem_name);
}
if (keyidlist.count == 0) {
cache_dir_close(&cache_dir);
kil_free(&keyidlist);
exit(EXIT_SUCCESS);
}
/* FIXME: we should set lcount=0 in all threads */
progress_start(&progress);
}
if (lcount == 0xFFFF) {
/* FIXME: all threads may want to update progress at roughly the same time */
#pragma omp critical
{
progress.count += lcount;
progress_update(&progress);
}
lcount = 0;
}
}
progress_stop(&progress);
}
abort(); /* unreachable */
}
/* vim:set ts=4 sw=4 sts=4 et:*/
|
denseParallelJacobi.h | //
// Created by mbarb on 24/01/2018.
//
#ifndef PARALLELITERATIVE_DENSEPARALLELJACOBI_H
#define PARALLELITERATIVE_DENSEPARALLELJACOBI_H
#include <omp.h>
namespace Iterative {
template <typename Scalar, long long SIZE>
class denseParallelJacobi {
public:
/**
*
* @param A linear system matrix of max rank
* @param b known terms vector
* @param iterations max number of iterations
* @param tolerance min error tolerated
* @param workers number of threads
*/
explicit denseParallelJacobi(
const Eigen::Matrix<Scalar, SIZE, SIZE>& A,
const Eigen::ColumnVector<Scalar, SIZE>& b,
const ulonglong iterations,
const Scalar tolerance,
const ulong workers=0L) :
A(A), b(b), iterations(iterations), tolerance(tolerance),
workers(workers), solution(b) {
solution.fill((Scalar)1/solution.size());
omp_set_num_threads(workers);
}
const Eigen::ColumnVector<Scalar, SIZE> solve() {
Eigen::ColumnVector<Scalar, SIZE> oldSolution(solution);
std::vector<ulonglong> index(solution.size());
for (ulonglong i = 0; i < solution.size(); ++i)
index[i]=i;
std::vector<ulonglong> remove;
for (iteration = 0; iteration < iterations; ++iteration) {
//calculate solutions parallelizing on rows
#pragma omp parallel for schedule(dynamic)
for (auto i = 0; i < index.size(); ++i){
auto el = index[i];
solution[el] = solution_find(b[el], el, oldSolution);
Scalar error = std::abs(solution[el]-oldSolution[el]);
if(error <= tolerance){
#pragma omp critical
remove.emplace_back(i);
}
}
if(!remove.empty()){
std::sort(remove.rbegin(), remove.rend());
for (auto i : remove) {
index.erase(index.begin() + i);
}
remove.clear();
if (index.empty()) break;
}
std::swap(solution, oldSolution);
}
std::cout << iteration << std::endl;
return this->solution;
}
const Eigen::ColumnVector<Scalar, SIZE> &getSolution() const {
return solution;
}
const long getIteration() const {
return iteration;
}
protected:
const Eigen::Matrix<Scalar, SIZE, SIZE>& A;
const Eigen::ColumnVector<Scalar, SIZE>& b;
const ulonglong iterations;
const Scalar tolerance;
const ulong workers;
Eigen::ColumnVector<Scalar, SIZE> solution;
long iteration = 0L;
private:
/**
* utility function implementing the jacobi method in order to find one solution
* @param row coeffiient row
* @param solutions vector solution
* @param term right term vector
* @param index index of the solution
* @return solution component
*/
inline Scalar solution_find(Scalar term, const ulonglong index, Eigen::ColumnVector<Scalar,SIZE>& oldSolution) {
term -= A.row(index) * oldSolution;
return (term + A(index, index) * oldSolution[index]) / A(index, index);
}
};
};
#endif //PARALLELITERATIVE_JACOBI_H
|
macro_expand.c | // RUN: %clang_cc1 -E %s | FileCheck --strict-whitespace %s
#define X() Y
#define Y() X
A: X()()()
// CHECK: {{^}}A: Y{{$}}
// PR3927
#define f(x) h(x
#define for(x) h(x
#define h(x) x()
B: f(f))
C: for(for))
// CHECK: {{^}}B: f(){{$}}
// CHECK: {{^}}C: for(){{$}}
// rdar://6880648
#define f(x,y...) y
f()
// CHECK: #pragma omp parallel for
#define FOO parallel
#define Streaming _Pragma("omp FOO for")
Streaming
|
swap_buffer.c | #include <stdio.h>
#include "wgrib2.h"
/*
* does a byte swap of 4-byte integers/ieee
*
* n should be a multiple of 4
*
* 3/2008 Public Domain Wesley Ebisuzaki
* 7/2015 OpenMP version Wesley Ebisuzaki
*/
int swap_buffer(unsigned char *buffer, unsigned int n) {
unsigned int ii;
unsigned char i, j;
#pragma omp parallel for private(ii, i, j)
for (ii = 0; ii < n; ii += 4) {
i = buffer[ii];
j = buffer[ii+1];
buffer[ii] = buffer[ii+3];
buffer[ii+1] = buffer[ii+2];
buffer[ii+2] = j;
buffer[ii+3] = i;
}
return 0;
}
|
conv_dw_kernel_rv64.c | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Parts of the following code in this file refs to
* https://github.com/Tencent/ncnn/blob/master/src/layer/arm/convolutiondepthwise_5x5.h
* Tencent is pleased to support the open source community by making ncnn
* available.
*
* Copyright (C) 2018 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
*/
/*
* Copyright (c) 2021, OPEN AI LAB
* Author: qtang@openailab.com
*/
#include "conv_dw_kernel_rv64.h"
#include "graph/tensor.h"
#include "graph/node.h"
#include "graph/graph.h"
#include "utility/sys_port.h"
#include "utility/float.h"
#include "utility/log.h"
#include "device/cpu/cpu_node.h"
#include "device/cpu/cpu_graph.h"
#include "device/cpu/cpu_module.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))
static void relu(float* data, int size, int activation)
{
for (int i = 0; i < size; i++)
{
data[i] = max(data[i], ( float )0);
if (activation > 0)
{
data[i] = min(data[i], ( float )activation);
}
}
}
static void pad(float* input, float* output, int in_h, int in_w, int out_h, int out_w, int top, int left, float v)
{
float* ptr = input;
float* outptr = output;
int y = 0;
// fill top
for (; y < top; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
// fill center
for (; y < (top + in_h); y++)
{
int x = 0;
for (; x < left; x++)
{
outptr[x] = v;
}
if (in_w < 12)
{
for (; x < (left + in_w); x++)
{
outptr[x] = ptr[x - left];
}
}
else
{
memcpy(outptr + left, ptr, in_w * sizeof(float));
x += in_w;
}
for (; x < out_w; x++)
{
outptr[x] = v;
}
ptr += in_w;
outptr += out_w;
}
// fill bottom
for (; y < out_h; y++)
{
int x = 0;
for (; x < out_w; x++)
{
outptr[x] = v;
}
outptr += out_w;
}
}
static void convdw3x3s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
float* outptr2 = outptr + outw;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* kernel0 = kernel + g * 9;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i + 1 < outh; i += 2)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
float sum2 = bias0;
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
*outptr = sum;
*outptr2 = sum2;
r0++;
r1++;
r2++;
r3++;
outptr++;
outptr2++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0++;
r1++;
r2++;
outptr++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
}
}
static void convdw3x3s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
const float* kernel0 = kernel + g * 9;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr = sum;
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
}
static void convdw5x5s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
float* outptr2 = outptr + outw;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* kernel0 = kernel + g * 25;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* r4 = img0 + w * 4;
const float* r5 = img0 + w * 5;
const float* k0 = kernel0;
const float* k1 = kernel0 + 5;
const float* k2 = kernel0 + 10;
const float* k3 = kernel0 + 15;
const float* k4 = kernel0 + 20;
int i = 0;
for (; i + 1 < outh; i += 2)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
float sum2 = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r1[3] * k0[3];
sum2 += r1[4] * k0[4];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r2[3] * k1[3];
sum2 += r2[4] * k1[4];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
sum2 += r3[3] * k2[3];
sum2 += r3[4] * k2[4];
sum2 += r4[0] * k3[0];
sum2 += r4[1] * k3[1];
sum2 += r4[2] * k3[2];
sum2 += r4[3] * k3[3];
sum2 += r4[4] * k3[4];
sum2 += r5[0] * k4[0];
sum2 += r5[1] * k4[1];
sum2 += r5[2] * k4[2];
sum2 += r5[3] * k4[3];
sum2 += r5[4] * k4[4];
*outptr = sum;
*outptr2 = sum2;
r0++;
r1++;
r2++;
r3++;
r4++;
r5++;
outptr++;
outptr2++;
}
r0 += 4 + w;
r1 += 4 + w;
r2 += 4 + w;
r3 += 4 + w;
r4 += 4 + w;
r5 += 4 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
*outptr = sum;
r0++;
r1++;
r2++;
r3++;
r4++;
outptr++;
}
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
}
}
}
static void convdw5x5s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w,
int out_h, int out_w, int num_thread)
{
int w = in_w;
int h = in_h;
int c_step_in = w * h;
int outw = out_w;
int outh = out_h;
int c_step_out = outw * outh;
const int group = channel;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* out = output + g * c_step_out;
float* outptr = out;
const float* kernel0 = kernel + g * 25;
const float bias0 = _bias ? _bias[g] : 0.f;
const float* img0 = input + g * c_step_in;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w * 2;
const float* r3 = img0 + w * 3;
const float* r4 = img0 + w * 4;
const float* k0 = kernel0;
const float* k1 = kernel0 + 5;
const float* k2 = kernel0 + 10;
const float* k3 = kernel0 + 15;
const float* k4 = kernel0 + 20;
int i = 0;
for (; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = bias0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r0[3] * k0[3];
sum += r0[4] * k0[4];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r1[3] * k1[3];
sum += r1[4] * k1[4];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum += r2[3] * k2[3];
sum += r2[4] * k2[4];
sum += r3[0] * k3[0];
sum += r3[1] * k3[1];
sum += r3[2] * k3[2];
sum += r3[3] * k3[3];
sum += r3[4] * k3[4];
sum += r4[0] * k4[0];
sum += r4[1] * k4[1];
sum += r4[2] * k4[2];
sum += r4[3] * k4[3];
sum += r4[4] * k4[4];
*outptr = sum;
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
r4 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
r3 += tailstep;
r4 += tailstep;
}
}
}
int conv_dw_run(struct tensor* input_tensor, struct tensor* weight_tensor, struct tensor* bias_tensor,
struct tensor* output_tensor, struct conv_priv_info* conv_info, struct conv_param* param, int num_thread, int cpu_affinity)
{
float* input = ( float* )input_tensor->data;
float* output = ( float* )output_tensor->data;
float* kernel = ( float* )weight_tensor->data;
float* biases = NULL;
if (bias_tensor)
biases = ( float* )bias_tensor->data;
int batch_number = input_tensor->dims[0];
int inc = input_tensor->dims[1];
int inh = input_tensor->dims[2];
int inw = input_tensor->dims[3];
int in_chw = inc * inh * inw;
int outc = output_tensor->dims[1];
int outh = output_tensor->dims[2];
int outw = output_tensor->dims[3];
int out_hw = outh * outw;
int out_chw = out_hw * outc;
int ksize_h = param->kernel_h;
int ksize_w = param->kernel_w;
int pad_w = param->pad_w0;
int pad_h = param->pad_h0;
int stride_w = param->stride_w;
int stride_h = param->stride_h;
int dilation_w = param->dilation_w;
int dilation_h = param->dilation_h;
int group = param->group;
int activation = param->activation;
/* pading */
int inh_tmp = inh + pad_h + pad_h;
int inw_tmp = inw + pad_w + pad_w;
float* input_tmp = NULL;
if (inh_tmp == inh && inw_tmp == inw)
input_tmp = input;
else
{
input_tmp = ( float* )sys_malloc(inh_tmp * inw_tmp * group * sizeof(float));
#pragma omp parallel for num_threads(num_thread)
for (int g = 0; g < group; g++)
{
float* pad_in = input + g * inh * inw;
float* pad_out = input_tmp + g * inh_tmp * inw_tmp;
pad(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0.f);
}
}
/* process */
for (int i = 0; i < batch_number; i++)
{
if (ksize_h ==3 && stride_h == 1)
convdw3x3s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else if (ksize_h ==3 && stride_h == 2)
convdw3x3s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else if (ksize_h ==5 && stride_h == 1)
convdw5x5s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else if (ksize_h ==5 && stride_h == 2)
convdw5x5s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread);
else
TLOG_ERR("convdw %d x %d, s %d not support.\n", ksize_h, ksize_w, stride_h);
}
/* relu */
if (activation >= 0)
relu(output, batch_number * out_chw, activation);
if (!(inh_tmp == inh && inw_tmp == inw))
sys_free(input_tmp);
return 0;
}
|
OMPIRBuilder.h | //===- IR/OpenMPIRBuilder.h - OpenMP encoding builder for LLVM IR - 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 OpenMPIRBuilder class and helpers used as a convenient
// way to create LLVM instructions for OpenMP directives.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
#define LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
#include "llvm/Frontend/OpenMP/OMPConstants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/Support/Allocator.h"
#include <forward_list>
namespace llvm {
class CanonicalLoopInfo;
/// An interface to create LLVM-IR for OpenMP directives.
///
/// Each OpenMP directive has a corresponding public generator method.
class OpenMPIRBuilder {
public:
/// Create a new OpenMPIRBuilder operating on the given module \p M. This will
/// not have an effect on \p M (see initialize).
OpenMPIRBuilder(Module &M) : M(M), Builder(M.getContext()) {}
~OpenMPIRBuilder();
/// Initialize the internal state, this will put structures types and
/// potentially other helpers into the underlying module. Must be called
/// before any other method and only once!
void initialize();
/// Finalize the underlying module, e.g., by outlining regions.
/// \param Fn The function to be finalized. If not used,
/// all functions are finalized.
/// \param AllowExtractorSinking Flag to include sinking instructions,
/// emitted by CodeExtractor, in the
/// outlined region. Default is false.
void finalize(Function *Fn = nullptr, bool AllowExtractorSinking = false);
/// Add attributes known for \p FnID to \p Fn.
void addAttributes(omp::RuntimeFunction FnID, Function &Fn);
/// Type used throughout for insertion points.
using InsertPointTy = IRBuilder<>::InsertPoint;
/// Callback type for variable finalization (think destructors).
///
/// \param CodeGenIP is the insertion point at which the finalization code
/// should be placed.
///
/// A finalize callback knows about all objects that need finalization, e.g.
/// destruction, when the scope of the currently generated construct is left
/// at the time, and location, the callback is invoked.
using FinalizeCallbackTy = std::function<void(InsertPointTy CodeGenIP)>;
struct FinalizationInfo {
/// The finalization callback provided by the last in-flight invocation of
/// createXXXX for the directive of kind DK.
FinalizeCallbackTy FiniCB;
/// The directive kind of the innermost directive that has an associated
/// region which might require finalization when it is left.
omp::Directive DK;
/// Flag to indicate if the directive is cancellable.
bool IsCancellable;
};
/// Push a finalization callback on the finalization stack.
///
/// NOTE: Temporary solution until Clang CG is gone.
void pushFinalizationCB(const FinalizationInfo &FI) {
FinalizationStack.push_back(FI);
}
/// Pop the last finalization callback from the finalization stack.
///
/// NOTE: Temporary solution until Clang CG is gone.
void popFinalizationCB() { FinalizationStack.pop_back(); }
/// Callback type for body (=inner region) code generation
///
/// The callback takes code locations as arguments, each describing a
/// location at which code might need to be generated or a location that is
/// the target of control transfer.
///
/// \param AllocaIP is the insertion point at which new alloca instructions
/// should be placed.
/// \param CodeGenIP is the insertion point at which the body code should be
/// placed.
/// \param ContinuationBB is the basic block target to leave the body.
///
/// Note that all blocks pointed to by the arguments have terminators.
using BodyGenCallbackTy =
function_ref<void(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
BasicBlock &ContinuationBB)>;
// This is created primarily for sections construct as llvm::function_ref
// (BodyGenCallbackTy) is not storable (as described in the comments of
// function_ref class - function_ref contains non-ownable reference
// to the callable.
using StorableBodyGenCallbackTy =
std::function<void(InsertPointTy AllocaIP, InsertPointTy CodeGenIP,
BasicBlock &ContinuationBB)>;
/// Callback type for loop body code generation.
///
/// \param CodeGenIP is the insertion point where the loop's body code must be
/// placed. This will be a dedicated BasicBlock with a
/// conditional branch from the loop condition check and
/// terminated with an unconditional branch to the loop
/// latch.
/// \param IndVar is the induction variable usable at the insertion point.
using LoopBodyGenCallbackTy =
function_ref<void(InsertPointTy CodeGenIP, Value *IndVar)>;
/// Callback type for variable privatization (think copy & default
/// constructor).
///
/// \param AllocaIP is the insertion point at which new alloca instructions
/// should be placed.
/// \param CodeGenIP is the insertion point at which the privatization code
/// should be placed.
/// \param Original The value being copied/created, should not be used in the
/// generated IR.
/// \param Inner The equivalent of \p Original that should be used in the
/// generated IR; this is equal to \p Original if the value is
/// a pointer and can thus be passed directly, otherwise it is
/// an equivalent but different value.
/// \param ReplVal The replacement value, thus a copy or new created version
/// of \p Inner.
///
/// \returns The new insertion point where code generation continues and
/// \p ReplVal the replacement value.
using PrivatizeCallbackTy = function_ref<InsertPointTy(
InsertPointTy AllocaIP, InsertPointTy CodeGenIP, Value &Original,
Value &Inner, Value *&ReplVal)>;
/// Description of a LLVM-IR insertion point (IP) and a debug/source location
/// (filename, line, column, ...).
struct LocationDescription {
template <typename T, typename U>
LocationDescription(const IRBuilder<T, U> &IRB)
: IP(IRB.saveIP()), DL(IRB.getCurrentDebugLocation()) {}
LocationDescription(const InsertPointTy &IP) : IP(IP) {}
LocationDescription(const InsertPointTy &IP, const DebugLoc &DL)
: IP(IP), DL(DL) {}
InsertPointTy IP;
DebugLoc DL;
};
/// Emitter methods for OpenMP directives.
///
///{
/// Generator for '#omp barrier'
///
/// \param Loc The location where the barrier directive was encountered.
/// \param DK The kind of directive that caused the barrier.
/// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
/// \param CheckCancelFlag Flag to indicate a cancel barrier return value
/// should be checked and acted upon.
///
/// \returns The insertion point after the barrier.
InsertPointTy createBarrier(const LocationDescription &Loc, omp::Directive DK,
bool ForceSimpleCall = false,
bool CheckCancelFlag = true);
/// Generator for '#omp cancel'
///
/// \param Loc The location where the directive was encountered.
/// \param IfCondition The evaluated 'if' clause expression, if any.
/// \param CanceledDirective The kind of directive that is cancled.
///
/// \returns The insertion point after the barrier.
InsertPointTy createCancel(const LocationDescription &Loc, Value *IfCondition,
omp::Directive CanceledDirective);
/// Generator for '#omp parallel'
///
/// \param Loc The insert and source location description.
/// \param AllocaIP The insertion points to be used for alloca instructions.
/// \param BodyGenCB Callback that will generate the region code.
/// \param PrivCB Callback to copy a given variable (think copy constructor).
/// \param FiniCB Callback to finalize variable copies.
/// \param IfCondition The evaluated 'if' clause expression, if any.
/// \param NumThreads The evaluated 'num_threads' clause expression, if any.
/// \param ProcBind The value of the 'proc_bind' clause (see ProcBindKind).
/// \param IsCancellable Flag to indicate a cancellable parallel region.
///
/// \returns The insertion position *after* the parallel.
IRBuilder<>::InsertPoint
createParallel(const LocationDescription &Loc, InsertPointTy AllocaIP,
BodyGenCallbackTy BodyGenCB, PrivatizeCallbackTy PrivCB,
FinalizeCallbackTy FiniCB, Value *IfCondition,
Value *NumThreads, omp::ProcBindKind ProcBind,
bool IsCancellable);
/// Generator for the control flow structure of an OpenMP canonical loop.
///
/// This generator operates on the logical iteration space of the loop, i.e.
/// the caller only has to provide a loop trip count of the loop as defined by
/// base language semantics. The trip count is interpreted as an unsigned
/// integer. The induction variable passed to \p BodyGenCB will be of the same
/// type and run from 0 to \p TripCount - 1. It is up to the callback to
/// convert the logical iteration variable to the loop counter variable in the
/// loop body.
///
/// \param Loc The insert and source location description. The insert
/// location can be between two instructions or the end of a
/// degenerate block (e.g. a BB under construction).
/// \param BodyGenCB Callback that will generate the loop body code.
/// \param TripCount Number of iterations the loop body is executed.
/// \param Name Base name used to derive BB and instruction names.
///
/// \returns An object representing the created control flow structure which
/// can be used for loop-associated directives.
CanonicalLoopInfo *createCanonicalLoop(const LocationDescription &Loc,
LoopBodyGenCallbackTy BodyGenCB,
Value *TripCount,
const Twine &Name = "loop");
/// Generator for the control flow structure of an OpenMP canonical loop.
///
/// Instead of a logical iteration space, this allows specifying user-defined
/// loop counter values using increment, upper- and lower bounds. To
/// disambiguate the terminology when counting downwards, instead of lower
/// bounds we use \p Start for the loop counter value in the first body
/// iteration.
///
/// Consider the following limitations:
///
/// * A loop counter space over all integer values of its bit-width cannot be
/// represented. E.g using uint8_t, its loop trip count of 256 cannot be
/// stored into an 8 bit integer):
///
/// DO I = 0, 255, 1
///
/// * Unsigned wrapping is only supported when wrapping only "once"; E.g.
/// effectively counting downwards:
///
/// for (uint8_t i = 100u; i > 0; i += 127u)
///
///
/// TODO: May need to add additional parameters to represent:
///
/// * Allow representing downcounting with unsigned integers.
///
/// * Sign of the step and the comparison operator might disagree:
///
/// for (int i = 0; i < 42; i -= 1u)
///
//
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the loop body code.
/// \param Start Value of the loop counter for the first iterations.
/// \param Stop Loop counter values past this will stop the loop.
/// \param Step Loop counter increment after each iteration; negative
/// means counting down.
/// \param IsSigned Whether Start, Stop and Step are signed integers.
/// \param InclusiveStop Whether \p Stop itself is a valid value for the loop
/// counter.
/// \param ComputeIP Insertion point for instructions computing the trip
/// count. Can be used to ensure the trip count is available
/// at the outermost loop of a loop nest. If not set,
/// defaults to the preheader of the generated loop.
/// \param Name Base name used to derive BB and instruction names.
///
/// \returns An object representing the created control flow structure which
/// can be used for loop-associated directives.
CanonicalLoopInfo *createCanonicalLoop(const LocationDescription &Loc,
LoopBodyGenCallbackTy BodyGenCB,
Value *Start, Value *Stop, Value *Step,
bool IsSigned, bool InclusiveStop,
InsertPointTy ComputeIP = {},
const Twine &Name = "loop");
/// Collapse a loop nest into a single loop.
///
/// Merges loops of a loop nest into a single CanonicalLoopNest representation
/// that has the same number of innermost loop iterations as the origin loop
/// nest. The induction variables of the input loops are derived from the
/// collapsed loop's induction variable. This is intended to be used to
/// implement OpenMP's collapse clause. Before applying a directive,
/// collapseLoops normalizes a loop nest to contain only a single loop and the
/// directive's implementation does not need to handle multiple loops itself.
/// This does not remove the need to handle all loop nest handling by
/// directives, such as the ordered(<n>) clause or the simd schedule-clause
/// modifier of the worksharing-loop directive.
///
/// Example:
/// \code
/// for (int i = 0; i < 7; ++i) // Canonical loop "i"
/// for (int j = 0; j < 9; ++j) // Canonical loop "j"
/// body(i, j);
/// \endcode
///
/// After collapsing with Loops={i,j}, the loop is changed to
/// \code
/// for (int ij = 0; ij < 63; ++ij) {
/// int i = ij / 9;
/// int j = ij % 9;
/// body(i, j);
/// }
/// \endcode
///
/// In the current implementation, the following limitations apply:
///
/// * All input loops have an induction variable of the same type.
///
/// * The collapsed loop will have the same trip count integer type as the
/// input loops. Therefore it is possible that the collapsed loop cannot
/// represent all iterations of the input loops. For instance, assuming a
/// 32 bit integer type, and two input loops both iterating 2^16 times, the
/// theoretical trip count of the collapsed loop would be 2^32 iteration,
/// which cannot be represented in an 32-bit integer. Behavior is undefined
/// in this case.
///
/// * The trip counts of every input loop must be available at \p ComputeIP.
/// Non-rectangular loops are not yet supported.
///
/// * At each nest level, code between a surrounding loop and its nested loop
/// is hoisted into the loop body, and such code will be executed more
/// often than before collapsing (or not at all if any inner loop iteration
/// has a trip count of 0). This is permitted by the OpenMP specification.
///
/// \param DL Debug location for instructions added for collapsing,
/// such as instructions to compute/derive the input loop's
/// induction variables.
/// \param Loops Loops in the loop nest to collapse. Loops are specified
/// from outermost-to-innermost and every control flow of a
/// loop's body must pass through its directly nested loop.
/// \param ComputeIP Where additional instruction that compute the collapsed
/// trip count. If not set, defaults to before the generated
/// loop.
///
/// \returns The CanonicalLoopInfo object representing the collapsed loop.
CanonicalLoopInfo *collapseLoops(DebugLoc DL,
ArrayRef<CanonicalLoopInfo *> Loops,
InsertPointTy ComputeIP);
/// Modifies the canonical loop to be a statically-scheduled workshare loop.
///
/// This takes a \p LoopInfo representing a canonical loop, such as the one
/// created by \p createCanonicalLoop and emits additional instructions to
/// turn it into a workshare loop. In particular, it calls to an OpenMP
/// runtime function in the preheader to obtain the loop bounds to be used in
/// the current thread, updates the relevant instructions in the canonical
/// loop and calls to an OpenMP runtime finalization function after the loop.
///
/// TODO: Workshare loops with static scheduling may contain up to two loops
/// that fulfill the requirements of an OpenMP canonical loop. One for
/// iterating over all iterations of a chunk and another one for iterating
/// over all chunks that are executed on the same thread. Returning
/// CanonicalLoopInfo objects representing them may eventually be useful for
/// the apply clause planned in OpenMP 6.0, but currently whether these are
/// canonical loops is irrelevant.
///
/// \param DL Debug location for instructions added for the
/// workshare-loop construct itself.
/// \param CLI A descriptor of the canonical loop to workshare.
/// \param AllocaIP An insertion point for Alloca instructions usable in the
/// preheader of the loop.
/// \param NeedsBarrier Indicates whether a barrier must be inserted after
/// the loop.
/// \param Chunk The size of loop chunk considered as a unit when
/// scheduling. If \p nullptr, defaults to 1.
///
/// \returns Point where to insert code after the workshare construct.
InsertPointTy applyStaticWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
InsertPointTy AllocaIP,
bool NeedsBarrier,
Value *Chunk = nullptr);
/// Modifies the canonical loop to be a dynamically-scheduled workshare loop.
///
/// This takes a \p LoopInfo representing a canonical loop, such as the one
/// created by \p createCanonicalLoop and emits additional instructions to
/// turn it into a workshare loop. In particular, it calls to an OpenMP
/// runtime function in the preheader to obtain, and then in each iteration
/// to update the loop counter.
///
/// \param DL Debug location for instructions added for the
/// workshare-loop construct itself.
/// \param CLI A descriptor of the canonical loop to workshare.
/// \param AllocaIP An insertion point for Alloca instructions usable in the
/// preheader of the loop.
/// \param SchedType Type of scheduling to be passed to the init function.
/// \param NeedsBarrier Indicates whether a barrier must be insterted after
/// the loop.
/// \param Chunk The size of loop chunk considered as a unit when
/// scheduling. If \p nullptr, defaults to 1.
///
/// \returns Point where to insert code after the workshare construct.
InsertPointTy applyDynamicWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
InsertPointTy AllocaIP,
omp::OMPScheduleType SchedType,
bool NeedsBarrier,
Value *Chunk = nullptr);
/// Modifies the canonical loop to be a workshare loop.
///
/// This takes a \p LoopInfo representing a canonical loop, such as the one
/// created by \p createCanonicalLoop and emits additional instructions to
/// turn it into a workshare loop. In particular, it calls to an OpenMP
/// runtime function in the preheader to obtain the loop bounds to be used in
/// the current thread, updates the relevant instructions in the canonical
/// loop and calls to an OpenMP runtime finalization function after the loop.
///
/// \param DL Debug location for instructions added for the
/// workshare-loop construct itself.
/// \param CLI A descriptor of the canonical loop to workshare.
/// \param AllocaIP An insertion point for Alloca instructions usable in the
/// preheader of the loop.
/// \param NeedsBarrier Indicates whether a barrier must be insterted after
/// the loop.
///
/// \returns Point where to insert code after the workshare construct.
InsertPointTy applyWorkshareLoop(DebugLoc DL, CanonicalLoopInfo *CLI,
InsertPointTy AllocaIP, bool NeedsBarrier);
/// Tile a loop nest.
///
/// Tiles the loops of \p Loops by the tile sizes in \p TileSizes. Loops in
/// \p/ Loops must be perfectly nested, from outermost to innermost loop
/// (i.e. Loops.front() is the outermost loop). The trip count llvm::Value
/// of every loop and every tile sizes must be usable in the outermost
/// loop's preheader. This implies that the loop nest is rectangular.
///
/// Example:
/// \code
/// for (int i = 0; i < 15; ++i) // Canonical loop "i"
/// for (int j = 0; j < 14; ++j) // Canonical loop "j"
/// body(i, j);
/// \endcode
///
/// After tiling with Loops={i,j} and TileSizes={5,7}, the loop is changed to
/// \code
/// for (int i1 = 0; i1 < 3; ++i1)
/// for (int j1 = 0; j1 < 2; ++j1)
/// for (int i2 = 0; i2 < 5; ++i2)
/// for (int j2 = 0; j2 < 7; ++j2)
/// body(i1*3+i2, j1*3+j2);
/// \endcode
///
/// The returned vector are the loops {i1,j1,i2,j2}. The loops i1 and j1 are
/// referred to the floor, and the loops i2 and j2 are the tiles. Tiling also
/// handles non-constant trip counts, non-constant tile sizes and trip counts
/// that are not multiples of the tile size. In the latter case the tile loop
/// of the last floor-loop iteration will have fewer iterations than specified
/// as its tile size.
///
///
/// @param DL Debug location for instructions added by tiling, for
/// instance the floor- and tile trip count computation.
/// @param Loops Loops to tile. The CanonicalLoopInfo objects are
/// invalidated by this method, i.e. should not used after
/// tiling.
/// @param TileSizes For each loop in \p Loops, the tile size for that
/// dimensions.
///
/// \returns A list of generated loops. Contains twice as many loops as the
/// input loop nest; the first half are the floor loops and the
/// second half are the tile loops.
std::vector<CanonicalLoopInfo *>
tileLoops(DebugLoc DL, ArrayRef<CanonicalLoopInfo *> Loops,
ArrayRef<Value *> TileSizes);
/// Fully unroll a loop.
///
/// Instead of unrolling the loop immediately (and duplicating its body
/// instructions), it is deferred to LLVM's LoopUnrollPass by adding loop
/// metadata.
///
/// \param DL Debug location for instructions added by unrolling.
/// \param Loop The loop to unroll. The loop will be invalidated.
void unrollLoopFull(DebugLoc DL, CanonicalLoopInfo *Loop);
/// Fully or partially unroll a loop. How the loop is unrolled is determined
/// using LLVM's LoopUnrollPass.
///
/// \param DL Debug location for instructions added by unrolling.
/// \param Loop The loop to unroll. The loop will be invalidated.
void unrollLoopHeuristic(DebugLoc DL, CanonicalLoopInfo *Loop);
/// Partially unroll a loop.
///
/// The CanonicalLoopInfo of the unrolled loop for use with chained
/// loop-associated directive can be requested using \p UnrolledCLI. Not
/// needing the CanonicalLoopInfo allows more efficient code generation by
/// deferring the actual unrolling to the LoopUnrollPass using loop metadata.
/// A loop-associated directive applied to the unrolled loop needs to know the
/// new trip count which means that if using a heuristically determined unroll
/// factor (\p Factor == 0), that factor must be computed immediately. We are
/// using the same logic as the LoopUnrollPass to derived the unroll factor,
/// but which assumes that some canonicalization has taken place (e.g.
/// Mem2Reg, LICM, GVN, Inlining, etc.). That is, the heuristic will perform
/// better when the unrolled loop's CanonicalLoopInfo is not needed.
///
/// \param DL Debug location for instructions added by unrolling.
/// \param Loop The loop to unroll. The loop will be invalidated.
/// \param Factor The factor to unroll the loop by. A factor of 0
/// indicates that a heuristic should be used to determine
/// the unroll-factor.
/// \param UnrolledCLI If non-null, receives the CanonicalLoopInfo of the
/// partially unrolled loop. Otherwise, uses loop metadata
/// to defer unrolling to the LoopUnrollPass.
void unrollLoopPartial(DebugLoc DL, CanonicalLoopInfo *Loop, int32_t Factor,
CanonicalLoopInfo **UnrolledCLI);
/// Generator for '#omp flush'
///
/// \param Loc The location where the flush directive was encountered
void createFlush(const LocationDescription &Loc);
/// Generator for '#omp taskwait'
///
/// \param Loc The location where the taskwait directive was encountered.
void createTaskwait(const LocationDescription &Loc);
/// Generator for '#omp taskyield'
///
/// \param Loc The location where the taskyield directive was encountered.
void createTaskyield(const LocationDescription &Loc);
/// Functions used to generate reductions. Such functions take two Values
/// representing LHS and RHS of the reduction, respectively, and a reference
/// to the value that is updated to refer to the reduction result.
using ReductionGenTy =
function_ref<InsertPointTy(InsertPointTy, Value *, Value *, Value *&)>;
/// Functions used to generate atomic reductions. Such functions take two
/// Values representing pointers to LHS and RHS of the reduction. They are
/// expected to atomically update the LHS to the reduced value.
using AtomicReductionGenTy =
function_ref<InsertPointTy(InsertPointTy, Value *, Value *)>;
/// Information about an OpenMP reduction.
struct ReductionInfo {
ReductionInfo(Value *Variable, Value *PrivateVariable,
ReductionGenTy ReductionGen,
AtomicReductionGenTy AtomicReductionGen)
: Variable(Variable), PrivateVariable(PrivateVariable),
ReductionGen(ReductionGen), AtomicReductionGen(AtomicReductionGen) {}
/// Returns the type of the element being reduced.
Type *getElementType() const {
return Variable->getType()->getPointerElementType();
}
/// Reduction variable of pointer type.
Value *Variable;
/// Thread-private partial reduction variable.
Value *PrivateVariable;
/// Callback for generating the reduction body. The IR produced by this will
/// be used to combine two values in a thread-safe context, e.g., under
/// lock or within the same thread, and therefore need not be atomic.
ReductionGenTy ReductionGen;
/// Callback for generating the atomic reduction body, may be null. The IR
/// produced by this will be used to atomically combine two values during
/// reduction. If null, the implementation will use the non-atomic version
/// along with the appropriate synchronization mechanisms.
AtomicReductionGenTy AtomicReductionGen;
};
// TODO: provide atomic and non-atomic reduction generators for reduction
// operators defined by the OpenMP specification.
/// Generator for '#omp reduction'.
///
/// Emits the IR instructing the runtime to perform the specific kind of
/// reductions. Expects reduction variables to have been privatized and
/// initialized to reduction-neutral values separately. Emits the calls to
/// runtime functions as well as the reduction function and the basic blocks
/// performing the reduction atomically and non-atomically.
///
/// The code emitted for the following:
///
/// \code
/// type var_1;
/// type var_2;
/// #pragma omp <directive> reduction(reduction-op:var_1,var_2)
/// /* body */;
/// \endcode
///
/// corresponds to the following sketch.
///
/// \code
/// void _outlined_par() {
/// // N is the number of different reductions.
/// void *red_array[] = {privatized_var_1, privatized_var_2, ...};
/// switch(__kmpc_reduce(..., N, /*size of data in red array*/, red_array,
/// _omp_reduction_func,
/// _gomp_critical_user.reduction.var)) {
/// case 1: {
/// var_1 = var_1 <reduction-op> privatized_var_1;
/// var_2 = var_2 <reduction-op> privatized_var_2;
/// // ...
/// __kmpc_end_reduce(...);
/// break;
/// }
/// case 2: {
/// _Atomic<ReductionOp>(var_1, privatized_var_1);
/// _Atomic<ReductionOp>(var_2, privatized_var_2);
/// // ...
/// break;
/// }
/// default: break;
/// }
/// }
///
/// void _omp_reduction_func(void **lhs, void **rhs) {
/// *(type *)lhs[0] = *(type *)lhs[0] <reduction-op> *(type *)rhs[0];
/// *(type *)lhs[1] = *(type *)lhs[1] <reduction-op> *(type *)rhs[1];
/// // ...
/// }
/// \endcode
///
/// \param Loc The location where the reduction was
/// encountered. Must be within the associate
/// directive and after the last local access to the
/// reduction variables.
/// \param AllocaIP An insertion point suitable for allocas usable
/// in reductions.
/// \param ReductionInfos A list of info on each reduction variable.
/// \param IsNoWait A flag set if the reduction is marked as nowait.
InsertPointTy createReductions(const LocationDescription &Loc,
InsertPointTy AllocaIP,
ArrayRef<ReductionInfo> ReductionInfos,
bool IsNoWait = false);
///}
/// Return the insertion point used by the underlying IRBuilder.
InsertPointTy getInsertionPoint() { return Builder.saveIP(); }
/// Update the internal location to \p Loc.
bool updateToLocation(const LocationDescription &Loc) {
Builder.restoreIP(Loc.IP);
Builder.SetCurrentDebugLocation(Loc.DL);
return Loc.IP.getBlock() != nullptr;
}
/// Return the function declaration for the runtime function with \p FnID.
FunctionCallee getOrCreateRuntimeFunction(Module &M,
omp::RuntimeFunction FnID);
Function *getOrCreateRuntimeFunctionPtr(omp::RuntimeFunction FnID);
/// Return the (LLVM-IR) string describing the source location \p LocStr.
Constant *getOrCreateSrcLocStr(StringRef LocStr);
/// Return the (LLVM-IR) string describing the default source location.
Constant *getOrCreateDefaultSrcLocStr();
/// Return the (LLVM-IR) string describing the source location identified by
/// the arguments.
Constant *getOrCreateSrcLocStr(StringRef FunctionName, StringRef FileName,
unsigned Line, unsigned Column);
/// Return the (LLVM-IR) string describing the DebugLoc \p DL. Use \p F as
/// fallback if \p DL does not specify the function name.
Constant *getOrCreateSrcLocStr(DebugLoc DL, Function *F = nullptr);
/// Return the (LLVM-IR) string describing the source location \p Loc.
Constant *getOrCreateSrcLocStr(const LocationDescription &Loc);
/// Return an ident_t* encoding the source location \p SrcLocStr and \p Flags.
/// TODO: Create a enum class for the Reserve2Flags
Value *getOrCreateIdent(Constant *SrcLocStr,
omp::IdentFlag Flags = omp::IdentFlag(0),
unsigned Reserve2Flags = 0);
/// Create a global value containing the \p DebugLevel to control debuggin in
/// the module.
GlobalValue *createDebugKind(unsigned DebugLevel);
/// Generate control flow and cleanup for cancellation.
///
/// \param CancelFlag Flag indicating if the cancellation is performed.
/// \param CanceledDirective The kind of directive that is cancled.
/// \param ExitCB Extra code to be generated in the exit block.
void emitCancelationCheckImpl(Value *CancelFlag,
omp::Directive CanceledDirective,
FinalizeCallbackTy ExitCB = {});
/// Generate a barrier runtime call.
///
/// \param Loc The location at which the request originated and is fulfilled.
/// \param DK The directive which caused the barrier
/// \param ForceSimpleCall Flag to force a simple (=non-cancellation) barrier.
/// \param CheckCancelFlag Flag to indicate a cancel barrier return value
/// should be checked and acted upon.
///
/// \returns The insertion point after the barrier.
InsertPointTy emitBarrierImpl(const LocationDescription &Loc,
omp::Directive DK, bool ForceSimpleCall,
bool CheckCancelFlag);
/// Generate a flush runtime call.
///
/// \param Loc The location at which the request originated and is fulfilled.
void emitFlush(const LocationDescription &Loc);
/// The finalization stack made up of finalize callbacks currently in-flight,
/// wrapped into FinalizationInfo objects that reference also the finalization
/// target block and the kind of cancellable directive.
SmallVector<FinalizationInfo, 8> FinalizationStack;
/// Return true if the last entry in the finalization stack is of kind \p DK
/// and cancellable.
bool isLastFinalizationInfoCancellable(omp::Directive DK) {
return !FinalizationStack.empty() &&
FinalizationStack.back().IsCancellable &&
FinalizationStack.back().DK == DK;
}
/// Generate a taskwait runtime call.
///
/// \param Loc The location at which the request originated and is fulfilled.
void emitTaskwaitImpl(const LocationDescription &Loc);
/// Generate a taskyield runtime call.
///
/// \param Loc The location at which the request originated and is fulfilled.
void emitTaskyieldImpl(const LocationDescription &Loc);
/// Return the current thread ID.
///
/// \param Ident The ident (ident_t*) describing the query origin.
Value *getOrCreateThreadID(Value *Ident);
/// The underlying LLVM-IR module
Module &M;
/// The LLVM-IR Builder used to create IR.
IRBuilder<> Builder;
/// Map to remember source location strings
StringMap<Constant *> SrcLocStrMap;
/// Map to remember existing ident_t*.
DenseMap<std::pair<Constant *, uint64_t>, Value *> IdentMap;
/// Helper that contains information about regions we need to outline
/// during finalization.
struct OutlineInfo {
using PostOutlineCBTy = std::function<void(Function &)>;
PostOutlineCBTy PostOutlineCB;
BasicBlock *EntryBB, *ExitBB;
/// Collect all blocks in between EntryBB and ExitBB in both the given
/// vector and set.
void collectBlocks(SmallPtrSetImpl<BasicBlock *> &BlockSet,
SmallVectorImpl<BasicBlock *> &BlockVector);
/// Return the function that contains the region to be outlined.
Function *getFunction() const { return EntryBB->getParent(); }
};
/// Collection of regions that need to be outlined during finalization.
SmallVector<OutlineInfo, 16> OutlineInfos;
/// Collection of owned canonical loop objects that eventually need to be
/// free'd.
std::forward_list<CanonicalLoopInfo> LoopInfos;
/// Add a new region that will be outlined later.
void addOutlineInfo(OutlineInfo &&OI) { OutlineInfos.emplace_back(OI); }
/// An ordered map of auto-generated variables to their unique names.
/// It stores variables with the following names: 1) ".gomp_critical_user_" +
/// <critical_section_name> + ".var" for "omp critical" directives; 2)
/// <mangled_name_for_global_var> + ".cache." for cache for threadprivate
/// variables.
StringMap<AssertingVH<Constant>, BumpPtrAllocator> InternalVars;
/// Create the global variable holding the offload mappings information.
GlobalVariable *createOffloadMaptypes(SmallVectorImpl<uint64_t> &Mappings,
std::string VarName);
/// Create the global variable holding the offload names information.
GlobalVariable *
createOffloadMapnames(SmallVectorImpl<llvm::Constant *> &Names,
std::string VarName);
struct MapperAllocas {
AllocaInst *ArgsBase = nullptr;
AllocaInst *Args = nullptr;
AllocaInst *ArgSizes = nullptr;
};
/// Create the allocas instruction used in call to mapper functions.
void createMapperAllocas(const LocationDescription &Loc,
InsertPointTy AllocaIP, unsigned NumOperands,
struct MapperAllocas &MapperAllocas);
/// Create the call for the target mapper function.
/// \param Loc The source location description.
/// \param MapperFunc Function to be called.
/// \param SrcLocInfo Source location information global.
/// \param MaptypesArg The argument types.
/// \param MapnamesArg The argument names.
/// \param MapperAllocas The AllocaInst used for the call.
/// \param DeviceID Device ID for the call.
/// \param NumOperands Number of operands in the call.
void emitMapperCall(const LocationDescription &Loc, Function *MapperFunc,
Value *SrcLocInfo, Value *MaptypesArg, Value *MapnamesArg,
struct MapperAllocas &MapperAllocas, int64_t DeviceID,
unsigned NumOperands);
public:
/// Generator for __kmpc_copyprivate
///
/// \param Loc The source location description.
/// \param BufSize Number of elements in the buffer.
/// \param CpyBuf List of pointers to data to be copied.
/// \param CpyFn function to call for copying data.
/// \param DidIt flag variable; 1 for 'single' thread, 0 otherwise.
///
/// \return The insertion position *after* the CopyPrivate call.
InsertPointTy createCopyPrivate(const LocationDescription &Loc,
llvm::Value *BufSize, llvm::Value *CpyBuf,
llvm::Value *CpyFn, llvm::Value *DidIt);
/// Generator for '#omp single'
///
/// \param Loc The source location description.
/// \param BodyGenCB Callback that will generate the region code.
/// \param FiniCB Callback to finalize variable copies.
/// \param DidIt Local variable used as a flag to indicate 'single' thread
///
/// \returns The insertion position *after* the single call.
InsertPointTy createSingle(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB, llvm::Value *DidIt);
/// Generator for '#omp master'
///
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the region code.
/// \param FiniCB Callback to finalize variable copies.
///
/// \returns The insertion position *after* the master.
InsertPointTy createMaster(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB);
/// Generator for '#omp masked'
///
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the region code.
/// \param FiniCB Callback to finialize variable copies.
///
/// \returns The insertion position *after* the masked.
InsertPointTy createMasked(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB, Value *Filter);
/// Generator for '#omp critical'
///
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the region body code.
/// \param FiniCB Callback to finalize variable copies.
/// \param CriticalName name of the lock used by the critical directive
/// \param HintInst Hint Instruction for hint clause associated with critical
///
/// \returns The insertion position *after* the critical.
InsertPointTy createCritical(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB,
StringRef CriticalName, Value *HintInst);
/// Generator for '#omp ordered depend (source | sink)'
///
/// \param Loc The insert and source location description.
/// \param AllocaIP The insertion point to be used for alloca instructions.
/// \param NumLoops The number of loops in depend clause.
/// \param StoreValues The value will be stored in vector address.
/// \param Name The name of alloca instruction.
/// \param IsDependSource If true, depend source; otherwise, depend sink.
///
/// \return The insertion position *after* the ordered.
InsertPointTy createOrderedDepend(const LocationDescription &Loc,
InsertPointTy AllocaIP, unsigned NumLoops,
ArrayRef<llvm::Value *> StoreValues,
const Twine &Name, bool IsDependSource);
/// Generator for '#omp ordered [threads | simd]'
///
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the region code.
/// \param FiniCB Callback to finalize variable copies.
/// \param IsThreads If true, with threads clause or without clause;
/// otherwise, with simd clause;
///
/// \returns The insertion position *after* the ordered.
InsertPointTy createOrderedThreadsSimd(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB,
bool IsThreads);
/// Generator for '#omp sections'
///
/// \param Loc The insert and source location description.
/// \param AllocaIP The insertion points to be used for alloca instructions.
/// \param SectionCBs Callbacks that will generate body of each section.
/// \param PrivCB Callback to copy a given variable (think copy constructor).
/// \param FiniCB Callback to finalize variable copies.
/// \param IsCancellable Flag to indicate a cancellable parallel region.
/// \param IsNowait If true, barrier - to ensure all sections are executed
/// before moving forward will not be generated.
/// \returns The insertion position *after* the sections.
InsertPointTy createSections(const LocationDescription &Loc,
InsertPointTy AllocaIP,
ArrayRef<StorableBodyGenCallbackTy> SectionCBs,
PrivatizeCallbackTy PrivCB,
FinalizeCallbackTy FiniCB, bool IsCancellable,
bool IsNowait);
/// Generator for '#omp section'
///
/// \param Loc The insert and source location description.
/// \param BodyGenCB Callback that will generate the region body code.
/// \param FiniCB Callback to finalize variable copies.
/// \returns The insertion position *after* the section.
InsertPointTy createSection(const LocationDescription &Loc,
BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB);
/// Generate conditional branch and relevant BasicBlocks through which private
/// threads copy the 'copyin' variables from Master copy to threadprivate
/// copies.
///
/// \param IP insertion block for copyin conditional
/// \param MasterVarPtr a pointer to the master variable
/// \param PrivateVarPtr a pointer to the threadprivate variable
/// \param IntPtrTy Pointer size type
/// \param BranchtoEnd Create a branch between the copyin.not.master blocks
// and copy.in.end block
///
/// \returns The insertion point where copying operation to be emitted.
InsertPointTy createCopyinClauseBlocks(InsertPointTy IP, Value *MasterAddr,
Value *PrivateAddr,
llvm::IntegerType *IntPtrTy,
bool BranchtoEnd = true);
/// Create a runtime call for kmpc_Alloc
///
/// \param Loc The insert and source location description.
/// \param Size Size of allocated memory space
/// \param Allocator Allocator information instruction
/// \param Name Name of call Instruction for OMP_alloc
///
/// \returns CallInst to the OMP_Alloc call
CallInst *createOMPAlloc(const LocationDescription &Loc, Value *Size,
Value *Allocator, std::string Name = "");
/// Create a runtime call for kmpc_free
///
/// \param Loc The insert and source location description.
/// \param Addr Address of memory space to be freed
/// \param Allocator Allocator information instruction
/// \param Name Name of call Instruction for OMP_Free
///
/// \returns CallInst to the OMP_Free call
CallInst *createOMPFree(const LocationDescription &Loc, Value *Addr,
Value *Allocator, std::string Name = "");
/// Create a runtime call for kmpc_threadprivate_cached
///
/// \param Loc The insert and source location description.
/// \param Pointer pointer to data to be cached
/// \param Size size of data to be cached
/// \param Name Name of call Instruction for callinst
///
/// \returns CallInst to the thread private cache call.
CallInst *createCachedThreadPrivate(const LocationDescription &Loc,
llvm::Value *Pointer,
llvm::ConstantInt *Size,
const llvm::Twine &Name = Twine(""));
/// The `omp target` interface
///
/// For more information about the usage of this interface,
/// \see openmp/libomptarget/deviceRTLs/common/include/target.h
///
///{
/// Create a runtime call for kmpc_target_init
///
/// \param Loc The insert and source location description.
/// \param IsSPMD Flag to indicate if the kernel is an SPMD kernel or not.
/// \param RequiresFullRuntime Indicate if a full device runtime is necessary.
InsertPointTy createTargetInit(const LocationDescription &Loc, bool IsSPMD,
bool RequiresFullRuntime);
/// Create a runtime call for kmpc_target_deinit
///
/// \param Loc The insert and source location description.
/// \param IsSPMD Flag to indicate if the kernel is an SPMD kernel or not.
/// \param RequiresFullRuntime Indicate if a full device runtime is necessary.
void createTargetDeinit(const LocationDescription &Loc, bool IsSPMD,
bool RequiresFullRuntime);
///}
/// Declarations for LLVM-IR types (simple, array, function and structure) are
/// generated below. Their names are defined and used in OpenMPKinds.def. Here
/// we provide the declarations, the initializeTypes function will provide the
/// values.
///
///{
#define OMP_TYPE(VarName, InitValue) Type *VarName = nullptr;
#define OMP_ARRAY_TYPE(VarName, ElemTy, ArraySize) \
ArrayType *VarName##Ty = nullptr; \
PointerType *VarName##PtrTy = nullptr;
#define OMP_FUNCTION_TYPE(VarName, IsVarArg, ReturnType, ...) \
FunctionType *VarName = nullptr; \
PointerType *VarName##Ptr = nullptr;
#define OMP_STRUCT_TYPE(VarName, StrName, ...) \
StructType *VarName = nullptr; \
PointerType *VarName##Ptr = nullptr;
#include "llvm/Frontend/OpenMP/OMPKinds.def"
///}
private:
/// Create all simple and struct types exposed by the runtime and remember
/// the llvm::PointerTypes of them for easy access later.
void initializeTypes(Module &M);
/// Common interface for generating entry calls for OMP Directives.
/// if the directive has a region/body, It will set the insertion
/// point to the body
///
/// \param OMPD Directive to generate entry blocks for
/// \param EntryCall Call to the entry OMP Runtime Function
/// \param ExitBB block where the region ends.
/// \param Conditional indicate if the entry call result will be used
/// to evaluate a conditional of whether a thread will execute
/// body code or not.
///
/// \return The insertion position in exit block
InsertPointTy emitCommonDirectiveEntry(omp::Directive OMPD, Value *EntryCall,
BasicBlock *ExitBB,
bool Conditional = false);
/// Common interface to finalize the region
///
/// \param OMPD Directive to generate exiting code for
/// \param FinIP Insertion point for emitting Finalization code and exit call
/// \param ExitCall Call to the ending OMP Runtime Function
/// \param HasFinalize indicate if the directive will require finalization
/// and has a finalization callback in the stack that
/// should be called.
///
/// \return The insertion position in exit block
InsertPointTy emitCommonDirectiveExit(omp::Directive OMPD,
InsertPointTy FinIP,
Instruction *ExitCall,
bool HasFinalize = true);
/// Common Interface to generate OMP inlined regions
///
/// \param OMPD Directive to generate inlined region for
/// \param EntryCall Call to the entry OMP Runtime Function
/// \param ExitCall Call to the ending OMP Runtime Function
/// \param BodyGenCB Body code generation callback.
/// \param FiniCB Finalization Callback. Will be called when finalizing region
/// \param Conditional indicate if the entry call result will be used
/// to evaluate a conditional of whether a thread will execute
/// body code or not.
/// \param HasFinalize indicate if the directive will require finalization
/// and has a finalization callback in the stack that
/// should be called.
/// \param IsCancellable if HasFinalize is set to true, indicate if the
/// the directive should be cancellable.
/// \return The insertion point after the region
InsertPointTy
EmitOMPInlinedRegion(omp::Directive OMPD, Instruction *EntryCall,
Instruction *ExitCall, BodyGenCallbackTy BodyGenCB,
FinalizeCallbackTy FiniCB, bool Conditional = false,
bool HasFinalize = true, bool IsCancellable = false);
/// Get the platform-specific name separator.
/// \param Parts different parts of the final name that needs separation
/// \param FirstSeparator First separator used between the initial two
/// parts of the name.
/// \param Separator separator used between all of the rest consecutive
/// parts of the name
static std::string getNameWithSeparators(ArrayRef<StringRef> Parts,
StringRef FirstSeparator,
StringRef Separator);
/// Gets (if variable with the given name already exist) or creates
/// internal global variable with the specified Name. The created variable has
/// linkage CommonLinkage by default and is initialized by null value.
/// \param Ty Type of the global variable. If it is exist already the type
/// must be the same.
/// \param Name Name of the variable.
Constant *getOrCreateOMPInternalVariable(Type *Ty, const Twine &Name,
unsigned AddressSpace = 0);
/// Returns corresponding lock object for the specified critical region
/// name. If the lock object does not exist it is created, otherwise the
/// reference to the existing copy is returned.
/// \param CriticalName Name of the critical region.
///
Value *getOMPCriticalRegionLock(StringRef CriticalName);
/// Callback type for Atomic Expression update
/// ex:
/// \code{.cpp}
/// unsigned x = 0;
/// #pragma omp atomic update
/// x = Expr(x_old); //Expr() is any legal operation
/// \endcode
///
/// \param XOld the value of the atomic memory address to use for update
/// \param IRB reference to the IRBuilder to use
///
/// \returns Value to update X to.
using AtomicUpdateCallbackTy =
const function_ref<Value *(Value *XOld, IRBuilder<> &IRB)>;
private:
enum AtomicKind { Read, Write, Update, Capture };
/// Determine whether to emit flush or not
///
/// \param Loc The insert and source location description.
/// \param AO The required atomic ordering
/// \param AK The OpenMP atomic operation kind used.
///
/// \returns wether a flush was emitted or not
bool checkAndEmitFlushAfterAtomic(const LocationDescription &Loc,
AtomicOrdering AO, AtomicKind AK);
/// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
/// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
/// Only Scalar data types.
///
/// \param AllocIP Instruction to create AllocaInst before.
/// \param X The target atomic pointer to be updated
/// \param Expr The value to update X with.
/// \param AO Atomic ordering of the generated atomic
/// instructions.
/// \param RMWOp The binary operation used for update. If
/// operation is not supported by atomicRMW,
/// or belong to {FADD, FSUB, BAD_BINOP}.
/// Then a `cmpExch` based atomic will be generated.
/// \param UpdateOp Code generator for complex expressions that cannot be
/// expressed through atomicrmw instruction.
/// \param VolatileX true if \a X volatile?
/// \param IsXLHSInRHSPart true if \a X is Left H.S. in Right H.S. part of
/// the update expression, false otherwise.
/// (e.g. true for X = X BinOp Expr)
///
/// \returns A pair of the old value of X before the update, and the value
/// used for the update.
std::pair<Value *, Value *> emitAtomicUpdate(Instruction *AllocIP, Value *X,
Value *Expr, AtomicOrdering AO,
AtomicRMWInst::BinOp RMWOp,
AtomicUpdateCallbackTy &UpdateOp,
bool VolatileX,
bool IsXLHSInRHSPart);
/// Emit the binary op. described by \p RMWOp, using \p Src1 and \p Src2 .
///
/// \Return The instruction
Value *emitRMWOpAsInstruction(Value *Src1, Value *Src2,
AtomicRMWInst::BinOp RMWOp);
public:
/// a struct to pack relevant information while generating atomic Ops
struct AtomicOpValue {
Value *Var = nullptr;
bool IsSigned = false;
bool IsVolatile = false;
};
/// Emit atomic Read for : V = X --- Only Scalar data types.
///
/// \param Loc The insert and source location description.
/// \param X The target pointer to be atomically read
/// \param V Memory address where to store atomically read
/// value
/// \param AO Atomic ordering of the generated atomic
/// instructions.
///
/// \return Insertion point after generated atomic read IR.
InsertPointTy createAtomicRead(const LocationDescription &Loc,
AtomicOpValue &X, AtomicOpValue &V,
AtomicOrdering AO);
/// Emit atomic write for : X = Expr --- Only Scalar data types.
///
/// \param Loc The insert and source location description.
/// \param X The target pointer to be atomically written to
/// \param Expr The value to store.
/// \param AO Atomic ordering of the generated atomic
/// instructions.
///
/// \return Insertion point after generated atomic Write IR.
InsertPointTy createAtomicWrite(const LocationDescription &Loc,
AtomicOpValue &X, Value *Expr,
AtomicOrdering AO);
/// Emit atomic update for constructs: X = X BinOp Expr ,or X = Expr BinOp X
/// For complex Operations: X = UpdateOp(X) => CmpExch X, old_X, UpdateOp(X)
/// Only Scalar data types.
///
/// \param Loc The insert and source location description.
/// \param AllocIP Instruction to create AllocaInst before.
/// \param X The target atomic pointer to be updated
/// \param Expr The value to update X with.
/// \param AO Atomic ordering of the generated atomic instructions.
/// \param RMWOp The binary operation used for update. If operation
/// is not supported by atomicRMW, or belong to
/// {FADD, FSUB, BAD_BINOP}. Then a `cmpExch` based
/// atomic will be generated.
/// \param UpdateOp Code generator for complex expressions that cannot be
/// expressed through atomicrmw instruction.
/// \param IsXLHSInRHSPart true if \a X is Left H.S. in Right H.S. part of
/// the update expression, false otherwise.
/// (e.g. true for X = X BinOp Expr)
///
/// \return Insertion point after generated atomic update IR.
InsertPointTy createAtomicUpdate(const LocationDescription &Loc,
Instruction *AllocIP, AtomicOpValue &X,
Value *Expr, AtomicOrdering AO,
AtomicRMWInst::BinOp RMWOp,
AtomicUpdateCallbackTy &UpdateOp,
bool IsXLHSInRHSPart);
/// Emit atomic update for constructs: --- Only Scalar data types
/// V = X; X = X BinOp Expr ,
/// X = X BinOp Expr; V = X,
/// V = X; X = Expr BinOp X,
/// X = Expr BinOp X; V = X,
/// V = X; X = UpdateOp(X),
/// X = UpdateOp(X); V = X,
///
/// \param Loc The insert and source location description.
/// \param AllocIP Instruction to create AllocaInst before.
/// \param X The target atomic pointer to be updated
/// \param V Memory address where to store captured value
/// \param Expr The value to update X with.
/// \param AO Atomic ordering of the generated atomic instructions
/// \param RMWOp The binary operation used for update. If
/// operation is not supported by atomicRMW, or belong to
/// {FADD, FSUB, BAD_BINOP}. Then a cmpExch based
/// atomic will be generated.
/// \param UpdateOp Code generator for complex expressions that cannot be
/// expressed through atomicrmw instruction.
/// \param UpdateExpr true if X is an in place update of the form
/// X = X BinOp Expr or X = Expr BinOp X
/// \param IsXLHSInRHSPart true if X is Left H.S. in Right H.S. part of the
/// update expression, false otherwise.
/// (e.g. true for X = X BinOp Expr)
/// \param IsPostfixUpdate true if original value of 'x' must be stored in
/// 'v', not an updated one.
///
/// \return Insertion point after generated atomic capture IR.
InsertPointTy
createAtomicCapture(const LocationDescription &Loc, Instruction *AllocIP,
AtomicOpValue &X, AtomicOpValue &V, Value *Expr,
AtomicOrdering AO, AtomicRMWInst::BinOp RMWOp,
AtomicUpdateCallbackTy &UpdateOp, bool UpdateExpr,
bool IsPostfixUpdate, bool IsXLHSInRHSPart);
/// Create the control flow structure of a canonical OpenMP loop.
///
/// The emitted loop will be disconnected, i.e. no edge to the loop's
/// preheader and no terminator in the AfterBB. The OpenMPIRBuilder's
/// IRBuilder location is not preserved.
///
/// \param DL DebugLoc used for the instructions in the skeleton.
/// \param TripCount Value to be used for the trip count.
/// \param F Function in which to insert the BasicBlocks.
/// \param PreInsertBefore Where to insert BBs that execute before the body,
/// typically the body itself.
/// \param PostInsertBefore Where to insert BBs that execute after the body.
/// \param Name Base name used to derive BB
/// and instruction names.
///
/// \returns The CanonicalLoopInfo that represents the emitted loop.
CanonicalLoopInfo *createLoopSkeleton(DebugLoc DL, Value *TripCount,
Function *F,
BasicBlock *PreInsertBefore,
BasicBlock *PostInsertBefore,
const Twine &Name = {});
};
/// Class to represented the control flow structure of an OpenMP canonical loop.
///
/// The control-flow structure is standardized for easy consumption by
/// directives associated with loops. For instance, the worksharing-loop
/// construct may change this control flow such that each loop iteration is
/// executed on only one thread. The constraints of a canonical loop in brief
/// are:
///
/// * The number of loop iterations must have been computed before entering the
/// loop.
///
/// * Has an (unsigned) logical induction variable that starts at zero and
/// increments by one.
///
/// * The loop's CFG itself has no side-effects. The OpenMP specification
/// itself allows side-effects, but the order in which they happen, including
/// how often or whether at all, is unspecified. We expect that the frontend
/// will emit those side-effect instructions somewhere (e.g. before the loop)
/// such that the CanonicalLoopInfo itself can be side-effect free.
///
/// Keep in mind that CanonicalLoopInfo is meant to only describe a repeated
/// execution of a loop body that satifies these constraints. It does NOT
/// represent arbitrary SESE regions that happen to contain a loop. Do not use
/// CanonicalLoopInfo for such purposes.
///
/// The control flow can be described as follows:
///
/// Preheader
/// |
/// /-> Header
/// | |
/// | Cond---\
/// | | |
/// | Body |
/// | | | |
/// | <...> |
/// | | | |
/// \--Latch |
/// |
/// Exit
/// |
/// After
///
/// The loop is thought to start at PreheaderIP (at the Preheader's terminator,
/// including) and end at AfterIP (at the After's first instruction, excluding).
/// That is, instructions in the Preheader and After blocks (except the
/// Preheader's terminator) are out of CanonicalLoopInfo's control and may have
/// side-effects. Typically, the Preheader is used to compute the loop's trip
/// count. The instructions from BodyIP (at the Body block's first instruction,
/// excluding) until the Latch are also considered outside CanonicalLoopInfo's
/// control and thus can have side-effects. The body block is the single entry
/// point into the loop body, which may contain arbitrary control flow as long
/// as all control paths eventually branch to the Latch block.
///
/// TODO: Consider adding another standardized BasicBlock between Body CFG and
/// Latch to guarantee that there is only a single edge to the latch. It would
/// make loop transformations easier to not needing to consider multiple
/// predecessors of the latch (See redirectAllPredecessorsTo) and would give us
/// an equivalant to PreheaderIP, AfterIP and BodyIP for inserting code that
/// executes after each body iteration.
///
/// There must be no loop-carried dependencies through llvm::Values. This is
/// equivalant to that the Latch has no PHINode and the Header's only PHINode is
/// for the induction variable.
///
/// All code in Header, Cond, Latch and Exit (plus the terminator of the
/// Preheader) are CanonicalLoopInfo's responsibility and their build-up checked
/// by assertOK(). They are expected to not be modified unless explicitly
/// modifying the CanonicalLoopInfo through a methods that applies a OpenMP
/// loop-associated construct such as applyWorkshareLoop, tileLoops, unrollLoop,
/// etc. These methods usually invalidate the CanonicalLoopInfo and re-use its
/// basic blocks. After invalidation, the CanonicalLoopInfo must not be used
/// anymore as its underlying control flow may not exist anymore.
/// Loop-transformation methods such as tileLoops, collapseLoops and unrollLoop
/// may also return a new CanonicalLoopInfo that can be passed to other
/// loop-associated construct implementing methods. These loop-transforming
/// methods may either create a new CanonicalLoopInfo usually using
/// createLoopSkeleton and invalidate the input CanonicalLoopInfo, or reuse and
/// modify one of the input CanonicalLoopInfo and return it as representing the
/// modified loop. What is done is an implementation detail of
/// transformation-implementing method and callers should always assume that the
/// CanonicalLoopInfo passed to it is invalidated and a new object is returned.
/// Returned CanonicalLoopInfo have the same structure and guarantees as the one
/// created by createCanonicalLoop, such that transforming methods do not have
/// to special case where the CanonicalLoopInfo originated from.
///
/// Generally, methods consuming CanonicalLoopInfo do not need an
/// OpenMPIRBuilder::InsertPointTy as argument, but use the locations of the
/// CanonicalLoopInfo to insert new or modify existing instructions. Unless
/// documented otherwise, methods consuming CanonicalLoopInfo do not invalidate
/// any InsertPoint that is outside CanonicalLoopInfo's control. Specifically,
/// any InsertPoint in the Preheader, After or Block can still be used after
/// calling such a method.
///
/// TODO: Provide mechanisms for exception handling and cancellation points.
///
/// Defined outside OpenMPIRBuilder because nested classes cannot be
/// forward-declared, e.g. to avoid having to include the entire OMPIRBuilder.h.
class CanonicalLoopInfo {
friend class OpenMPIRBuilder;
private:
BasicBlock *Preheader = nullptr;
BasicBlock *Header = nullptr;
BasicBlock *Cond = nullptr;
BasicBlock *Body = nullptr;
BasicBlock *Latch = nullptr;
BasicBlock *Exit = nullptr;
BasicBlock *After = nullptr;
/// Add the control blocks of this loop to \p BBs.
///
/// This does not include any block from the body, including the one returned
/// by getBody().
///
/// FIXME: This currently includes the Preheader and After blocks even though
/// their content is (mostly) not under CanonicalLoopInfo's control.
/// Re-evaluated whether this makes sense.
void collectControlBlocks(SmallVectorImpl<BasicBlock *> &BBs);
public:
/// Returns whether this object currently represents the IR of a loop. If
/// returning false, it may have been consumed by a loop transformation or not
/// been intialized. Do not use in this case;
bool isValid() const { return Header; }
/// The preheader ensures that there is only a single edge entering the loop.
/// Code that must be execute before any loop iteration can be emitted here,
/// such as computing the loop trip count and begin lifetime markers. Code in
/// the preheader is not considered part of the canonical loop.
BasicBlock *getPreheader() const {
assert(isValid() && "Requires a valid canonical loop");
return Preheader;
}
/// The header is the entry for each iteration. In the canonical control flow,
/// it only contains the PHINode for the induction variable.
BasicBlock *getHeader() const {
assert(isValid() && "Requires a valid canonical loop");
return Header;
}
/// The condition block computes whether there is another loop iteration. If
/// yes, branches to the body; otherwise to the exit block.
BasicBlock *getCond() const {
assert(isValid() && "Requires a valid canonical loop");
return Cond;
}
/// The body block is the single entry for a loop iteration and not controlled
/// by CanonicalLoopInfo. It can contain arbitrary control flow but must
/// eventually branch to the \p Latch block.
BasicBlock *getBody() const {
assert(isValid() && "Requires a valid canonical loop");
return Body;
}
/// Reaching the latch indicates the end of the loop body code. In the
/// canonical control flow, it only contains the increment of the induction
/// variable.
BasicBlock *getLatch() const {
assert(isValid() && "Requires a valid canonical loop");
return Latch;
}
/// Reaching the exit indicates no more iterations are being executed.
BasicBlock *getExit() const {
assert(isValid() && "Requires a valid canonical loop");
return Exit;
}
/// The after block is intended for clean-up code such as lifetime end
/// markers. It is separate from the exit block to ensure, analogous to the
/// preheader, it having just a single entry edge and being free from PHI
/// nodes should there be multiple loop exits (such as from break
/// statements/cancellations).
BasicBlock *getAfter() const {
assert(isValid() && "Requires a valid canonical loop");
return After;
}
/// Returns the llvm::Value containing the number of loop iterations. It must
/// be valid in the preheader and always interpreted as an unsigned integer of
/// any bit-width.
Value *getTripCount() const {
assert(isValid() && "Requires a valid canonical loop");
Instruction *CmpI = &Cond->front();
assert(isa<CmpInst>(CmpI) && "First inst must compare IV with TripCount");
return CmpI->getOperand(1);
}
/// Returns the instruction representing the current logical induction
/// variable. Always unsigned, always starting at 0 with an increment of one.
Instruction *getIndVar() const {
assert(isValid() && "Requires a valid canonical loop");
Instruction *IndVarPHI = &Header->front();
assert(isa<PHINode>(IndVarPHI) && "First inst must be the IV PHI");
return IndVarPHI;
}
/// Return the type of the induction variable (and the trip count).
Type *getIndVarType() const {
assert(isValid() && "Requires a valid canonical loop");
return getIndVar()->getType();
}
/// Return the insertion point for user code before the loop.
OpenMPIRBuilder::InsertPointTy getPreheaderIP() const {
assert(isValid() && "Requires a valid canonical loop");
return {Preheader, std::prev(Preheader->end())};
};
/// Return the insertion point for user code in the body.
OpenMPIRBuilder::InsertPointTy getBodyIP() const {
assert(isValid() && "Requires a valid canonical loop");
return {Body, Body->begin()};
};
/// Return the insertion point for user code after the loop.
OpenMPIRBuilder::InsertPointTy getAfterIP() const {
assert(isValid() && "Requires a valid canonical loop");
return {After, After->begin()};
};
Function *getFunction() const {
assert(isValid() && "Requires a valid canonical loop");
return Header->getParent();
}
/// Consistency self-check.
void assertOK() const;
/// Invalidate this loop. That is, the underlying IR does not fulfill the
/// requirements of an OpenMP canonical loop anymore.
void invalidate();
};
} // end namespace llvm
#endif // LLVM_FRONTEND_OPENMP_OMPIRBUILDER_H
|
macadam.c | // converted some old code to use our cie1931 arrays
//
// this will precompute a map suitable to reconstruct MacAdam-style box spectra
// from tristimulus input.
// the map contains three numbers per pixel: maximum brightness (X+Y+Z),
// lambda0 and lambda1. the two wavelengths are the locations of the rising
// and the falling edge, respectively. if the falling edge comes before the
// rising one, the spectrum is a dip instead of a peak.
#define CIE_SAMPLES 95
#define CIE_LAMBDA_MIN 360.0
#define CIE_LAMBDA_MAX 830.0
#define CIE_FINE_SAMPLES ((CIE_SAMPLES - 1) * 3 + 1)
#include "details/cie1931.h"
#include "clip.h"
#include "inpaint.h"
#include "../o-pfm/half.h"
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc, char *argv[])
{
const int max_l = CIE_SAMPLES*2;
int res = 1024;
float *buf = calloc(sizeof(float), 4*res*res);
int incres = 8.0;//64.0;
// enumerate all possible box spectra in the sense of [MacAdam 1935],
// all wavelengths l: l0 <= l <= l1 are s(l) = 1, 0 else:
#pragma omp parallel for schedule(dynamic) default(shared)
for(int iw0=0;iw0<=incres*(max_l/2-1);iw0++)
{
for(int iw1=iw0+1;iw1<=incres*(max_l-2);iw1++)
{
const float w0 = iw0/(float)incres;
const float w1 = iw1/(float)incres;
// compute xy chromaticities:
// const int l0 = w0, l1 = w1;
// const float f0 = w0-l0, f1 = w1-l1;
const float lambda0 = CIE_LAMBDA_MIN + w0 * 5.0;
const float lambda1 = CIE_LAMBDA_MIN + w1 * 5.0 > CIE_LAMBDA_MAX ?
CIE_LAMBDA_MIN + (w1 - CIE_SAMPLES + 1)*5.0 :
CIE_LAMBDA_MIN + w1 * 5.0;
double X, Y, Z;
X = Y = Z = 0.0;
for(int l=0;l<5*CIE_SAMPLES;l++)
{
const float ll = l / (5.0f*CIE_SAMPLES - 1.0f);
const float lambda = CIE_LAMBDA_MIN * (1.0f-ll) + CIE_LAMBDA_MAX * ll;
float p = 0.0f;
if(lambda0 < lambda1)
{ // peak
if(lambda > lambda0 && lambda <= lambda1) p = 1.0f;
}
else
{ // dip
if(lambda <= lambda1 || lambda > lambda0) p = 1.0f;
}
X += p * cie_x[l/5] * 1.0f/106.89;
Y += p * cie_y[l/5] * 1.0f/106.89;
Z += p * cie_z[l/5] * 1.0f/106.89;
}
const float b = X+Y+Z;
const float x = X/b;
const float y = Y/b;
// rasterize into map
if(b > 1e-4f && x > 0 && y > 0)
{
const int i = x*res+0.5f, j = y*res+0.5f;
if(i>=0&&i<res&&j>=0&&j<res)
{
float *v = buf + 4*(j*res+i);
// const float n = v[3];
// const float t0 = n/(n+1.0), t1 = 1.0/(n+1.0);
const float t0 = 0.0f, t1 = 1.0f;
v[0] = t0*v[0] + t1*b;
v[1] = t0*v[1] + t1*lambda0;
v[2] = t0*v[2] + t1*lambda1;
v[3] ++ ;
}
}
}
}
// inpaint/hole filling
buf_t inpaint_buf = {
.dat = buf,
.wd = res,
.ht = res,
.cpp = 4,
};
inpaint(&inpaint_buf);
// clear out of gamut values again
for(int j=0;j<res;j++)
for(int i=0;i<res;i++)
if(spectrum_outside(
(i+.5) / (float)res,
(j+.5) / (float)res))
for(int c=0;c<3;c++)
buf[4*(j*res+i)+c] = 0.0f;
// blur 5x5 to smooth over cmf resolution
float *smooth = calloc(sizeof(float), res*res);
for(int j=0;j<res;j++) for(int i=0;i<res;i++)
{
const float wg[] = {1.0f, 4.0f, 6.0f, 4.0f, 1.0f};
float weight = 0.0f;
// for(int jj=-2;jj<=2;jj++) for(int ii=-2;ii<=2;ii++)
for(int jj=-4;jj<=4;jj+=2) for(int ii=-4;ii<=4;ii+=2) // even smoother
{
if(j+jj >= 0 && j+jj < res && i+ii >= 0 && i+ii < res)
{
// float w = wg[jj+2]*wg[ii+2];
float w = wg[jj/2+2]*wg[ii/2+2];
smooth[j*res+i] += w * buf[4*((j+jj)*res+i+ii)];
weight += w;
}
}
if(weight > 0.0f) smooth[j*res+i] /= weight;
}
// write 1 channel half lut:
uint32_t size = sizeof(uint16_t)*res*res;
uint16_t *b16 = malloc(size);
for(int k=0;k<res*res;k++)
b16[k] = float_to_half(smooth[k]);
typedef struct header_t
{
uint32_t magic;
uint16_t version;
uint8_t channels;
uint8_t datatype;
uint32_t wd;
uint32_t ht;
}
header_t;
header_t head = (header_t) {
.magic = 1234,
.version = 2,
.channels = 1,
.datatype = 0,
.wd = res,
.ht = res,
};
FILE *f = fopen("macadam.lut", "wb");
if(f)
{
fwrite(&head, sizeof(head), 1, f);
fwrite(b16, size, 1, f);
fclose(f);
}
#if 0 // debug, can look at this with eu:
FILE *pfm = fopen("macadam.pfm", "wb");
if(pfm)
{
fprintf(pfm, "PF\n%d %d\n-1.0\n", res, res);
for(int k=0;k<res*res;k++) for(int c=0;c<3;c++)
fwrite(smooth+k, sizeof(float), 1, pfm);
fclose(pfm);
}
#endif
free(b16);
free(smooth);
exit(0);
}
|
mandelbrot_6.c | // The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// Contributed by Kevin Miller
//
// ver 2: added a couple of optimizations
// - Reduced number of times a vector of 8 was checked to see if
// they had all escaped, similar to Dominic Letz's C #5 entry.
// - Processed 64 pixels at a time if width was a multiple of 64,
// thereby reducing writes to the bitmap.
//
// compile with following gcc flags
// -pipe -Wall -O3 -ffast-math -fno-finite-math-only -march=native -mfpmath=sse -msse3 -fopenmp
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <emmintrin.h>
long numDigits(long n)
{
long len = 0;
while(n)
{
n=n/10;
len++;
}
return len;
}
inline long vec_nle(__m128d *v, double f)
{
return (v[0][0] <= f ||
v[0][1] <= f ||
v[1][0] <= f ||
v[1][1] <= f ||
v[2][0] <= f ||
v[2][1] <= f ||
v[3][0] <= f ||
v[3][1] <= f) ? 0 : -1;
}
inline void clrPixels_nle(__m128d *v, double f, unsigned long * pix8)
{
if(!(v[0][0] <= f)) *pix8 &= 0x7f;
if(!(v[0][1] <= f)) *pix8 &= 0xbf;
if(!(v[1][0] <= f)) *pix8 &= 0xdf;
if(!(v[1][1] <= f)) *pix8 &= 0xef;
if(!(v[2][0] <= f)) *pix8 &= 0xf7;
if(!(v[2][1] <= f)) *pix8 &= 0xfb;
if(!(v[3][0] <= f)) *pix8 &= 0xfd;
if(!(v[3][1] <= f)) *pix8 &= 0xfe;
}
inline void calcSum(__m128d *r, __m128d *i, __m128d *sum, __m128d *init_r, __m128d init_i)
{
for(long pair=0; pair<4; pair++)
{
__m128d r2 = r[pair] * r[pair];
__m128d i2 = i[pair] * i[pair];
__m128d ri = r[pair] * i[pair];
sum[pair] = r2 + i2;
r[pair]=r2 - i2 + init_r[pair];
i[pair]=ri + ri + init_i;
}
}
inline unsigned long mand8(__m128d *init_r, __m128d init_i)
{
__m128d r[4], i[4], sum[4];
for(long pair=0; pair<4; pair++)
{
r[pair]=init_r[pair];
i[pair]=init_i;
}
unsigned long pix8 = 0xff;
for (long j = 0; j < 6; j++)
{
for(long k=0; k<8; k++)
calcSum(r, i, sum, init_r, init_i);
if (vec_nle(sum, 4.0))
{
pix8 = 0x00;
break;
}
}
if (pix8)
{
calcSum(r, i, sum, init_r, init_i);
calcSum(r, i, sum, init_r, init_i);
clrPixels_nle(sum, 4.0, &pix8);
}
return pix8;
}
unsigned long mand64(__m128d *init_r, __m128d init_i)
{
unsigned long pix64 = 0;
for(long byte=0; byte<8; byte++)
{
unsigned long pix8 = mand8(init_r, init_i);
pix64 = (pix64 >> 8) | (pix8 << 56);
init_r += 4;
}
return pix64;
}
int main(int argc, char ** argv)
{
// get width/height from arguments
long wid_ht = 200;
if (argc >= 2)
{
wid_ht = atoi(argv[1]);
}
wid_ht = (wid_ht+7) & ~7;
// allocate memory for header and pixels
long headerLength = numDigits(wid_ht)*2+5;
long pad = ((headerLength + 7) & ~7) - headerLength; // pad aligns pixels on 8
long dataLength = headerLength + wid_ht*(wid_ht>>3);
unsigned char * const buffer = malloc(pad + dataLength);
unsigned char * const header = buffer + pad;
unsigned char * const pixels = header + headerLength;
// generate the bitmap header
sprintf((char *)header, "P4\n%ld %ld\n", wid_ht, wid_ht);
// calculate initial values, store in r0, i0
__m128d r0[wid_ht/2];
double i0[wid_ht];
for(long xy=0; xy<wid_ht; xy+=2)
{
r0[xy>>1] = 2.0 / wid_ht * (__m128d){xy, xy+1} - 1.5;
i0[xy] = 2.0 / wid_ht * xy - 1.0;
i0[xy+1] = 2.0 / wid_ht * (xy+1) - 1.0;
}
// generate the bitmap
long use8 = wid_ht%64;
if (use8)
{
// process 8 pixels (one byte) at a time
#pragma omp parallel for schedule(guided)
for(long y=0; y<wid_ht; y++)
{
__m128d init_i = (__m128d){i0[y], i0[y]};
long rowstart = y*wid_ht/8;
for(long x=0; x<wid_ht; x+=8)
{
pixels[rowstart + x/8] = mand8(r0+x/2, init_i);
}
}
}
else
{
// process 64 pixels (8 bytes) at a time
#pragma omp parallel for schedule(guided)
for(long y=0; y<wid_ht; y++)
{
__m128d init_i = (__m128d){i0[y], i0[y]};
long rowstart = y*wid_ht/64;
for(long x=0; x<wid_ht; x+=64)
{
((unsigned long *)pixels)[rowstart + x/64] = mand64(r0+x/2, init_i);
}
}
}
// write the data
long ret = ret = write(STDOUT_FILENO, header, dataLength);
free(buffer);
return 0;
}
|
GB_binop__bclr_int16.c |
//------------------------------------------------------------------------------
// GB_binop: hard-coded functions for each built-in binary operator
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If this file is in the Generated2/ folder, do not edit it
// (it is auto-generated from Generator/*).
#include "GB.h"
#ifndef 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__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_08__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_02__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_04__bclr_int16)
// A.*B function (eWiseMult): GB (_AemultB_bitmap__bclr_int16)
// A*D function (colscale): GB ((none))
// D*A function (rowscale): GB ((none))
// C+=B function (dense accum): GB (_Cdense_accumB__bclr_int16)
// C+=b function (dense accum): GB (_Cdense_accumb__bclr_int16)
// C+=A+B function (dense ewise3): GB ((none))
// C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bclr_int16)
// C=scalar+B GB (_bind1st__bclr_int16)
// C=scalar+B' GB (_bind1st_tran__bclr_int16)
// C=A+scalar GB (_bind2nd__bclr_int16)
// C=A'+scalar GB (_bind2nd_tran__bclr_int16)
// C type: int16_t
// A type: int16_t
// A pattern? 0
// B type: int16_t
// B pattern? 0
// BinaryOp: cij = GB_BITCLR (aij, bij, int16_t, 16)
#define GB_ATYPE \
int16_t
#define GB_BTYPE \
int16_t
#define GB_CTYPE \
int16_t
// true if the types of A and B are identical
#define GB_ATYPE_IS_BTYPE \
1
// true if the types of C and A are identical
#define GB_CTYPE_IS_ATYPE \
1
// true if the types of C and B are identical
#define GB_CTYPE_IS_BTYPE \
1
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA,A_iso) \
int16_t aij = GBX (Ax, pA, A_iso)
// true if values of A are not used
#define GB_A_IS_PATTERN \
0 \
// bij = Bx [pB]
#define GB_GETB(bij,Bx,pB,B_iso) \
int16_t bij = GBX (Bx, pB, B_iso)
// true if values of B are not used
#define GB_B_IS_PATTERN \
0 \
// declare scalar of the same type as C
#define GB_CTYPE_SCALAR(t) \
int16_t t
// cij = Ax [pA]
#define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \
cij = GBX (Ax, pA, A_iso)
// cij = Bx [pB]
#define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \
cij = GBX (Bx, pB, B_iso)
#define GB_CX(p) Cx [p]
// binary operator
#define GB_BINOP(z,x,y,i,j) \
z = GB_BITCLR (x, y, int16_t, 16) ;
// true if the binop must be flipped
#define GB_BINOP_FLIP \
1
// op is second
#define GB_OP_IS_SECOND \
0
// do the numerical phases of GB_add and GB_emult
#define GB_PHASE_2_OF_2
// hard-coded loops can be vectorized
#define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_BCLR || GxB_NO_INT16 || GxB_NO_BCLR_INT16)
//------------------------------------------------------------------------------
// 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__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix B,
const int nthreads
)
{
#include "GB_dense_ewise3_noaccum_template.c"
}
//------------------------------------------------------------------------------
// C += B, accumulate a sparse matrix into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumB__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix B,
const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
#include "GB_dense_subassign_23_template.c"
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C += b, accumulate a scalar into a dense matrix
//------------------------------------------------------------------------------
GrB_Info GB (_Cdense_accumb__bclr_int16)
(
GrB_Matrix C,
const GB_void *p_bwork,
const int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
{
// get the scalar b for C += b, of type int16_t
int16_t bwork = (*((int16_t *) p_bwork)) ;
#include "GB_dense_subassign_22_template.c"
return (GrB_SUCCESS) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = A*D, column scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix A,
const GrB_Matrix D,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_colscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// C = D*B, row scale with diagonal D matrix
//------------------------------------------------------------------------------
#if 0
GrB_Info GB ((none))
(
GrB_Matrix C,
const GrB_Matrix D,
const GrB_Matrix B,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *restrict Cx = (int16_t *) C->x ;
#include "GB_AxB_rowscale_template.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
//------------------------------------------------------------------------------
// eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B
//------------------------------------------------------------------------------
GrB_Info GB (_AaddB__bclr_int16)
(
GrB_Matrix C,
const int C_sparsity,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool is_eWiseUnion,
const GB_void *alpha_scalar_in,
const GB_void *beta_scalar_in,
const bool Ch_is_Mh,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
GB_WERK_DECLARE (M_ek_slicing, int64_t) ;
GB_WERK_DECLARE (A_ek_slicing, int64_t) ;
GB_WERK_DECLARE (B_ek_slicing, int64_t) ;
int16_t alpha_scalar ;
int16_t beta_scalar ;
if (is_eWiseUnion)
{
alpha_scalar = (*((int16_t *) alpha_scalar_in)) ;
beta_scalar = (*((int16_t *) beta_scalar_in )) ;
}
#include "GB_add_template.c"
GB_FREE_WORKSPACE ;
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_08__bclr_int16)
(
GrB_Matrix C,
const int C_sparsity,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict C_to_M,
const int64_t *restrict C_to_A,
const int64_t *restrict C_to_B,
const GB_task_struct *restrict TaskList,
const int C_ntasks,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_08_meta.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_02__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const bool flipxy,
const int64_t *restrict Cp_kfirst,
const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#if GB_BINOP_FLIP
// The operator is not commutative, and does not have a flipped
// variant. For example z=atan2(y,x).
if (flipxy)
{
// use fmult(y,x)
#undef GB_FLIPPED
#define GB_FLIPPED 1
#include "GB_emult_02_template.c"
}
else
{
// use fmult(x,y)
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
}
#else
// No need to handle the flip: the operator is either commutative, or
// has been handled by changing z=div(y,x) to z=rdiv(x,y) for example.
#undef GB_FLIPPED
#define GB_FLIPPED 0
#include "GB_emult_02_template.c"
#endif
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_04__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix M,
const bool Mask_struct,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *restrict Cp_kfirst,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_emult_04_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap
//------------------------------------------------------------------------------
GrB_Info GB (_AemultB_bitmap__bclr_int16)
(
GrB_Matrix C,
const int ewise_method,
const GrB_Matrix M,
const bool Mask_struct,
const bool Mask_comp,
const GrB_Matrix A,
const GrB_Matrix B,
const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads,
const int C_nthreads,
GB_Context Context
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_bitmap_emult_template.c"
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st
//------------------------------------------------------------------------------
GrB_Info GB (_bind1st__bclr_int16)
(
GB_void *Cx_output, // Cx and Bx may be aliased
const GB_void *x_input,
const GB_void *Bx_input,
const int8_t *restrict Bb,
int64_t bnz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t *Cx = (int16_t *) Cx_output ;
int16_t x = (*((int16_t *) x_input)) ;
int16_t *Bx = (int16_t *) Bx_input ;
int64_t p ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < bnz ; p++)
{
if (!GBB (Bb, p)) continue ;
int16_t bij = GBX (Bx, p, false) ;
Cx [p] = GB_BITCLR (x, bij, int16_t, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd
//------------------------------------------------------------------------------
GrB_Info GB (_bind2nd__bclr_int16)
(
GB_void *Cx_output, // Cx and Ax may be aliased
const GB_void *Ax_input,
const GB_void *y_input,
const int8_t *restrict Ab,
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
int16_t *Cx = (int16_t *) Cx_output ;
int16_t *Ax = (int16_t *) Ax_input ;
int16_t y = (*((int16_t *) y_input)) ;
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!GBB (Ab, p)) continue ;
int16_t aij = GBX (Ax, p, false) ;
Cx [p] = GB_BITCLR (aij, y, int16_t, 16) ;
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (x, A'): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (x, aij), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITCLR (x, aij, int16_t, 16) ; \
}
GrB_Info GB (_bind1st_tran__bclr_int16)
(
GrB_Matrix C,
const GB_void *x_input,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
// GB_unop_transpose.c uses GB_ATYPE, but A is
// the 2nd input to binary operator z=f(x,y).
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t x = (*((const int16_t *) x_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
#undef GB_ATYPE
#define GB_ATYPE \
int16_t
}
//------------------------------------------------------------------------------
// C = op (A', y): transpose and apply a binary operator
//------------------------------------------------------------------------------
// cij = op (aij, y), no typecasting (in spite of the macro name)
#undef GB_CAST_OP
#define GB_CAST_OP(pC,pA) \
{ \
int16_t aij = GBX (Ax, pA, false) ; \
Cx [pC] = GB_BITCLR (aij, y, int16_t, 16) ; \
}
GrB_Info GB (_bind2nd_tran__bclr_int16)
(
GrB_Matrix C,
const GrB_Matrix A,
const GB_void *y_input,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int16_t y = (*((const int16_t *) y_input)) ;
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
gt.region.c | /*
* PROJECT: GEM-Tools library
* FILE: gt.gtfcount.c
* DATE: 10/07/2013
* AUTHOR(S): Thasso Griebel <thasso.griebel@gmail.com>
* DESCRIPTION: Annotation map a file against a reference annotation
*/
#include <getopt.h>
#include <omp.h>
#include "gem_tools.h"
typedef struct {
char *input_file;
char *output_file;
char *annotation;
char *gene_id;
bool paired;
uint64_t num_threads;
} gt_region_args;
gt_region_args parameters = {
.input_file=NULL,
.output_file=NULL,
.annotation=NULL,
.gene_id=NULL,
.paired=false,
.num_threads=1
};
GT_INLINE void gt_region_read(gt_gtf* const gtf) {
// Open file IN/OUT
gt_input_file* input_file = (parameters.input_file==NULL) ?
gt_input_stream_open(stdin) : gt_input_file_open(parameters.input_file,false);
gt_output_file* output_file = (parameters.output_file==NULL) ?
gt_output_stream_new(stdout,SORTED_FILE) : gt_output_file_new(parameters.output_file,SORTED_FILE);
// Parallel I/O
#pragma omp parallel num_threads(parameters.num_threads)
{
gt_vector* hits = gt_vector_new(16, sizeof(gt_gtf_entry*));
gt_output_map_attributes* const output_map_attributes = gt_output_map_attributes_new();
GT_BEGIN_READING_WRITING_LOOP(input_file,output_file,parameters.paired,buffered_output,template){
gt_vector_clear(hits);
gt_gtf_search_template(gtf, hits, template);
GT_VECTOR_ITERATE(hits, v, c, gt_gtf_entry*){
gt_gtf_entry* e = *v;
if(parameters.gene_id != NULL && e->gene_id != NULL){
if(strcmp(e->gene_id->buffer, parameters.gene_id) == 0){
//gt_output_map_bofprint_gem_template(buffered_output, template, output_map_attributes);
gt_output_map_fprint_gem_template(stdout, template, output_map_attributes);
break;
}
}
}
}GT_END_READING_WRITING_LOOP(input_file,output_file,template);
// cleanup per threads
gt_vector_delete(hits);
gt_output_map_attributes_delete(output_map_attributes);
}
// Clean global
gt_input_file_close(input_file);
gt_output_file_close(output_file);
}
void parse_arguments(int argc,char** argv) {
struct option* gt_region_getopt = gt_options_adaptor_getopt(gt_region_options);
gt_string* const gt_region_short_getopt = gt_options_adaptor_getopt_short(gt_region_options);
int option, option_index;
while (true) {
// Get option & Select case
if ((option=getopt_long(argc,argv,
gt_string_get_string(gt_region_short_getopt),gt_region_getopt,&option_index))==-1) break;
switch (option) {
/* I/O */
case 'i':
parameters.input_file = optarg;
break;
case 'o':
parameters.output_file = optarg;
break;
case 'a':
parameters.annotation = optarg;
break;
case 'p':
parameters.paired = true;
break;
/* Misc */
case 'g':
parameters.gene_id = optarg;
break;
case 't':
parameters.num_threads = atol(optarg);
break;
case 'h':
fprintf(stderr, "USE: gt.gtfcount [OPERATION] [ARGS]...\n");
gt_options_fprint_menu(stderr,gt_region_options,gt_region_groups,false,false);
exit(1);
case 'J':
gt_options_fprint_json_menu(stderr,gt_region_options,gt_region_groups,true,false);
exit(1);
break;
case '?':
default:
gt_fatal_error_msg("Option not recognized");
}
}
// Check parameters
if (parameters.annotation==NULL) {
gt_fatal_error_msg("Please specify a reference annotation");
}
// Free
gt_string_delete(gt_region_short_getopt);
}
int main(int argc,char** argv) {
// GT error handler
gt_handle_error_signals();
parse_arguments(argc,argv);
// read gtf file
gt_gtf* const gtf = gt_gtf_read_from_file(parameters.annotation, parameters.num_threads);
gt_region_read(gtf);
return 0;
}
|
mandelbrot_gcc4.c |
/*
gcc -pipe -Wall -O3 -fomit-frame-pointer -march=native -std=c99 -D_GNU_SOURCE -mfpmath=sse -msse2 -fopenmp mandelbrot.gcc-4.c -o mandelbrot.gcc-4.gcc_run
*/
/* The Computer Language Benchmarks Game
* http://benchmarksgame.alioth.debian.org/
contributed by Paolo Bonzini
further optimized by Jason Garrett-Glaser
pthreads added by Eckehard Berns
further optimized by Ryan Henszey
modified by Samy Al Bahra (use GCC atomic builtins)
modified by Kenneth Jonsson
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
typedef
double v2df __attribute__ ((vector_size(16))); /* vector of two doubles */
#if(0)
typedef int v4si __attribute__ ((vector_size(16))); /* vector of four ints */
#endif
const v2df zero = { 0.0, 0.0 };
const v2df four = { 4.0, 4.0 };
/*
* Constant throughout the program, value depends on N
*/
int bytes_per_row;
double inverse_w;
double inverse_h;
/*
* Program argument: height and width of the image
*/
int N;
/*
* Lookup table for initial real-axis value
*/
v2df *Crvs;
/*
* Mandelbrot bitmap
*/
uint8_t *bitmap;
static void calc_row(int y) {
uint8_t *row_bitmap = bitmap + (bytes_per_row * y);
int x;
const v2df Civ_init = { y*inverse_h-1.0, y*inverse_h-1.0 };
for (x=0; x<N; x+=2)
{
v2df Crv = Crvs[x >> 1];
v2df Civ = Civ_init;
v2df Zrv = zero;
v2df Ziv = zero;
v2df Trv = zero;
v2df Tiv = zero;
int i = 50;
int two_pixels;
v2df is_still_bounded;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
/*
* All bits will be set to 1 if 'Trv + Tiv' is less than 4
* and all bits will be set to 0 otherwise. Two elements
* are calculated in parallel here.
*/
is_still_bounded = __builtin_ia32_cmplepd(Trv + Tiv, four);
/*
* Move the sign-bit of the low element to bit 0, move the
* sign-bit of the high element to bit 1. The result is
* that the pixel will be set if the calculation was
* bounded.
*/
two_pixels = __builtin_ia32_movmskpd(is_still_bounded);
} while (--i > 0 && two_pixels);
/*
* The pixel bits must be in the most and second most
* significant position
*/
two_pixels <<= 6;
/*
* Add the two pixels to the bitmap, all bits are
* initially zero since the area was allocated with
* calloc()
*/
row_bitmap[x >> 3] |= (uint8_t) (two_pixels >> (x & 7));
}
}
int main (int argc, char **argv)
{
int i;
N = atoi(argv[1]);
bytes_per_row = (N + 7) >> 3;
inverse_w = 2.0 / (bytes_per_row << 3);
inverse_h = 2.0 / N;
/*
* Crvs must be 16-bytes aligned on some CPU:s.
*/
if (posix_memalign((void**)&Crvs, sizeof(v2df), sizeof(v2df) * N / 2))
return EXIT_FAILURE;
#pragma omp parallel for
for (i = 0; i < N; i+=2) {
v2df Crv = { (i+1.0)*inverse_w-1.5, (i)*inverse_w-1.5 };
Crvs[i >> 1] = Crv;
}
bitmap = calloc(bytes_per_row, N);
if (bitmap == NULL)
return EXIT_FAILURE;
#pragma omp parallel for schedule(static,1)
for (i = 0; i < N; i++)
calc_row(i);
printf("P4\n%d %d\n", N, N);
fwrite(bitmap, bytes_per_row, N, stdout);
free(bitmap);
free(Crvs);
return EXIT_SUCCESS;
}
/* ****** ****** */
/* end of [mandelbrot_gcc4.c] */
|
BsplineFunctor.h | //////////////////////////////////////////////////////////////////////////////////////
// This file is distributed under the University of Illinois/NCSA Open Source License.
// See LICENSE file in top directory for details.
//
// Copyright (c) 2016 Jeongnim Kim and QMCPACK developers.
//
// File developed by: John R. Gergely, University of Illinois at Urbana-Champaign
// Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign
// Miguel Morales, moralessilva2@llnl.gov, Lawrence Livermore National Laboratory
// Raymond Clay III, j.k.rofling@gmail.com, Lawrence Livermore National Laboratory
// Jeremy McMinnis, jmcminis@gmail.com, University of Illinois at Urbana-Champaign
// Jeongnim Kim, jeongnim.kim@gmail.com, University of Illinois at Urbana-Champaign
// Jaron T. Krogel, krogeljt@ornl.gov, Oak Ridge National Laboratory
// Mark A. Berrill, berrillma@ornl.gov, Oak Ridge National Laboratory
// Amrita Mathuriya, amrita.mathuriya@intel.com, Intel Corp.
//
// File created by: Ken Esler, kpesler@gmail.com, University of Illinois at Urbana-Champaign
//////////////////////////////////////////////////////////////////////////////////////
#ifndef QMCPLUSPLUS_BSPLINE_FUNCTOR_H
#define QMCPLUSPLUS_BSPLINE_FUNCTOR_H
#include "Numerics/OptimizableFunctorBase.h"
#include "Utilities/ProgressReportEngine.h"
#include "OhmmsData/AttributeSet.h"
#include "Numerics/LinearFit.h"
#include "simd/allocator.hpp"
#include <cstdio>
namespace qmcplusplus
{
template<class T>
struct BsplineFunctor : public OptimizableFunctorBase
{
typedef real_type value_type;
int NumParams;
int Dummy;
const real_type A[16], dA[16], d2A[16], d3A[16];
aligned_vector<real_type> SplineCoefs;
//static const real_type A[16], dA[16], d2A[16];
real_type DeltaR, DeltaRInv;
real_type CuspValue;
real_type Y, dY, d2Y;
// Stores the derivatives w.r.t. SplineCoefs
// of the u, du/dr, and d2u/dr2
std::vector<TinyVector<real_type, 3>> SplineDerivs;
std::vector<real_type> Parameters;
std::vector<std::string> ParameterNames;
std::string elementType, pairType;
std::string fileName;
int ResetCount;
bool notOpt;
bool periodic;
///constructor
BsplineFunctor(real_type cusp = 0.0)
: NumParams(0),
A{-1.0 / 6.0,
3.0 / 6.0,
-3.0 / 6.0,
1.0 / 6.0,
3.0 / 6.0,
-6.0 / 6.0,
0.0 / 6.0,
4.0 / 6.0,
-3.0 / 6.0,
3.0 / 6.0,
3.0 / 6.0,
1.0 / 6.0,
1.0 / 6.0,
0.0 / 6.0,
0.0 / 6.0,
0.0 / 6.0},
dA{0.0, -0.5, 1.0, -0.5, 0.0, 1.5, -2.0, 0.0, 0.0, -1.5, 1.0, 0.5, 0.0, 0.5, 0.0, 0.0},
d2A{0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0},
d3A{0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 3.0, 0.0, 0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 1.0},
CuspValue(cusp),
ResetCount(0),
notOpt(false),
periodic(true)
{
cutoff_radius = 0.0;
}
OptimizableFunctorBase* makeClone() const { return new BsplineFunctor(*this); }
void setCusp(real_type c) { CuspValue = c; }
void setPeriodic(bool p) { periodic = p; }
void resize(int n)
{
NumParams = n;
int numCoefs = NumParams + 4;
int numKnots = numCoefs - 2;
DeltaR = cutoff_radius / (real_type)(numKnots - 1);
DeltaRInv = 1.0 / DeltaR;
Parameters.resize(n);
SplineCoefs.resize(numCoefs);
SplineDerivs.resize(numCoefs);
}
void reset()
{
int numCoefs = NumParams + 4;
int numKnots = numCoefs - 2;
DeltaR = cutoff_radius / (real_type)(numKnots - 1);
DeltaRInv = 1.0 / DeltaR;
for (int i = 0; i < SplineCoefs.size(); i++)
SplineCoefs[i] = 0.0;
// Ensure that cusp conditions is satisfied at the origin
SplineCoefs[1] = Parameters[0];
SplineCoefs[2] = Parameters[1];
SplineCoefs[0] = Parameters[1] - 2.0 * DeltaR * CuspValue;
for (int i = 2; i < Parameters.size(); i++)
SplineCoefs[i + 1] = Parameters[i];
}
/** compute value, gradient and laplacian for [iStart, iEnd) pairs
* @param iat dummy
* @param iStart starting particle index
* @param iEnd ending particle index
* @param _distArray distance arrUay
* @param _valArray u(r_j) for j=[iStart,iEnd)
* @param _gradArray du(r_j)/dr /r_j for j=[iStart,iEnd)
* @param _lapArray d2u(r_j)/dr2 for j=[iStart,iEnd)
* @param distArrayCompressed temp storage to filter r_j < cutoff_radius
* @param distIndices temp storage for the compressed index
*/
void evaluateVGL(const int iat,
const int iStart,
const int iEnd,
const T* _distArray,
T* restrict _valArray,
T* restrict _gradArray,
T* restrict _laplArray,
T* restrict distArrayCompressed,
int* restrict distIndices) const;
/** evaluate sum of the pair potentials for [iStart,iEnd)
* @param iat dummy
* @param iStart starting particle index
* @param iEnd ending particle index
* @param _distArray distance arrUay
* @param distArrayCompressed temp storage to filter r_j < cutoff_radius
* @return \f$\sum u(r_j)\f$ for r_j < cutoff_radius
*/
T evaluateV(const int iat,
const int iStart,
const int iEnd,
const T* restrict _distArray,
T* restrict distArrayCompressed) const;
inline real_type evaluate(real_type r)
{
if (r >= cutoff_radius)
return 0.0;
r *= DeltaRInv;
real_type ipart, t;
t = std::modf(r, &ipart);
int i = (int)ipart;
real_type tp[4];
tp[0] = t * t * t;
tp[1] = t * t;
tp[2] = t;
tp[3] = 1.0;
return (SplineCoefs[i + 0] * (A[0] * tp[0] + A[1] * tp[1] + A[2] * tp[2] + A[3] * tp[3]) +
SplineCoefs[i + 1] * (A[4] * tp[0] + A[5] * tp[1] + A[6] * tp[2] + A[7] * tp[3]) +
SplineCoefs[i + 2] * (A[8] * tp[0] + A[9] * tp[1] + A[10] * tp[2] + A[11] * tp[3]) +
SplineCoefs[i + 3] * (A[12] * tp[0] + A[13] * tp[1] + A[14] * tp[2] + A[15] * tp[3]));
}
inline real_type evaluate(real_type r, real_type rinv) { return Y = evaluate(r, dY, d2Y); }
inline void evaluateAll(real_type r, real_type rinv) { Y = evaluate(r, dY, d2Y); }
inline real_type evaluate(real_type r, real_type& dudr, real_type& d2udr2)
{
if (r >= cutoff_radius)
{
dudr = d2udr2 = 0.0;
return 0.0;
}
// real_type eps = 1.0e-5;
// real_type dudr_FD = (evaluate(r+eps)-evaluate(r-eps))/(2.0*eps);
// real_type d2udr2_FD = (evaluate(r+eps)+evaluate(r-eps)-2.0*evaluate(r))/(eps*eps);
r *= DeltaRInv;
real_type ipart, t;
t = std::modf(r, &ipart);
int i = (int)ipart;
real_type tp[4];
tp[0] = t * t * t;
tp[1] = t * t;
tp[2] = t;
tp[3] = 1.0;
d2udr2 = DeltaRInv * DeltaRInv *
(SplineCoefs[i + 0] * (d2A[0] * tp[0] + d2A[1] * tp[1] + d2A[2] * tp[2] + d2A[3] * tp[3]) +
SplineCoefs[i + 1] * (d2A[4] * tp[0] + d2A[5] * tp[1] + d2A[6] * tp[2] + d2A[7] * tp[3]) +
SplineCoefs[i + 2] * (d2A[8] * tp[0] + d2A[9] * tp[1] + d2A[10] * tp[2] + d2A[11] * tp[3]) +
SplineCoefs[i + 3] * (d2A[12] * tp[0] + d2A[13] * tp[1] + d2A[14] * tp[2] + d2A[15] * tp[3]));
dudr = DeltaRInv *
(SplineCoefs[i + 0] * (dA[0] * tp[0] + dA[1] * tp[1] + dA[2] * tp[2] + dA[3] * tp[3]) +
SplineCoefs[i + 1] * (dA[4] * tp[0] + dA[5] * tp[1] + dA[6] * tp[2] + dA[7] * tp[3]) +
SplineCoefs[i + 2] * (dA[8] * tp[0] + dA[9] * tp[1] + dA[10] * tp[2] + dA[11] * tp[3]) +
SplineCoefs[i + 3] * (dA[12] * tp[0] + dA[13] * tp[1] + dA[14] * tp[2] + dA[15] * tp[3]));
// if (std::abs(dudr_FD-dudr) > 1.0e-8)
// std::cerr << "Error in BsplineFunction: dudr = " << dudr
// << " dudr_FD = " << dudr_FD << std::endl;
// if (std::abs(d2udr2_FD-d2udr2) > 1.0e-4)
// std::cerr << "Error in BsplineFunction: r = " << r << " d2udr2 = " << dudr
// << " d2udr2_FD = " << d2udr2_FD << " rcut = " << cutoff_radius << std::endl;
return (SplineCoefs[i + 0] * (A[0] * tp[0] + A[1] * tp[1] + A[2] * tp[2] + A[3] * tp[3]) +
SplineCoefs[i + 1] * (A[4] * tp[0] + A[5] * tp[1] + A[6] * tp[2] + A[7] * tp[3]) +
SplineCoefs[i + 2] * (A[8] * tp[0] + A[9] * tp[1] + A[10] * tp[2] + A[11] * tp[3]) +
SplineCoefs[i + 3] * (A[12] * tp[0] + A[13] * tp[1] + A[14] * tp[2] + A[15] * tp[3]));
}
inline real_type evaluate(real_type r, real_type& dudr, real_type& d2udr2, real_type& d3udr3)
{
if (r >= cutoff_radius)
{
dudr = d2udr2 = d3udr3 = 0.0;
return 0.0;
}
// real_type eps = 1.0e-5;
// real_type dudr_FD = (evaluate(r+eps)-evaluate(r-eps))/(2.0*eps);
// real_type d2udr2_FD = (evaluate(r+eps)+evaluate(r-eps)-2.0*evaluate(r))/(eps*eps);
// real_type d3udr3_FD = (-1.0*evaluate(r+1.0*eps)
// +2.0*evaluate(r+0.5*eps)
// -2.0*evaluate(r-0.5*eps)
// +1.0*evaluate(r-1.0*eps))/(eps*eps*eps);
r *= DeltaRInv;
real_type ipart, t;
t = std::modf(r, &ipart);
int i = (int)ipart;
real_type tp[4];
tp[0] = t * t * t;
tp[1] = t * t;
tp[2] = t;
tp[3] = 1.0;
d3udr3 = DeltaRInv * DeltaRInv * DeltaRInv *
(SplineCoefs[i + 0] * (d3A[0] * tp[0] + d3A[1] * tp[1] + d3A[2] * tp[2] + d3A[3] * tp[3]) +
SplineCoefs[i + 1] * (d3A[4] * tp[0] + d3A[5] * tp[1] + d3A[6] * tp[2] + d3A[7] * tp[3]) +
SplineCoefs[i + 2] * (d3A[8] * tp[0] + d3A[9] * tp[1] + d3A[10] * tp[2] + d3A[11] * tp[3]) +
SplineCoefs[i + 3] * (d3A[12] * tp[0] + d3A[13] * tp[1] + d3A[14] * tp[2] + d3A[15] * tp[3]));
d2udr2 = DeltaRInv * DeltaRInv *
(SplineCoefs[i + 0] * (d2A[0] * tp[0] + d2A[1] * tp[1] + d2A[2] * tp[2] + d2A[3] * tp[3]) +
SplineCoefs[i + 1] * (d2A[4] * tp[0] + d2A[5] * tp[1] + d2A[6] * tp[2] + d2A[7] * tp[3]) +
SplineCoefs[i + 2] * (d2A[8] * tp[0] + d2A[9] * tp[1] + d2A[10] * tp[2] + d2A[11] * tp[3]) +
SplineCoefs[i + 3] * (d2A[12] * tp[0] + d2A[13] * tp[1] + d2A[14] * tp[2] + d2A[15] * tp[3]));
dudr = DeltaRInv *
(SplineCoefs[i + 0] * (dA[0] * tp[0] + dA[1] * tp[1] + dA[2] * tp[2] + dA[3] * tp[3]) +
SplineCoefs[i + 1] * (dA[4] * tp[0] + dA[5] * tp[1] + dA[6] * tp[2] + dA[7] * tp[3]) +
SplineCoefs[i + 2] * (dA[8] * tp[0] + dA[9] * tp[1] + dA[10] * tp[2] + dA[11] * tp[3]) +
SplineCoefs[i + 3] * (dA[12] * tp[0] + dA[13] * tp[1] + dA[14] * tp[2] + dA[15] * tp[3]));
// if (std::abs(dudr_FD-dudr) > 1.0e-8)
// std::cerr << "Error in BsplineFunction: dudr = " << dudr
// << " dudr_FD = " << dudr_FD << std::endl;
// if (std::abs(d2udr2_FD-d2udr2) > 1.0e-4)
// std::cerr << "Error in BsplineFunction: r = " << r << " d2udr2 = " << dudr
// << " d2udr2_FD = " << d2udr2_FD << " rcut = " << cutoff_radius << std::endl;
// if (std::abs(d3udr3_FD-d3udr3) > 1.0e-4)
// std::cerr << "Error in BsplineFunction: r = " << r << " d3udr3 = " << dudr
// << " d3udr3_FD = " << d3udr3_FD << " rcut = " << cutoff_radius << std::endl;
return (SplineCoefs[i + 0] * (A[0] * tp[0] + A[1] * tp[1] + A[2] * tp[2] + A[3] * tp[3]) +
SplineCoefs[i + 1] * (A[4] * tp[0] + A[5] * tp[1] + A[6] * tp[2] + A[7] * tp[3]) +
SplineCoefs[i + 2] * (A[8] * tp[0] + A[9] * tp[1] + A[10] * tp[2] + A[11] * tp[3]) +
SplineCoefs[i + 3] * (A[12] * tp[0] + A[13] * tp[1] + A[14] * tp[2] + A[15] * tp[3]));
}
inline bool evaluateDerivatives(real_type r, std::vector<TinyVector<real_type, 3>>& derivs)
{
if (r >= cutoff_radius)
return false;
r *= DeltaRInv;
real_type ipart, t;
t = std::modf(r, &ipart);
int i = (int)ipart;
real_type tp[4];
tp[0] = t * t * t;
tp[1] = t * t;
tp[2] = t;
tp[3] = 1.0;
SplineDerivs[0] = TinyVector<real_type, 3>(0.0);
// d/dp_i u(r)
SplineDerivs[i + 0][0] = A[0] * tp[0] + A[1] * tp[1] + A[2] * tp[2] + A[3] * tp[3];
SplineDerivs[i + 1][0] = A[4] * tp[0] + A[5] * tp[1] + A[6] * tp[2] + A[7] * tp[3];
SplineDerivs[i + 2][0] = A[8] * tp[0] + A[9] * tp[1] + A[10] * tp[2] + A[11] * tp[3];
SplineDerivs[i + 3][0] = A[12] * tp[0] + A[13] * tp[1] + A[14] * tp[2] + A[15] * tp[3];
// d/dp_i du/dr
SplineDerivs[i + 0][1] = DeltaRInv * (dA[1] * tp[1] + dA[2] * tp[2] + dA[3] * tp[3]);
SplineDerivs[i + 1][1] = DeltaRInv * (dA[5] * tp[1] + dA[6] * tp[2] + dA[7] * tp[3]);
SplineDerivs[i + 2][1] = DeltaRInv * (dA[9] * tp[1] + dA[10] * tp[2] + dA[11] * tp[3]);
SplineDerivs[i + 3][1] = DeltaRInv * (dA[13] * tp[1] + dA[14] * tp[2] + dA[15] * tp[3]);
// d/dp_i d2u/dr2
SplineDerivs[i + 0][2] = DeltaRInv * DeltaRInv * (d2A[2] * tp[2] + d2A[3] * tp[3]);
SplineDerivs[i + 1][2] = DeltaRInv * DeltaRInv * (d2A[6] * tp[2] + d2A[7] * tp[3]);
SplineDerivs[i + 2][2] = DeltaRInv * DeltaRInv * (d2A[10] * tp[2] + d2A[11] * tp[3]);
SplineDerivs[i + 3][2] = DeltaRInv * DeltaRInv * (d2A[14] * tp[2] + d2A[15] * tp[3]);
int imin = std::max(i, 1);
int imax = std::min(i + 4, NumParams + 1);
for (int n = imin; n < imax; ++n)
derivs[n - 1] = SplineDerivs[n];
derivs[1] += SplineDerivs[0];
//real_type v[4],dv[4],d2v[4];
//v[0] = A[ 0]*tp[0] + A[ 1]*tp[1] + A[ 2]*tp[2] + A[ 3]*tp[3];
//v[1] = A[ 4]*tp[0] + A[ 5]*tp[1] + A[ 6]*tp[2] + A[ 7]*tp[3];
//v[2] = A[ 8]*tp[0] + A[ 9]*tp[1] + A[10]*tp[2] + A[11]*tp[3];
//v[3] = A[12]*tp[0] + A[13]*tp[1] + A[14]*tp[2] + A[15]*tp[3];
//// d/dp_i du/dr
//dv[0] = DeltaRInv * (dA[ 1]*tp[1] + dA[ 2]*tp[2] + dA[ 3]*tp[3]);
//dv[1] = DeltaRInv * (dA[ 5]*tp[1] + dA[ 6]*tp[2] + dA[ 7]*tp[3]);
//dv[2] = DeltaRInv * (dA[ 9]*tp[1] + dA[10]*tp[2] + dA[11]*tp[3]);
//dv[3] = DeltaRInv * (dA[13]*tp[1] + dA[14]*tp[2] + dA[15]*tp[3]);
//// d/dp_i d2u/dr2
//d2v[0] = DeltaRInv * DeltaRInv * (d2A[ 2]*tp[2] + d2A[ 3]*tp[3]);
//d2v[1] = DeltaRInv * DeltaRInv * (d2A[ 6]*tp[2] + d2A[ 7]*tp[3]);
//d2v[2] = DeltaRInv * DeltaRInv * (d2A[10]*tp[2] + d2A[11]*tp[3]);
//d2v[3] = DeltaRInv * DeltaRInv * (d2A[14]*tp[2] + d2A[15]*tp[3]);
//int imin=std::max(i,1);
//int imax=std::min(i+4,NumParams+1)-1;
//int n=imin-1, j=imin-i;
//while(n<imax && j<4)
//{
// derivs[n] = TinyVector<real_type,3>(v[j],dv[j],d2v[j]);
// n++; j++;
//}
//if(i==0) derivs[1]+= TinyVector<real_type,3>(v[0],dv[0],d2v[0]);
return true;
}
inline bool evaluateDerivatives(real_type r, std::vector<real_type>& derivs)
{
if (r >= cutoff_radius)
return false;
real_type tp[4], v[4], ipart, t;
t = std::modf(r * DeltaRInv, &ipart);
tp[0] = t * t * t;
tp[1] = t * t;
tp[2] = t;
tp[3] = 1.0;
v[0] = A[0] * tp[0] + A[1] * tp[1] + A[2] * tp[2] + A[3] * tp[3];
v[1] = A[4] * tp[0] + A[5] * tp[1] + A[6] * tp[2] + A[7] * tp[3];
v[2] = A[8] * tp[0] + A[9] * tp[1] + A[10] * tp[2] + A[11] * tp[3];
v[3] = A[12] * tp[0] + A[13] * tp[1] + A[14] * tp[2] + A[15] * tp[3];
int i = (int)ipart;
int imin = std::max(i, 1);
int imax = std::min(i + 4, NumParams + 1) - 1;
int n = imin - 1, j = imin - i;
while (n < imax && j < 4)
{
derivs[n] = v[j];
n++;
j++;
}
if (i == 0)
derivs[1] += v[0];
return true;
}
inline real_type f(real_type r)
{
if (r >= cutoff_radius)
return 0.0;
return evaluate(r);
}
inline real_type df(real_type r)
{
if (r >= cutoff_radius)
return 0.0;
real_type du, d2u;
evaluate(r, du, d2u);
return du;
}
bool put(xmlNodePtr cur)
{
ReportEngine PRE("BsplineFunctor", "put(xmlNodePtr)");
//CuspValue = -1.0e10;
NumParams = 0;
//cutoff_radius = 0.0;
OhmmsAttributeSet rAttrib;
real_type radius = -1.0;
rAttrib.add(NumParams, "size");
rAttrib.add(radius, "rcut");
rAttrib.add(radius, "cutoff");
rAttrib.put(cur);
if (radius < 0.0)
if (periodic)
{
app_log() << " Jastrow cutoff unspecified. Setting to Wigner-Seitz radius = " << cutoff_radius << std::endl;
app_log() << std::endl;
}
else
{
APP_ABORT(" Jastrow cutoff unspecified. Cutoff must be given when using open boundary conditions");
}
else if (periodic && radius > cutoff_radius)
{
if (radius - cutoff_radius > 1e-4)
{
APP_ABORT(" The Jastrow cutoff specified should not be larger than Wigner-Seitz radius.");
}
else
{
app_log() << " The Jastrow cutoff specified is slightly larger than the Wigner-Seitz radius.";
app_log() << " Setting to Wigner-Seitz radius = " << cutoff_radius << ".\n";
}
}
else
cutoff_radius = radius;
if (NumParams == 0)
{
PRE.error("You must specify a positive number of parameters for the Bspline jastrow function.", true);
}
app_summary() << " Number of parameters: " << NumParams << std::endl;
app_summary() << " Cusp: " << CuspValue << std::endl;
app_summary() << " Cutoff radius: " << cutoff_radius << std::endl;
resize(NumParams);
// Now read coefficents
xmlNodePtr xmlCoefs = cur->xmlChildrenNode;
while (xmlCoefs != NULL)
{
std::string cname((const char*)xmlCoefs->name);
if (cname == "coefficients")
{
std::string type("0"), id("0");
std::string optimize("yes");
OhmmsAttributeSet cAttrib;
cAttrib.add(id, "id");
cAttrib.add(type, "type");
cAttrib.add(optimize, "optimize");
cAttrib.put(xmlCoefs);
if (type != "Array")
{
PRE.error("Unknown correlation type " + type + " in BsplineFunctor." + "Resetting to \"Array\"");
xmlNewProp(xmlCoefs, (const xmlChar*)"type", (const xmlChar*)"Array");
}
std::vector<real_type> params;
putContent(params, xmlCoefs);
if (params.size() == NumParams)
Parameters = params;
else
{
app_log() << " Changing number of Bspline parameters from " << params.size() << " to " << NumParams
<< ". Performing fit:\n";
// Fit function to new number of parameters
const int numPoints = 500;
BsplineFunctor<T> tmp_func(CuspValue);
tmp_func.cutoff_radius = cutoff_radius;
tmp_func.resize(params.size());
tmp_func.Parameters = params;
tmp_func.reset();
std::vector<real_type> y(numPoints);
Matrix<real_type> basis(numPoints, NumParams);
std::vector<TinyVector<real_type, 3>> derivs(NumParams);
for (int i = 0; i < numPoints; i++)
{
real_type r = (real_type)i / (real_type)numPoints * cutoff_radius;
y[i] = tmp_func.evaluate(r);
evaluateDerivatives(r, derivs);
for (int j = 0; j < NumParams; j++)
basis(i, j) = derivs[j][0];
}
resize(NumParams);
LinearFit(y, basis, Parameters);
app_log() << "New parameters are:\n";
for (int i = 0; i < Parameters.size(); i++)
app_log() << " " << Parameters[i] << std::endl;
}
if (optimize == "yes")
{
notOpt = false;
}
else
{
notOpt = true;
}
for (int i = 0; i < NumParams; i++)
{
std::stringstream sstr;
sstr << id << "_" << i;
myVars.insert(sstr.str(), (value_type)Parameters[i], !notOpt, optimize::LOGLINEAR_P);
}
int left_pad_space = 5;
app_log() << std::endl;
myVars.print(app_log(), left_pad_space, true);
}
xmlCoefs = xmlCoefs->next;
}
reset();
real_type zeros = 0;
for (int i = 0; i < NumParams; i++)
zeros += Parameters[i] * Parameters[i];
return zeros > 1.0e-12; //true if Parameters are not zero
}
void initialize(int numPoints,
std::vector<real_type>& x,
std::vector<real_type>& y,
real_type cusp,
real_type rcut,
std::string& id,
std::string& optimize)
{
ReportEngine PRE("BsplineFunctor", "initialize");
NumParams = numPoints;
cutoff_radius = rcut;
CuspValue = cusp;
if (NumParams == 0)
{
PRE.error("You must specify a positive number of parameters for the Bspline jastrow function.", true);
}
app_log() << "Initializing BsplineFunctor from array. \n";
app_log() << " size = " << NumParams << " parameters " << std::endl;
app_log() << " cusp = " << CuspValue << std::endl;
app_log() << " rcut = " << cutoff_radius << std::endl;
resize(NumParams);
int npts = x.size();
Matrix<real_type> basis(npts, NumParams);
std::vector<TinyVector<real_type, 3>> derivs(NumParams);
for (int i = 0; i < npts; i++)
{
real_type r = x[i];
if (r > cutoff_radius)
{
PRE.error("Error in BsplineFunctor::initialize: r > cutoff_radius.", true);
}
evaluateDerivatives(r, derivs);
for (int j = 0; j < NumParams; j++)
basis(i, j) = derivs[j][0];
}
resize(NumParams);
LinearFit(y, basis, Parameters);
app_log() << "New parameters are:\n";
for (int i = 0; i < Parameters.size(); i++)
app_log() << " " << Parameters[i] << std::endl;
#if !defined(QMC_BUILD_SANDBOX_ONLY)
if (optimize == "yes")
{
// Setup parameter names
for (int i = 0; i < NumParams; i++)
{
std::stringstream sstr;
sstr << id << "_" << i;
myVars.insert(sstr.str(), (value_type)Parameters[i], true, optimize::LOGLINEAR_P);
}
myVars.print(app_log());
}
else
#endif
{
notOpt = true;
app_log() << "Parameters of BsplineFunctor id:" << id << " are not being optimized.\n";
}
reset();
}
void reportStatus(std::ostream& os)
{
if (notOpt)
return;
myVars.print(os);
}
void checkOutVariables(const opt_variables_type& active)
{
if (notOpt)
return;
myVars.getIndex(active);
}
void checkInVariables(opt_variables_type& active)
{
if (notOpt)
return;
active.insertFrom(myVars);
}
void resetParameters(const opt_variables_type& active)
{
if (notOpt)
return;
for (int i = 0; i < Parameters.size(); ++i)
{
int loc = myVars.where(i);
if (loc >= 0) {
Parameters[i] = std::real( myVars[i] = active[loc] );
}
}
// if (ResetCount++ == 100)
// {
// ResetCount = 0;
// if(ReportLevel) print();
// }
reset();
}
// check if this object has active optimizable parameters
bool isOptimizable()
{
if (notOpt)
return false;
for (int i = 0; i < Parameters.size(); ++i)
{
int loc = myVars.where(i);
if (loc >= 0)
return true;
}
return false;
}
};
template<typename T>
inline T BsplineFunctor<T>::evaluateV(const int iat,
const int iStart,
const int iEnd,
const T* restrict _distArray,
T* restrict distArrayCompressed) const
{
const real_type* restrict distArray = _distArray + iStart;
ASSUME_ALIGNED(distArrayCompressed);
int iCount = 0;
const int iLimit = iEnd - iStart;
#pragma vector always
for (int jat = 0; jat < iLimit; jat++)
{
real_type r = distArray[jat];
// pick the distances smaller than the cutoff and avoid the reference atom
if (r < cutoff_radius && iStart + jat != iat)
distArrayCompressed[iCount++] = distArray[jat];
}
real_type d = 0.0;
#pragma omp simd reduction(+ : d)
for (int jat = 0; jat < iCount; jat++)
{
real_type r = distArrayCompressed[jat];
r *= DeltaRInv;
int i = (int)r;
real_type t = r - real_type(i);
real_type tp0 = t * t * t;
real_type tp1 = t * t;
real_type tp2 = t;
real_type d1 = SplineCoefs[i + 0] * (A[0] * tp0 + A[1] * tp1 + A[2] * tp2 + A[3]);
real_type d2 = SplineCoefs[i + 1] * (A[4] * tp0 + A[5] * tp1 + A[6] * tp2 + A[7]);
real_type d3 = SplineCoefs[i + 2] * (A[8] * tp0 + A[9] * tp1 + A[10] * tp2 + A[11]);
real_type d4 = SplineCoefs[i + 3] * (A[12] * tp0 + A[13] * tp1 + A[14] * tp2 + A[15]);
d += (d1 + d2 + d3 + d4);
}
return d;
}
template<typename T>
inline void BsplineFunctor<T>::evaluateVGL(const int iat,
const int iStart,
const int iEnd,
const T* _distArray,
T* restrict _valArray,
T* restrict _gradArray,
T* restrict _laplArray,
T* restrict distArrayCompressed,
int* restrict distIndices) const
{
real_type dSquareDeltaRinv = DeltaRInv * DeltaRInv;
constexpr real_type cOne(1);
// START_MARK_FIRST();
ASSUME_ALIGNED(distIndices);
ASSUME_ALIGNED(distArrayCompressed);
int iCount = 0;
int iLimit = iEnd - iStart;
const real_type* distArray = _distArray + iStart;
real_type* valArray = _valArray + iStart;
real_type* gradArray = _gradArray + iStart;
real_type* laplArray = _laplArray + iStart;
#pragma vector always
for (int jat = 0; jat < iLimit; jat++)
{
real_type r = distArray[jat];
if (r < cutoff_radius && iStart + jat != iat)
{
distIndices[iCount] = jat;
distArrayCompressed[iCount] = r;
iCount++;
}
}
#pragma omp simd
for (int j = 0; j < iCount; j++)
{
real_type r = distArrayCompressed[j];
int iScatter = distIndices[j];
real_type rinv = cOne / r;
r *= DeltaRInv;
int iGather = (int)r;
real_type t = r - real_type(iGather);
real_type tp0 = t * t * t;
real_type tp1 = t * t;
real_type tp2 = t;
real_type sCoef0 = SplineCoefs[iGather + 0];
real_type sCoef1 = SplineCoefs[iGather + 1];
real_type sCoef2 = SplineCoefs[iGather + 2];
real_type sCoef3 = SplineCoefs[iGather + 3];
laplArray[iScatter] = dSquareDeltaRinv *
(sCoef0 * (d2A[2] * tp2 + d2A[3]) + sCoef1 * (d2A[6] * tp2 + d2A[7]) + sCoef2 * (d2A[10] * tp2 + d2A[11]) +
sCoef3 * (d2A[14] * tp2 + d2A[15]));
gradArray[iScatter] = DeltaRInv * rinv *
(sCoef0 * (dA[1] * tp1 + dA[2] * tp2 + dA[3]) + sCoef1 * (dA[5] * tp1 + dA[6] * tp2 + dA[7]) +
sCoef2 * (dA[9] * tp1 + dA[10] * tp2 + dA[11]) + sCoef3 * (dA[13] * tp1 + dA[14] * tp2 + dA[15]));
valArray[iScatter] = (sCoef0 * (A[0] * tp0 + A[1] * tp1 + A[2] * tp2 + A[3]) +
sCoef1 * (A[4] * tp0 + A[5] * tp1 + A[6] * tp2 + A[7]) +
sCoef2 * (A[8] * tp0 + A[9] * tp1 + A[10] * tp2 + A[11]) +
sCoef3 * (A[12] * tp0 + A[13] * tp1 + A[14] * tp2 + A[15]));
}
}
} // namespace qmcplusplus
#endif
|
adi-parallel-no.c | /**
* adi.c: This file is part of the PolyBench/C 3.2 test suite.
*
* Alternating Direction Implicit solver:
*
* Contact: Louis-Noel Pouchet <pouchet@cse.ohio-state.edu>
* Web address: http://polybench.sourceforge.net
* License: /LICENSE.OSU.txt
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <math.h>
/* Include polybench common header. */
#include <polybench.h>
/* Include benchmark-specific header. */
/* Default data type is double, default size is 10x1024x1024. */
#include "adi.h"
/* Array initialization. */
static void init_array(int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int i;
//int j;
{
int c1;
int c2;
if (n >= 1) {
#pragma omp parallel for private(c2)
for (c1 = 0; c1 <= n + -1; c1++) {
for (c2 = 0; c2 <= n + -1; c2++) {
X[c1][c2] = (((double )c1) * (c2 + 1) + 1) / n;
A[c1][c2] = (((double )c1) * (c2 + 2) + 2) / n;
B[c1][c2] = (((double )c1) * (c2 + 3) + 3) / n;
}
}
}
}
}
/* DCE code. Must scan the entire live-out data.
Can be used also to check the correctness of the output. */
static void print_array(int n,double X[500 + 0][500 + 0])
{
int i;
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
fprintf(stderr,"%0.2lf ",X[i][j]);
if ((i * 500 + j) % 20 == 0)
fprintf(stderr,"\n");
}
fprintf(stderr,"\n");
}
/* Main computational kernel. The whole function will be timed,
including the call and return. */
static void kernel_adi(int tsteps,int n,double X[500 + 0][500 + 0],double A[500 + 0][500 + 0],double B[500 + 0][500 + 0])
{
//int t;
//int i1;
//int i2;
//#pragma scop
{
int c0;
int c2;
int c8;
for (c0 = 0; c0 <= 9; c0++) {
#pragma omp parallel for private(c8)
for (c2 = 0; c2 <= 499; c2++) {
for (c8 = 1; c8 <= 499; c8++) {
B[c2][c8] = B[c2][c8] - A[c2][c8] * A[c2][c8] / B[c2][c8 - 1];
}
for (c8 = 1; c8 <= 499; c8++) {
X[c2][c8] = X[c2][c8] - X[c2][c8 - 1] * A[c2][c8] / B[c2][c8 - 1];
}
for (c8 = 0; c8 <= 497; c8++) {
X[c2][500 - c8 - 2] = (X[c2][500 - 2 - c8] - X[c2][500 - 2 - c8 - 1] * A[c2][500 - c8 - 3]) / B[c2][500 - 3 - c8];
}
}
#pragma omp parallel for
for (c2 = 0; c2 <= 499; c2++) {
X[c2][500 - 1] = X[c2][500 - 1] / B[c2][500 - 1];
}
#pragma omp parallel for private(c8)
for (c2 = 0; c2 <= 499; c2++) {
for (c8 = 1; c8 <= 499; c8++) {
B[c8][c2] = B[c8][c2] - A[c8][c2] * A[c8][c2] / B[c8 - 1][c2];
}
for (c8 = 1; c8 <= 499; c8++) {
X[c8][c2] = X[c8][c2] - X[c8 - 1][c2] * A[c8][c2] / B[c8 - 1][c2];
}
for (c8 = 0; c8 <= 497; c8++) {
X[500 - 2 - c8][c2] = (X[500 - 2 - c8][c2] - X[500 - c8 - 3][c2] * A[500 - 3 - c8][c2]) / B[500 - 2 - c8][c2];
}
}
#pragma omp parallel for
for (c2 = 0; c2 <= 499; c2++) {
X[500 - 1][c2] = X[500 - 1][c2] / B[500 - 1][c2];
}
}
}
//#pragma endscop
}
int main(int argc,char **argv)
{
/* Retrieve problem size. */
int n = 500;
int tsteps = 10;
/* Variable declaration/allocation. */
double (*X)[500 + 0][500 + 0];
X = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*A)[500 + 0][500 + 0];
A = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
double (*B)[500 + 0][500 + 0];
B = ((double (*)[500 + 0][500 + 0])(polybench_alloc_data(((500 + 0) * (500 + 0)),(sizeof(double )))));
;
/* Initialize array(s). */
init_array(n, *X, *A, *B);
/* Start timer. */
polybench_timer_start();
;
/* Run kernel. */
kernel_adi(tsteps,n, *X, *A, *B);
/* Stop and print timer. */
polybench_timer_stop();
;
polybench_timer_print();
;
/* Prevent dead-code elimination. All live-out data must be printed
by the function call in argument. */
if (argc > 42 && !strcmp(argv[0],""))
print_array(n, *X);
/* Be clean. */
free(((void *)X));
;
free(((void *)A));
;
free(((void *)B));
;
return 0;
}
|
GB_AxB_dot3.c | //------------------------------------------------------------------------------
// GB_AxB_dot3: compute C<M> = A'*B in parallel
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved.
// http://suitesparse.com See GraphBLAS/Doc/License.txt for license.
//------------------------------------------------------------------------------
// This function only computes C<M>=A'*B. The mask must be present, and not
// complemented. The mask is always applied.
#include "GB_mxm.h"
#ifndef GBCOMPACT
#include "GB_AxB__include.h"
#endif
#define GB_FREE_WORK \
{ \
GB_FREE_MEMORY (TaskList, max_ntasks+1, sizeof (GB_task_struct)) ; \
}
#define GB_FREE_ALL \
{ \
GB_FREE_WORK ; \
GrB_free (Chandle) ; \
}
GrB_Info GB_AxB_dot3 // C<M> = A'*B using dot product method
(
GrB_Matrix *Chandle, // output matrix
const GrB_Matrix M, // mask matrix
const GrB_Matrix A, // input matrix
const GrB_Matrix B, // input matrix
const GrB_Semiring semiring, // semiring that defines C=A*B
const bool flipxy, // if true, do z=fmult(b,a) vs fmult(a,b)
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
ASSERT (Chandle != NULL) ;
ASSERT (*Chandle == NULL) ;
ASSERT_OK (GB_check (M, "M for dot3 A'*B", GB0)) ;
ASSERT_OK (GB_check (A, "A for dot3 A'*B", GB0)) ;
ASSERT_OK (GB_check (B, "B for dot3 A'*B", GB0)) ;
ASSERT (!GB_PENDING (M)) ; ASSERT (!GB_ZOMBIES (M)) ;
ASSERT (!GB_PENDING (A)) ; ASSERT (!GB_ZOMBIES (A)) ;
ASSERT (!GB_PENDING (B)) ; ASSERT (!GB_ZOMBIES (B)) ;
ASSERT_OK (GB_check (semiring, "semiring for numeric A'*B", GB0)) ;
ASSERT (A->vlen == B->vlen) ;
int ntasks, max_ntasks = 0, nthreads ;
GB_task_struct *TaskList = NULL ;
//--------------------------------------------------------------------------
// get the semiring operators
//--------------------------------------------------------------------------
GrB_BinaryOp mult = semiring->multiply ;
GrB_Monoid add = semiring->add ;
ASSERT (mult->ztype == add->op->ztype) ;
bool op_is_first = mult->opcode == GB_FIRST_opcode ;
bool op_is_second = mult->opcode == GB_SECOND_opcode ;
bool A_is_pattern = false ;
bool B_is_pattern = false ;
if (flipxy)
{
// z = fmult (b,a) will be computed
A_is_pattern = op_is_first ;
B_is_pattern = op_is_second ;
ASSERT (GB_IMPLIES (!A_is_pattern,
GB_Type_compatible (A->type, mult->ytype))) ;
ASSERT (GB_IMPLIES (!B_is_pattern,
GB_Type_compatible (B->type, mult->xtype))) ;
}
else
{
// z = fmult (a,b) will be computed
A_is_pattern = op_is_second ;
B_is_pattern = op_is_first ;
ASSERT (GB_IMPLIES (!A_is_pattern,
GB_Type_compatible (A->type, mult->xtype))) ;
ASSERT (GB_IMPLIES (!B_is_pattern,
GB_Type_compatible (B->type, mult->ytype))) ;
}
(*Chandle) = NULL ;
//--------------------------------------------------------------------------
// get M, A, and B
//--------------------------------------------------------------------------
const int64_t *restrict Mp = M->p ;
const int64_t *restrict Mh = M->h ;
const int64_t *restrict Mi = M->i ;
const GB_void *restrict Mx = M->x ;
const size_t msize = M->type->size ;
const int64_t mvlen = M->vlen ;
const int64_t mvdim = M->vdim ;
const int64_t mnz = GB_NNZ (M) ;
const int64_t mnvec = M->nvec ;
const bool M_is_hyper = M->is_hyper ;
GB_cast_function cast_M = GB_cast_factory (GB_BOOL_code, M->type->code) ;
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
// const int64_t *restrict Ai = A->i ;
// const int64_t avlen = A->vlen ;
// const int64_t avdim = A->vdim ;
// const int64_t anz = GB_NNZ (A) ;
const int64_t anvec = A->nvec ;
const bool A_is_hyper = A->is_hyper ;
const int64_t *restrict Bp = B->p ;
const int64_t *restrict Bh = B->h ;
// const int64_t *restrict Bi = B->i ;
// const int64_t bvlen = B->vlen ;
// const int64_t bvdim = B->vdim ;
// const int64_t bnz = GB_NNZ (B) ;
const int64_t bnvec = B->nvec ;
const bool B_is_hyper = B->is_hyper ;
//--------------------------------------------------------------------------
// allocate C, the same size and # of entries as M
//--------------------------------------------------------------------------
GrB_Type ctype = add->op->ztype ;
int64_t cvlen = mvlen ;
int64_t cvdim = mvdim ;
int64_t cnz = mnz ;
int64_t cnvec = mnvec ;
GB_CREATE (Chandle, ctype, cvlen, cvdim, GB_Ap_malloc, true,
GB_SAME_HYPER_AS (M_is_hyper), M->hyper_ratio, cnvec,
cnz+1, // add one to cnz for GB_cumsum
true, Context) ;
if (info != GrB_SUCCESS)
{
// out of memory
GB_FREE_ALL ;
return (info) ;
}
GrB_Matrix C = (*Chandle) ;
int64_t *restrict Cp = C->p ;
int64_t *restrict Ch = C->h ;
int64_t *restrict Cwork = C->i ; // use C->i as workspace
// printf ("Ch is %p\n", (void *) Ch) ;
//--------------------------------------------------------------------------
// determine the # of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
//--------------------------------------------------------------------------
// copy Mp and Mh into C
//--------------------------------------------------------------------------
// FUTURE:: C->p and C->h could be shallow copies of M->p and M->h, which
// could same some time and memory if C is then, say, transposed by
// GB_accum_mask later on.
nthreads = GB_nthreads (cnvec, chunk, nthreads_max) ;
GB_memcpy (Cp, Mp, (cnvec+1) * sizeof (int64_t), nthreads) ;
if (M_is_hyper)
{
GB_memcpy (Ch, Mh, cnvec * sizeof (int64_t), nthreads) ;
}
C->magic = GB_MAGIC ;
C->nvec_nonempty = M->nvec_nonempty ;
C->nvec = M->nvec ;
//--------------------------------------------------------------------------
// construct the tasks for the first phase
//--------------------------------------------------------------------------
nthreads = GB_nthreads (cnz, chunk, nthreads_max) ;
GB_OK (GB_AxB_dot3_one_slice (&TaskList, &max_ntasks, &ntasks, &nthreads,
M, Context)) ;
//--------------------------------------------------------------------------
// phase1: estimate the work to compute each entry in C
//--------------------------------------------------------------------------
// The work to compute C(i,j) is held in Cwork [p], if C(i,j) appears in
// as the pth entry in C.
#pragma omp parallel for num_threads(nthreads) schedule(dynamic,1)
for (int taskid = 0 ; taskid < ntasks ; taskid++)
{
//----------------------------------------------------------------------
// get the task descriptor
//----------------------------------------------------------------------
// GB_GET_TASK_DESCRIPTOR ;
int64_t kfirst = TaskList [taskid].kfirst ;
int64_t klast = TaskList [taskid].klast ;
bool fine_task = (klast == -1) ;
if (fine_task)
{
// a fine task operates on a slice of a single vector
klast = kfirst ;
}
int64_t bpleft = 0 ;
//----------------------------------------------------------------------
// compute all vectors in this task
//----------------------------------------------------------------------
for (int64_t k = kfirst ; k <= klast ; k++)
{
//------------------------------------------------------------------
// get j, the kth vector of C and M
//------------------------------------------------------------------
int64_t j = (Mh == NULL) ? k : Mh [k] ;
GB_GET_VECTOR (pM, pM_end, pM, pM_end, Mp, k) ;
//------------------------------------------------------------------
// get B(:,j)
//------------------------------------------------------------------
int64_t pB, pB_end ;
GB_lookup (B_is_hyper, Bh, Bp, &bpleft, bnvec-1, j, &pB, &pB_end) ;
int64_t bjnz = pB_end - pB ;
//------------------------------------------------------------------
// estimate the work to compute each entry of C(:,j)
//------------------------------------------------------------------
// A decent estimate of the work to compute the dot product C(i,j)
// = A(:,i)'*B(:,j) is min (|A(:,i)|, |B(:,j)|) + 1. This is a
// lower bound. The actual work could require a binary search of
// either A(:,i) or B(:,j), or a merge of the two vectors. Or it
// could require no work at all if all entries in A(:,i) appear
// before all entries in B(:,j), or visa versa. No work is done if
// M(i,j)=0. A more accurate estimate is possible to compute,
// following the different methods used in
// Template/GB_AxB_dot_cij.c.
if (bjnz == 0)
{
// B(:,j) is empty, so C(:,j) is empty as well. No work is to
// be done, but it still takes unit work to flag each C(:,j) as
// a zombie
for ( ; pM < pM_end ; pM++)
{
Cwork [pM] = 1 ;
}
}
else
{
int64_t apleft = 0 ;
for ( ; pM < pM_end ; pM++)
{
int64_t work = 1 ;
bool mij ;
cast_M (&mij, Mx +(pM*msize), 0) ;
if (mij)
{
int64_t pA, pA_end, i = Mi [pM] ;
GB_lookup (A_is_hyper, Ah, Ap, &apleft, anvec-1, i,
&pA, &pA_end) ;
int64_t ajnz = pA_end - pA ;
work += GB_IMIN (ajnz, bjnz) ;
}
Cwork [pM] = work ;
}
}
}
}
//--------------------------------------------------------------------------
// free the current tasks and construct the tasks for the second phase
//--------------------------------------------------------------------------
GB_FREE_MEMORY (TaskList, max_ntasks+1, sizeof (GB_task_struct)) ;
GB_OK (GB_AxB_dot3_slice (&TaskList, &max_ntasks, &ntasks, &nthreads,
C, Context)) ;
// if (ntasks > 1) printf ("ntasks %d\n", ntasks) ;
//--------------------------------------------------------------------------
// C<M> = A'*B, via masked dot product method and built-in semiring
//--------------------------------------------------------------------------
bool done = false ;
#ifndef GBCOMPACT
//--------------------------------------------------------------------------
// define the worker for the switch factory
//--------------------------------------------------------------------------
#define GB_Adot3B(add,mult,xyname) GB_Adot3B_ ## add ## mult ## xyname
#define GB_AxB_WORKER(add,mult,xyname) \
{ \
info = GB_Adot3B (add,mult,xyname) (C, M, \
A, A_is_pattern, B, B_is_pattern, \
TaskList, ntasks, nthreads) ; \
done = (info != GrB_NO_VALUE) ; \
} \
break ;
//--------------------------------------------------------------------------
// launch the switch factory
//--------------------------------------------------------------------------
GB_Opcode mult_opcode, add_opcode ;
GB_Type_code xycode, zcode ;
if (GB_AxB_semiring_builtin (A, A_is_pattern, B, B_is_pattern, semiring,
flipxy, &mult_opcode, &add_opcode, &xycode, &zcode))
{
#include "GB_AxB_factory.c"
}
#endif
//--------------------------------------------------------------------------
// user semirings created at compile time
//--------------------------------------------------------------------------
if (semiring->object_kind == GB_USER_COMPILED)
{
// determine the required type of A and B for the user semiring
GrB_Type atype_required, btype_required ;
if (flipxy)
{
// A is passed as y, and B as x, in z = mult(x,y)
atype_required = mult->ytype ;
btype_required = mult->xtype ;
}
else
{
// A is passed as x, and B as y, in z = mult(x,y)
atype_required = mult->xtype ;
btype_required = mult->ytype ;
}
if (A->type == atype_required && B->type == btype_required)
{
info = GB_AxB_user (GxB_AxB_DOT, semiring, Chandle, M, A, B,
flipxy,
/* heap: */ NULL, NULL, NULL, 0,
/* Gustavson: */ NULL,
/* dot2: */ NULL, NULL, nthreads, 0, 0, NULL,
/* dot3: */ TaskList, ntasks) ;
done = true ;
}
}
//--------------------------------------------------------------------------
// C<M> = A'*B, via masked dot product method and typecasting
//--------------------------------------------------------------------------
if (!done)
{
//----------------------------------------------------------------------
// get operators, functions, workspace, contents of A, B, C, and M
//----------------------------------------------------------------------
GxB_binary_function fmult = mult->function ;
GxB_binary_function fadd = add->op->function ;
size_t csize = C->type->size ;
size_t asize = A_is_pattern ? 0 : A->type->size ;
size_t bsize = B_is_pattern ? 0 : B->type->size ;
size_t xsize = mult->xtype->size ;
size_t ysize = mult->ytype->size ;
// scalar workspace: because of typecasting, the x/y types need not
// be the same as the size of the A and B types.
// flipxy false: aki = (xtype) A(k,i) and bkj = (ytype) B(k,j)
// flipxy true: aki = (ytype) A(k,i) and bkj = (xtype) B(k,j)
size_t aki_size = flipxy ? ysize : xsize ;
size_t bkj_size = flipxy ? xsize : ysize ;
// GB_void *restrict identity = add->identity ;
GB_void *restrict terminal = add->terminal ;
GB_cast_function cast_A, cast_B ;
if (flipxy)
{
// A is typecasted to y, and B is typecasted to x
cast_A = A_is_pattern ? NULL :
GB_cast_factory (mult->ytype->code, A->type->code) ;
cast_B = B_is_pattern ? NULL :
GB_cast_factory (mult->xtype->code, B->type->code) ;
}
else
{
// A is typecasted to x, and B is typecasted to y
cast_A = A_is_pattern ? NULL :
GB_cast_factory (mult->xtype->code, A->type->code) ;
cast_B = B_is_pattern ? NULL :
GB_cast_factory (mult->ytype->code, B->type->code) ;
}
//----------------------------------------------------------------------
// C<M> = A'*B via dot products, function pointers, and typecasting
//----------------------------------------------------------------------
// aki = A(k,i), located in Ax [pA]
#define GB_GETA(aki,Ax,pA) \
GB_void aki [GB_PGI(aki_size)] ; \
if (!A_is_pattern) cast_A (aki, Ax +((pA)*asize), asize) ;
// bkj = B(k,j), located in Bx [pB]
#define GB_GETB(bkj,Bx,pB) \
GB_void bkj [GB_PGI(bkj_size)] ; \
if (!B_is_pattern) cast_B (bkj, Bx +((pB)*bsize), bsize) ;
// break if cij reaches the terminal value
#define GB_DOT_TERMINAL(cij) \
if (terminal != NULL && memcmp (cij, terminal, csize) == 0) \
{ \
break ; \
}
// C(i,j) = A(i,k) * B(k,j)
#define GB_MULT(cij, aki, bkj) \
GB_MULTIPLY (cij, aki, bkj) ; \
// C(i,j) += A(i,k) * B(k,j)
#define GB_MULTADD(cij, aki, bkj) \
GB_void zwork [GB_PGI(csize)] ; \
GB_MULTIPLY (zwork, aki, bkj) ; \
fadd (cij, cij, zwork) ;
// define cij for each task
#define GB_CIJ_DECLARE(cij) \
GB_void cij [GB_PGI(csize)] ;
// address of Cx [p]
#define GB_CX(p) Cx +((p)*csize)
// save the value of C(i,j)
#define GB_CIJ_SAVE(cij,p) \
memcpy (GB_CX (p), cij, csize) ;
#define GB_ATYPE GB_void
#define GB_BTYPE GB_void
#define GB_CTYPE GB_void
// loops with function pointers cannot be vectorized
#define GB_DOT_SIMD ;
if (flipxy)
{
#define GB_MULTIPLY(z,x,y) fmult (z,y,x)
#include "GB_AxB_dot3_template.c"
#undef GB_MULTIPLY
}
else
{
#define GB_MULTIPLY(z,x,y) fmult (z,x,y)
#include "GB_AxB_dot3_template.c"
#undef GB_MULTIPLY
}
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
if (C->nzombies > 0)
{
// C has been created with zombies, so place it in the queue
GB_CRITICAL (GB_queue_insert (C)) ;
}
GB_FREE_WORK ;
ASSERT_OK (GB_check (C, "dot3: C<M> = A'*B output", GB0)) ;
ASSERT (*Chandle == C) ;
ASSERT (GB_ZOMBIES_OK (C)) ;
ASSERT (!GB_PENDING (C)) ;
return (GrB_SUCCESS) ;
}
|
tester.c | #include <stdio.h>
#include <stdlib.h>
#include <omp.h>
/* The following is included as a reference user-space implementation */
//**********************************************************
// Parallel Pseudo random number generator:
//
// USAGE:
//
// The pseudo random sequence is seeded with a range
//
// void seed(lower_limit, higher_limit)
//
// and then subsequent calls to the random number generator
// generates values in the sequence:
//
// double random()
//
// A leap frog method is used to assure non-overlapping
// sequences for each thread.
//
// Note: these functions are to be called from inside the
// the OpenMP parallel region that will use the sequence.
//
// BACKGROUND:
//
// We are using a modulus of 2^31-1 and a multiplier from
// the Hoaglin LCGs in the following article:
//
// http://random.mat.sbg.ac.at/~charly/server/node3.html#lcg
//
// we are using a zero addend just to make the leap frog
// algorithm easier to implement.
//
// HISTORY:
//
// 9/2008: Written by Tim Mattson by cutting and pasting
// from a generator written by Larry Meadows
//
//***********************************************************
static unsigned long long MULTIPLIER = 764261123;
static unsigned long long PMOD = 2147483647;
static unsigned long long mult_n;
double random_low, random_hi;
#define MAX_THREADS 128
static unsigned long long pseed[MAX_THREADS][4]; //[4] to padd to cache line
//size to avoid false sharing
unsigned long long random_last = 0;
#pragma omp threadprivate(random_last)
double myrandom()
{
unsigned long long random_next;
double ret_val;
FILE *fp;
fp = fopen("/proc/lfprng", "r");
char ch = fgetc(fp);
//
// compute an integer random number from zero to mod
//
random_next = (unsigned long long)((mult_n * random_last)% PMOD);
random_last = random_next;
//
// shift into preset range
//
ret_val = ((double)random_next/(double)PMOD)*(random_hi-random_low)+random_low;
return ret_val;
}
//
// set the seed, the multiplier and the range
//
void seed(unsigned long long iseed, double low_in, double hi_in)
{
int i, id, nthreads;
id = omp_get_thread_num();
#pragma omp single
{
if(low_in < hi_in)
{
random_low = low_in;
random_hi = hi_in;
}
else
{
random_low = hi_in;
random_hi = low_in;
}
//
// The Leapfrog method ... adjust the multiplier so you stride through
// the sequence by increments of "nthreads" and adust seeds so each
// thread starts with the right offset
//
nthreads = omp_get_num_threads();
if ( iseed == 0 )
iseed = PMOD/MULTIPLIER; // just pick a reasonable seed
pseed[0][0] = iseed;
mult_n = MULTIPLIER;
for (i = 1; i < nthreads; ++i)
{
iseed = (unsigned long long)((MULTIPLIER * iseed) % PMOD);
pseed[i][0] = iseed;
mult_n = (mult_n * MULTIPLIER) % PMOD;
}
}
random_last = (unsigned long long) pseed[id][0];
}
/* This ends the reference openMP implementation. The following is the core testing loop. */
int tests[6]={2,3,4,5,6,10};
int main(int argc, char **argv) {
double baseref[120];
double testref[120];
unsigned long long myseed = 123456789, setseed;
int i, j;
setseed=myseed;
seed(setseed, 0.0, 1.1);
for (i=0; i<120; i++) {
baseref[i] = myrandom();
}
for (j=0; j<6; j++) {
int numthreads = tests[j];
double sum;
omp_set_num_threads(numthreads);
sum = 0;
#pragma omp parallel reduction(+:sum)
{
setseed=myseed;
seed(setseed,0.0,1.0);
#pragma omp for
for (i=0; i<120; i++) {
sum += abs(myrandom() - baseref[i]);
}
}
printf(" Diff for %i threads is %f.\n", numthreads, sum);
}
printf("\n");
}
|
3dMath.h | /* Public Domain / CC0 C99 Vector Math Library
*/
#ifndef CHAD_MATH_H
#define CHAD_MATH_H
/* Default behavior- compatibility.
*/
#ifndef CHAD_MATH_NO_ALIGN
#define CHAD_MATH_NO_ALIGN
#endif
#ifdef __TINYC__
#define CHAD_MATH_NO_ALIGN
#endif
#ifndef CHAD_MATH_NO_ALIGN
#include <stdalign.h>
#define CHAD_ALIGN alignas(16)
#warning "Chad math library compiling with alignas of 16, malloc and realloc MUST return 16-byte-aligned pointers."
#else
#define CHAD_ALIGN /*a comment*/
#endif
#include <math.h>
#include <string.h>
typedef float f_;
typedef unsigned int uint;
#define MAX(x,y) (x>y?x:y)
#define MIN(x,y) (x<y?x:y)
typedef struct {CHAD_ALIGN f_ d[3];} vec3;
typedef struct {CHAD_ALIGN int d[3];} ivec3;
typedef struct {CHAD_ALIGN f_ d[4];} vec4;
typedef struct {CHAD_ALIGN f_ d[16];} mat4;
/*Collision detection
These Algorithms return the penetration vector into
the shape in the first argument
With depth of penetration in element 4
if depth of penetration is zero or lower then there is no penetration.
*/
typedef struct{
vec4 c;
vec3 e;
}aabb;
typedef aabb colshape; /*c.d[3] determines if it's a sphere or box. 0 or less = box, greater than 0 = sphere*/
static inline mat4 scalemat4( vec4 s){
mat4 ret;
for(int i = 1; i < 16; i++)
ret.d[i]= 0.0;
ret.d[0*4 + 0] = s.d[0];
ret.d[1*4 + 1] = s.d[1];
ret.d[2*4 + 2] = s.d[2];
ret.d[3*4 + 3] = s.d[3];
return ret;
}
static inline int invmat4( mat4 m, mat4* invOut) /*returns 1 if successful*/
{
mat4 inv;
f_ det;
int i;
inv.d[0] = m.d[5] * m.d[10] * m.d[15] -
m.d[5] * m.d[11] * m.d[14] -
m.d[9] * m.d[6] * m.d[15] +
m.d[9] * m.d[7] * m.d[14] +
m.d[13] * m.d[6] * m.d[11] -
m.d[13] * m.d[7] * m.d[10];
inv.d[4] = -m.d[4] * m.d[10] * m.d[15] +
m.d[4] * m.d[11] * m.d[14] +
m.d[8] * m.d[6] * m.d[15] -
m.d[8] * m.d[7] * m.d[14] -
m.d[12] * m.d[6] * m.d[11] +
m.d[12] * m.d[7] * m.d[10];
inv.d[8] = m.d[4] * m.d[9] * m.d[15] -
m.d[4] * m.d[11] * m.d[13] -
m.d[8] * m.d[5] * m.d[15] +
m.d[8] * m.d[7] * m.d[13] +
m.d[12] * m.d[5] * m.d[11] -
m.d[12] * m.d[7] * m.d[9];
inv.d[12] = -m.d[4] * m.d[9] * m.d[14] +
m.d[4] * m.d[10] * m.d[13] +
m.d[8] * m.d[5] * m.d[14] -
m.d[8] * m.d[6] * m.d[13] -
m.d[12] * m.d[5] * m.d[10] +
m.d[12] * m.d[6] * m.d[9];
inv.d[1] = -m.d[1] * m.d[10] * m.d[15] +
m.d[1] * m.d[11] * m.d[14] +
m.d[9] * m.d[2] * m.d[15] -
m.d[9] * m.d[3] * m.d[14] -
m.d[13] * m.d[2] * m.d[11] +
m.d[13] * m.d[3] * m.d[10];
inv.d[5] = m.d[0] * m.d[10] * m.d[15] -
m.d[0] * m.d[11] * m.d[14] -
m.d[8] * m.d[2] * m.d[15] +
m.d[8] * m.d[3] * m.d[14] +
m.d[12] * m.d[2] * m.d[11] -
m.d[12] * m.d[3] * m.d[10];
inv.d[9] = -m.d[0] * m.d[9] * m.d[15] +
m.d[0] * m.d[11] * m.d[13] +
m.d[8] * m.d[1] * m.d[15] -
m.d[8] * m.d[3] * m.d[13] -
m.d[12] * m.d[1] * m.d[11] +
m.d[12] * m.d[3] * m.d[9];
inv.d[13] = m.d[0] * m.d[9] * m.d[14] -
m.d[0] * m.d[10] * m.d[13] -
m.d[8] * m.d[1] * m.d[14] +
m.d[8] * m.d[2] * m.d[13] +
m.d[12] * m.d[1] * m.d[10] -
m.d[12] * m.d[2] * m.d[9];
inv.d[2] = m.d[1] * m.d[6] * m.d[15] -
m.d[1] * m.d[7] * m.d[14] -
m.d[5] * m.d[2] * m.d[15] +
m.d[5] * m.d[3] * m.d[14] +
m.d[13] * m.d[2] * m.d[7] -
m.d[13] * m.d[3] * m.d[6];
inv.d[6] = -m.d[0] * m.d[6] * m.d[15] +
m.d[0] * m.d[7] * m.d[14] +
m.d[4] * m.d[2] * m.d[15] -
m.d[4] * m.d[3] * m.d[14] -
m.d[12] * m.d[2] * m.d[7] +
m.d[12] * m.d[3] * m.d[6];
inv.d[10] = m.d[0] * m.d[5] * m.d[15] -
m.d[0] * m.d[7] * m.d[13] -
m.d[4] * m.d[1] * m.d[15] +
m.d[4] * m.d[3] * m.d[13] +
m.d[12] * m.d[1] * m.d[7] -
m.d[12] * m.d[3] * m.d[5];
inv.d[14] = -m.d[0] * m.d[5] * m.d[14] +
m.d[0] * m.d[6] * m.d[13] +
m.d[4] * m.d[1] * m.d[14] -
m.d[4] * m.d[2] * m.d[13] -
m.d[12] * m.d[1] * m.d[6] +
m.d[12] * m.d[2] * m.d[5];
inv.d[3] = -m.d[1] * m.d[6] * m.d[11] +
m.d[1] * m.d[7] * m.d[10] +
m.d[5] * m.d[2] * m.d[11] -
m.d[5] * m.d[3] * m.d[10] -
m.d[9] * m.d[2] * m.d[7] +
m.d[9] * m.d[3] * m.d[6];
inv.d[7] = m.d[0] * m.d[6] * m.d[11] -
m.d[0] * m.d[7] * m.d[10] -
m.d[4] * m.d[2] * m.d[11] +
m.d[4] * m.d[3] * m.d[10] +
m.d[8] * m.d[2] * m.d[7] -
m.d[8] * m.d[3] * m.d[6];
inv.d[11] = -m.d[0] * m.d[5] * m.d[11] +
m.d[0] * m.d[7] * m.d[9] +
m.d[4] * m.d[1] * m.d[11] -
m.d[4] * m.d[3] * m.d[9] -
m.d[8] * m.d[1] * m.d[7] +
m.d[8] * m.d[3] * m.d[5];
inv.d[15] = m.d[0] * m.d[5] * m.d[10] -
m.d[0] * m.d[6] * m.d[9] -
m.d[4] * m.d[1] * m.d[10] +
m.d[4] * m.d[2] * m.d[9] +
m.d[8] * m.d[1] * m.d[6] -
m.d[8] * m.d[2] * m.d[5];
det = m.d[0] * inv.d[0] + m.d[1] * inv.d[4] + m.d[2] * inv.d[8] + m.d[3] * inv.d[12];
if (det == 0)
return 0;
det = 1.0 / det;
for (i = 0; i < 16; i++)
invOut->d[i] = inv.d[i] * det;
return 1;
}
static inline mat4 perspective( f_ fov, f_ aspect, f_ near, f_ far){
mat4 ret;
f_ D2R = 3.14159265358979323 / 180.0;
f_ yScale = 1.0/tanf(D2R * fov/2);
f_ xScale = yScale/aspect;
f_ nearmfar = near-far;
ret.d[0*4+0] = xScale; ret.d[0*4+1]=0; ret.d[0*4+2]=0; ret.d[0*4+3]=0;
ret.d[1*4+0]=0; ret.d[1*4+1]=yScale;ret.d[1*4+2]=0; ret.d[1*4+3]=0;
ret.d[2*4+0]=0; ret.d[2*4+1]=0; ret.d[2*4+2]=(far+near)/nearmfar;ret.d[2*4+3]=-1;
ret.d[3*4+0]=0; ret.d[3*4+1]=0; ret.d[3*4+2]=2*far*near/nearmfar;ret.d[3*4+3]=0;
/*
ret.d[0*4+0] = xScale; ret.d[0*4+1]=0; ret.d[0*4+2]=0; ret.d[0*4+3]=0;
ret.d[1*4+0]=0; ret.d[1*4+1]=yScale;ret.d[1*4+2]=0; ret.d[1*4+3]=0;
ret.d[2*4+0]=0; ret.d[2*4+1]=0; ret.d[2*4+2]=(far+near)/nearmfar; ret.d[2*4+3]=2*far*near/nearmfar;
ret.d[3*4+0]=0; ret.d[3*4+1]=0; ret.d[3*4+2]=-1; ret.d[3*4+3]=0;
*/
return ret;
}
static inline vec3 viewport( uint xdim, uint ydim, vec3 input){
input.d[0] += 1;
input.d[1] += 1;
input.d[0] *= (f_)xdim / 2.0;
input.d[1] *= (f_)ydim / 2.0;
input.d[2] = (input.d[2])/2.0;
return input;
}
static inline mat4 rotate( vec3 rotation){
f_ a = rotation.d[0];
f_ b = rotation.d[1];
f_ c = rotation.d[2];
mat4 rm;
rm.d[0*4 + 0] = cosf(a)*cosf(b);
rm.d[1*4 + 0] = sinf(a)*cosf(b);
rm.d[2*4 + 0] = -sinf(b);
rm.d[0*4 + 1] = cosf(a)*sinf(b)*sinf(c)-sinf(a)*cosf(c);
rm.d[1*4 + 1] = sinf(a)*sinf(b)*sinf(c)+cosf(a)*cosf(c);
rm.d[2*4 + 1] = cosf(b)*sinf(c);
rm.d[0*4 + 2] = cosf(a)*sinf(b)*cosf(c)+sinf(a)*sinf(c);
rm.d[1*4 + 2] = sinf(a)*sinf(b)*cosf(c)-cosf(a)*sinf(c);
rm.d[2*4 + 2] = cosf(b)*cosf(c);
rm.d[0*4 + 3] = 0;
rm.d[1*4 + 3] = 0;
rm.d[2*4 + 3] = 0;
rm.d[3*4 + 3] = 1; /*the bottom right corner of the matrix.*/
rm.d[3*4 + 0] = 0;
rm.d[3*4 + 1] = 0;
rm.d[3*4 + 2] = 0;
return rm;
}
static inline f_ clampf( f_ a, f_ min, f_ max){
if(a<min) return min;
if(a>max) return max;
return a;
}
static inline f_ lengthv3( vec3 a){
return sqrtf(a.d[0] * a.d[0] + a.d[1] * a.d[1] + a.d[2] * a.d[2]);
}
static inline f_ lengthv4( vec4 a){
return sqrtf(a.d[0] * a.d[0] + a.d[1] * a.d[1] + a.d[2] * a.d[2] + a.d[3] * a.d[3]);
}
static inline vec3 multvec3( vec3 a, vec3 b){
return (vec3){
.d[0]=a.d[0]*b.d[0],
.d[1]=a.d[1]*b.d[1],
.d[2]=a.d[2]*b.d[2]
};
}
static inline vec4 multvec4( vec4 a, vec4 b){
return (vec4){
.d[0]=a.d[0]*b.d[0],
.d[1]=a.d[1]*b.d[1],
.d[2]=a.d[2]*b.d[2],
.d[3]=a.d[3]*b.d[3]
};
}
static inline vec3 clampvec3( vec3 a, vec3 min, vec3 max){
vec3 ret;
ret.d[0] = clampf(a.d[0],min.d[0],max.d[0]);
ret.d[1] = clampf(a.d[1],min.d[1],max.d[1]);
ret.d[2] = clampf(a.d[2],min.d[2],max.d[2]);
return ret;
}
static inline vec4 clampvec4( vec4 a, vec4 min, vec4 max){
vec4 ret;
ret.d[0] = clampf(a.d[0],min.d[0],max.d[0]);
ret.d[1] = clampf(a.d[1],min.d[1],max.d[1]);
ret.d[2] = clampf(a.d[2],min.d[2],max.d[2]);
ret.d[3] = clampf(a.d[3],min.d[3],max.d[3]);
return ret;
}
static inline f_ dotv3( vec3 a, vec3 b){
return a.d[0] * b.d[0] + a.d[1] * b.d[1] + a.d[2] * b.d[2];
}
static inline f_ dotv4( vec4 a, vec4 b){
return a.d[0] * b.d[0] + a.d[1] * b.d[1] + a.d[2] * b.d[2] + a.d[3] * b.d[3];
}
static inline vec4 getrow( mat4 a, uint index){
return (vec4){
.d[0]=a.d[index],
.d[1]=a.d[4+index],
.d[2]=a.d[8+index],
.d[3]=a.d[12+index]
};
}
static inline mat4 swapRowColumnMajor( mat4 in){
mat4 result;
vec4 t;
int i = 0;
t = getrow(in,i);
memcpy(result.d+i*4, t.d, 4*4);i++;
t = getrow(in,i);
memcpy(result.d+i*4, t.d, 4*4);i++;
t = getrow(in,i);
memcpy(result.d+i*4, t.d, 4*4);i++;
t = getrow(in,i);
memcpy(result.d+i*4, t.d, 4*4);
return result;
}
static inline vec4 getcol( mat4 a, uint index){
return (vec4){
.d[0]=a.d[index*4],
.d[1]=a.d[index*4+1],
.d[2]=a.d[index*4+2],
.d[3]=a.d[index*4+3]
};
}
static inline mat4 multm4( mat4 a, mat4 b){
mat4 ret;
#ifdef _OPENMP
#pragma omp simd
#endif
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
ret.d[i*4 + j] = dotv4( /*j is the ROW of the target, i is the COLUMN.*/
getrow(a, j), /*we retrieve the same ROW as our ROW INDEX.*/
getcol(b, i) /*we retrieve the same COLUMN as our COLUMN INDEX.*/
);
return ret;
}
static inline vec4 mat4xvec4( mat4 t, vec4 v){
vec4 vr;
/*
Getting a ROW of the matrix and dotting it with the COLUMN VECTOR to get
ONE ROW of the output COLUMN VECTOR- one float.*/
vr.d[0] = t.d[0*4] * v.d[0] +
t.d[1*4] * v.d[1] +
t.d[2*4] * v.d[2] +
t.d[3*4] * v.d[3];
vr.d[1] = t.d[0*4+1] * v.d[0] +
t.d[1*4+1] * v.d[1] +
t.d[2*4+1] * v.d[2] +
t.d[3*4+1] * v.d[3];
vr.d[2] = t.d[0*4+2] * v.d[0] +
t.d[1*4+2] * v.d[1] +
t.d[2*4+2] * v.d[2] +
t.d[3*4+2] * v.d[3];
vr.d[3] = t.d[0*4+3] * v.d[0] +
t.d[1*4+3] * v.d[1] +
t.d[2*4+3] * v.d[2] +
t.d[3*4+3] * v.d[3];
return vr;
}
static inline vec3 crossv3( vec3 a, vec3 b){
vec3 retval;
retval.d[0] = a.d[1] * b.d[2] - a.d[2] * b.d[1];
retval.d[1] = a.d[2] * b.d[0] - a.d[0] * b.d[2];
retval.d[2] = a.d[0] * b.d[1] - a.d[1] * b.d[0];
return retval;
}
static inline vec3 scalev3( f_ s, vec3 i){i.d[0] *= s; i.d[1] *= s; i.d[2] *= s; return i;}
static inline vec4 scalev4( f_ s, vec4 i){i.d[0] *= s; i.d[1] *= s; i.d[2] *= s;i.d[3] *= s; return i;}
static inline vec3 normalizev3( vec3 a){
if(lengthv3(a)==0) return (vec3){.d[0]=0.0,.d[1]=0.0,.d[2]=1.0};
return scalev3(1.0/lengthv3(a), a);
}
static inline vec4 normalizev4( vec4 a){
if(lengthv4(a)==0) return (vec4){.d[0]=0.0,.d[1]=0.0,.d[2]=1.0,.d[3]=0.0};
return scalev4(1.0/lengthv4(a), a);
}
static inline vec3 addv3( vec3 aa, vec3 b){
vec3 a = aa;
a.d[0] += b.d[0]; a.d[1] += b.d[1]; a.d[2] += b.d[2]; return a;
}
static inline vec3 rotatev3( vec3 in, vec3 axis, f_ ang){
vec3 t1 = scalev3(cosf(ang),in);
vec3 t2 = scalev3(sinf(ang),crossv3(axis,in));
vec3 t3 = scalev3((1-cosf(ang))*dotv3(axis,in),axis);
return addv3(t1,addv3(t2,t3));
}
static inline vec4 addv4( vec4 aa, vec4 b){
vec4 a = aa;
a.d[0] += b.d[0]; a.d[1] += b.d[1]; a.d[2] += b.d[2]; a.d[3] += b.d[3]; return a;
}
static inline vec3 subv3( vec3 a, vec3 b){
return addv3(a,scalev3(-1,b));
}
static inline mat4 identitymat4(){
return scalemat4(
(vec4){.d[0]=1.0,.d[1]=1.0,.d[2]=1.0,.d[3]=1.0}
);
}
static inline mat4 translate( vec3 t){
mat4 tm = identitymat4();
tm.d[3*4+0] = t.d[0];
tm.d[3*4+1] = t.d[1];
tm.d[3*4+2] = t.d[2];
return tm;
}
static inline vec4 subv4( vec4 a, vec4 b){
return addv4(a,scalev4(-1,b));
}
static inline vec3 reflect( vec3 in, vec3 norm){
return
addv3(in,
scalev3(-2.0*dotv3(norm, in),
norm
)
);
}
static inline vec4 upv3( vec3 in, f_ w){
return (vec4){
.d[0]=in.d[0],
.d[1]=in.d[1],
.d[2]=in.d[2],
.d[3]=w
};
}
static inline vec3 downv4( vec4 in){
return (vec3){
.d[0]=in.d[0],
.d[1]=in.d[1],
.d[2]=in.d[2]
};
}
static inline mat4 lookAt( vec3 eye, vec3 at, vec3 up){
mat4 cw = identitymat4();
vec3 zaxis = normalizev3(subv3(at,eye));
vec3 xaxis = normalizev3(crossv3(zaxis,up));
vec3 yaxis = crossv3(xaxis, zaxis);
zaxis = scalev3(-1,zaxis);
cw.d[0*4+0] = xaxis.d[0];
cw.d[1*4+0] = xaxis.d[1];
cw.d[2*4+0] = xaxis.d[2];
cw.d[3*4+0] = -dotv3(xaxis,eye);
cw.d[0*4+1] = yaxis.d[0];
cw.d[1*4+1] = yaxis.d[1];
cw.d[2*4+1] = yaxis.d[2];
cw.d[3*4+1] = -dotv3(yaxis,eye);
cw.d[0*4+2] = zaxis.d[0];
cw.d[1*4+2] = zaxis.d[1];
cw.d[2*4+2] = zaxis.d[2];
cw.d[3*4+2] = -dotv3(zaxis,eye);
cw.d[0*4+3] = 0;
cw.d[1*4+3] = 0;
cw.d[2*4+3] = 0;
cw.d[3*4+3] = 1;
return cw;
}
/*
Collision detection
These Algorithms return the penetration vector into
the shape in the first argument
With depth of penetration in element 4
if depth of penetration is zero or lower then there is no penetration.
*/
static inline vec4 spherevsphere( vec4 s1, vec4 s2){
vec4 ret;
vec3 diff = subv3(
downv4(s2),
downv4(s1)
);
f_ lv3 = lengthv3(diff);
f_ l = (s1.d[3] + s2.d[3]-lv3);
if(l < 0 || lv3 == 0) {
ret.d[3] = 0;return ret;
}
ret = upv3(
scalev3(
l/lv3,diff
)
,l
);
return ret;
}
static inline int boxvboxbool (aabb b1, aabb b2){
vec3 sumextents = addv3(b1.e,b2.e);
vec3 b1c = downv4(b1.c);
vec3 b2c = downv4(b2.c);
if(
!(
(fabs(b1c.d[0] - b2c.d[0]) <= sumextents.d[0]) &&
(fabs(b1c.d[1] - b2c.d[1]) <= sumextents.d[1]) &&
(fabs(b1c.d[2] - b2c.d[2]) <= sumextents.d[2])
)
){
return 0;
}
return 1;
}
static inline vec4 boxvbox( aabb b1, aabb b2){ /*Just points along the minimum separating axis, Nothing fancy.*/
vec4 ret = (vec4){
.d[0]=0,
.d[1]=0,
.d[2]=0,
.d[3]=0
};
vec3 sumextents = addv3(b1.e,b2.e);
vec3 b1c = downv4(b1.c);
vec3 b2c = downv4(b2.c);
vec3 b1min = subv3(b1c,b1.e);
vec3 b2min = subv3(b2c,b2.e);
vec3 b1max = addv3(b1c,b1.e);
vec3 b2max = addv3(b2c,b2.e);
if(
!(
(fabs(b1c.d[0] - b2c.d[0]) <= sumextents.d[0]) &&
(fabs(b1c.d[1] - b2c.d[1]) <= sumextents.d[1]) &&
(fabs(b1c.d[2] - b2c.d[2]) <= sumextents.d[2])
)
){
return ret;
}
vec3 axispen[2];
axispen[0] = subv3(b1max,b2min);
axispen[1] = subv3(b1min,b2max);
ret.d[3] = fabs(axispen[0].d[0]);
ret.d[0] = axispen[0].d[0];
for(int i = 1; i < 6; i++){
if(fabs(axispen[i/3].d[i%3]) < fabs(ret.d[3])){
ret = (vec4){
.d[0]=0,
.d[1]=0,
.d[2]=0,
.d[3]=(axispen[i/3].d[i%3])
};
ret.d[i%3] = ret.d[3];
ret.d[3] = fabs(ret.d[3]);
}
}
return ret;
}
static inline vec3 closestpointAABB( aabb b, vec3 p){
vec3 b1min = subv3(downv4(b.c),b.e);
vec3 b1max = addv3(downv4(b.c),b.e);
return clampvec3(p,b1min,b1max);
}
static inline vec4 spherevaabb( vec4 sph, aabb box){
vec4 ret;
vec3 p = closestpointAABB(box,downv4(sph));
vec3 v = subv3(p,downv4(sph));
f_ d2 = dotv3(v,v);
if(d2 <= sph.d[3] * sph.d[3]){
f_ len = lengthv3(v);
f_ diff = (sph.d[3] - len);
if(len > 0){
f_ factor = diff/len;
vec3 bruh = scalev3(factor, v);
ret = upv3(bruh, diff);
return ret;
} else {
aabb virt;
virt.c = sph;
virt.e.d[0] = sph.d[3];
virt.e.d[1] = sph.d[3];
virt.e.d[2] = sph.d[3];
return boxvbox(virt,box);
}
}
else
return (vec4){
.d[0]=0,
.d[1]=0,
.d[2]=0,
.d[3]=0
};
}
/*END Math_Library.h~~~~~~~~~~~~~~~~~~~~*/
#endif
|
hermv_c_bsr_n_hi.c | #include <string.h>
#ifdef _OPENMP
#include <omp.h>
#endif
#include "alphasparse/opt.h"
#include "alphasparse/kernel.h"
#include "alphasparse/util.h"
alphasparse_status_t
ONAME(const ALPHA_Number alpha,
const ALPHA_SPMAT_BSR *A,
const ALPHA_Number *x,
const ALPHA_Number beta,
ALPHA_Number *y)
{
const ALPHA_INT m = A->rows * A->block_size;
const ALPHA_INT n = A->cols * A->block_size;
const ALPHA_INT bs = A->block_size;
const ALPHA_INT bs2 = bs * bs;
// assert(m==n);
ALPHA_INT b_rows = A->rows;
ALPHA_INT b_cols = A->cols;
if (b_rows != b_cols)
return ALPHA_SPARSE_STATUS_INVALID_VALUE;
ALPHA_INT thread_num = alpha_get_thread_num();
ALPHA_INT partition[thread_num + 1];
balanced_partition_row_by_nnz(A->rows_end, b_rows, thread_num, partition);
ALPHA_Number **tmp = (ALPHA_Number **)malloc(sizeof(ALPHA_Number *) * thread_num);
#ifdef _OPENMP
#pragma omp parallel num_threads(thread_num)
#endif
{
const ALPHA_INT tid = alpha_get_thread_id();
const ALPHA_INT local_m_s = partition[tid];
const ALPHA_INT local_m_e = partition[tid + 1];
tmp[tid] = (ALPHA_Number *)malloc(sizeof(ALPHA_Number) * b_rows * bs);
memset(tmp[tid], 0, sizeof(ALPHA_Number) * b_rows * bs);
if (A->block_layout == ALPHA_SPARSE_LAYOUT_ROW_MAJOR)
{
for (ALPHA_INT br = local_m_s; br < local_m_e; br++)
{
ALPHA_INT row = br * bs;
ALPHA_INT block_start = A->rows_start[br], block_end = A->rows_end[br];
ALPHA_INT upper_start = alpha_lower_bound(&A->col_indx[block_start], &A->col_indx[block_end], br) - A->col_indx;
for (ALPHA_INT ai = upper_start; ai < block_end; ai++)
{
ALPHA_INT bc = A->col_indx[ai];
ALPHA_INT col = bc * bs;
ALPHA_INT a0_idx = ai * bs2;
// diagonal block containing diagonal entry
if (bc == br)
{
for (ALPHA_INT b_row = 0; b_row < bs; b_row++)
{
//dignaol entry A(row+b_row,col+b_col)
alpha_madde(tmp[tid][b_row + row], A->values[a0_idx + b_row * (bs + 1)], x[col + b_row]);
//tmp[tid][b_row + row] += alpha*A->values[a0_idx + (b_row + 1) * bs]*x[col + b_col];
for (ALPHA_INT b_col = b_row + 1; b_col < bs; b_col++)
{
alpha_madde(tmp[tid][b_row + row], A->values[a0_idx + b_row * bs + b_col], x[col + b_col]);
alpha_madde_2c(tmp[tid][b_col + col], A->values[a0_idx + b_row * bs + b_col], x[row + b_row]);
}
}
}
else
{
for (ALPHA_INT b_row = 0; b_row < bs; b_row++)
{
for (ALPHA_INT b_col = 0; b_col < bs; b_col++)
{
alpha_madde(tmp[tid][b_row + row], A->values[a0_idx + b_row * bs + b_col], x[col + b_col]);
alpha_madde_2c(tmp[tid][b_col + col], A->values[a0_idx + b_row * bs + b_col], x[row + b_row]);
}
}
}
}
}
}
else if (A->block_layout == ALPHA_SPARSE_LAYOUT_COLUMN_MAJOR)
{
for (ALPHA_INT br = local_m_s; br < local_m_e; br++)
{
ALPHA_INT row = br * bs;
ALPHA_INT block_start = A->rows_start[br], block_end = A->rows_end[br];
ALPHA_INT upper_start = alpha_lower_bound(&A->col_indx[block_start], &A->col_indx[block_end], br) - A->col_indx;
for (ALPHA_INT ai = upper_start; ai < block_end; ai++)
{
ALPHA_INT bc = A->col_indx[ai];
ALPHA_INT col = bc * bs;
ALPHA_INT a0_idx = ai * bs2;
// diagonal block containing diagonal entry
if (bc == br)
{
for (ALPHA_INT b_col = 0; b_col < bs; b_col++)
{
//dignaol entry A(row+b_row,col+b_col)
alpha_madde(tmp[tid][b_col + row], A->values[a0_idx + b_col * (bs + 1)], x[b_col + col]);
//tmp[tid][b_row + row] += alpha*A->values[a0_idx + (b_row + 1) * bs]*x[col + b_col];
for (ALPHA_INT b_row = 0; b_row < b_col; b_row++)
{
alpha_madde(tmp[tid][b_row + row], A->values[a0_idx + b_col * bs + b_row], x[col + b_col]);
alpha_madde_2c(tmp[tid][b_col + col], A->values[a0_idx + b_col * bs + b_row], x[row + b_row]);
}
}
}
else
{
for (ALPHA_INT b_col = 0; b_col < bs; b_col++)
{
for (ALPHA_INT b_row = 0; b_row < bs; b_row++)
{
alpha_madde(tmp[tid][b_row + row], A->values[a0_idx + b_col * bs + b_row], x[col + b_col]);
alpha_madde_2c(tmp[tid][b_col + col], A->values[a0_idx + b_col * bs + b_row], x[row + b_row]);
}
}
}
}
}
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < b_cols * bs; ++i)
{
ALPHA_Number tmp_y;
alpha_setzero(tmp_y);
for (ALPHA_INT j = 0; j < thread_num; ++j)
{
alpha_add(tmp_y, tmp_y, tmp[j][i]);
//tmp_y += tmp[j][i];
}
alpha_mul(y[i], y[i], beta);
alpha_madde(y[i], tmp_y, alpha);
//y[i] = y[i]*beta + tmp_y*alpha;
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(thread_num)
#endif
for (ALPHA_INT i = 0; i < thread_num; ++i)
{
free(tmp[i]);
}
free(tmp);
return ALPHA_SPARSE_STATUS_SUCCESS;
}
|
direct.h | #include <math.h>
#include <stdio.h>
#include <iostream>
#include <sys/time.h>
#include <omp.h>
#define REAL double
double get_time (void);
REAL norm(REAL *x);
void cross(REAL *x, REAL *y, REAL *z);
void MV(REAL *M, REAL *V, REAL *res);
REAL dot_prod(REAL *x, REAL *y);
void axpy(REAL *x, REAL *y, REAL *z, REAL alpha, int sign, int N);
void ax(REAL *x, REAL *y, REAL alpha, int N);
void lineInt(REAL &PHI_K, REAL &PHI_V, REAL z, REAL x, REAL v1, REAL v2, REAL kappa, REAL *xk, REAL *wk, int K, int LorY);
void intSide(REAL &PHI_K, REAL &PHI_V, REAL *v1, REAL *v2, REAL p, REAL kappa, REAL *xk, REAL *wk, int K, int LorY);
void SA(REAL &PHI_K, REAL &PHI_V, REAL *y, REAL *x, REAL kappa, int same,
REAL K_diag, REAL V_diag, int LorY, REAL *xk, int xkSize, REAL *wk);
void computeDiagonal_cy(REAL *VL, int VLSize, REAL *KL, int KLSize, REAL *VY, int VYSize, REAL *KY, int KYSize,
REAL *triangle, int triangleSize, REAL *centers, int centersSize, REAL kappa,
REAL K_diag, REAL V_diag, REAL *xk, int xkSize, REAL *wk, int wkSize);
void GQ_fine(REAL &PHI_K, REAL &PHI_V, REAL *panel, REAL xi, REAL yi, REAL zi,
REAL kappa, REAL *Xk, REAL *Wk, int K_fine, REAL Area, int LorY);
void GQ_fineKt(REAL &PHI_Ktx, REAL &PHI_Kty, REAL &PHI_Ktz, REAL *panel,
REAL xi, REAL yi, REAL zi, REAL kappa, REAL *Xk, REAL *Wk,
int K_fine, REAL Area, int LorY);
void direct_c_cy(int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, int AI_int, REAL *phi_reac, int phi_reacSize);
void direct_sort_cy(REAL *K_aux, int K_auxSize, REAL *V_aux, int V_auxSize, int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *interList, int interListSize, int *offTar, int offTarSize, int *sizeTar, int sizeTarSize, int *offSrc, int offSrcSize, int *offTwg, int offTwgSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, REAL *aux, int auxSize);
void directKt_sort_cy(REAL *Ktx_aux, int Ktx_auxSize, REAL *Kty_aux, int Kty_auxSize, REAL *Ktz_aux, int Ktz_auxSize,
int LorY, REAL *triangle, int triangleSize,
int *k, int kSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize, REAL *s_zj, int s_zjSize,
REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mKclean, int mKcleanSize,
int *interList, int interListSize, int *offTar, int offTarSize, int *sizeTar, int sizeTarSize,
int *offSrc, int offSrcSize, int *offTwg, int offTwgSize, REAL *Area, int AreaSize,
REAL *Xsk, int XskSize, REAL *Wsk, int WskSize, REAL kappa, REAL threshold, REAL eps, REAL *aux, int auxSize);
void coulomb_direct_cy(REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *K_aux, int K_auxSize);
void direct_c_derivative_cy(REAL *dKx_aux, int dKx_auxSize, REAL *dKy_aux, int dKy_auxSize, REAL *dKz_aux, int dKz_auxSize,
REAL *dVx_aux, int dVx_auxSize, REAL *dVy_aux, int dVy_auxSize, REAL *dVz_aux, int dVz_auxSize,
int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, REAL *aux, int auxSize);
double get_time (void)
{
struct timeval tv;
gettimeofday(&tv,NULL);
return (double)(tv.tv_sec+1e-6*tv.tv_usec);
};
REAL norm(REAL *x)
{
return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);
};
void cross(REAL *x, REAL *y, REAL *z) // z is the resulting array
{
z[0] = x[1]*y[2] - x[2]*y[1];
z[1] = x[2]*y[0] - x[0]*y[2];
z[2] = x[0]*y[1] - x[1]*y[0];
};
void MV(REAL *M, REAL *V, REAL *res) // 3x3 mat-vec
{
REAL V2[3] = {V[0], V[1], V[2]};
for (int i=0; i<3; i++)
{
REAL sum = 0.;
for (int j=0; j<3; j++)
{
sum += M[3*i+j]*V2[j];
}
res[i] = sum;
}
};
REAL dot_prod(REAL *x, REAL *y) // len(3) vector dot product
{
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
};
void axpy(REAL *x, REAL *y, REAL *z, REAL alpha, int sign, int N)
{
for(int i=0; i<N; i++)
{
z[i] = sign*alpha*x[i] + y[i];
}
};
void ax(REAL *x, REAL *y, REAL alpha, int N)
{
for(int i=0; i<N; i++)
{
y[i] = alpha*x[i];
}
};
void lineInt(REAL &PHI_K, REAL &PHI_V, REAL z, REAL x, REAL v1, REAL v2, REAL kappa, REAL *xk, REAL *wk, int K, int LorY)
{
REAL theta1 = atan2(v1,x);
REAL theta2 = atan2(v2,x);
REAL dtheta = theta2 - theta1;
REAL thetam = (theta2 + theta1)/2;
REAL absZ = fabs(z), signZ;
if (absZ<1e-10) signZ = 0;
else signZ = z/absZ;
// Loop over gauss points
REAL thetak, Rtheta, R, expKr, expKz;
if (LorY==2)
expKz = exp(-kappa*absZ);
for (int i=0; i<K; i++)
{
thetak = dtheta/2*xk[i] + thetam;
Rtheta = x/cos(thetak);
R = sqrt(Rtheta*Rtheta + z*z);
expKr = exp(-kappa*R);
if (LorY==2)
{
if (kappa>1e-12)
{
PHI_V += -wk[i]*(expKr - expKz)/kappa * dtheta/2;
PHI_K += wk[i]*(z/R*expKr - expKz*signZ) * dtheta/2;
}
else
{
PHI_V += wk[i]*(R-absZ) * dtheta/2;
PHI_K += wk[i]*(z/R - signZ) * dtheta/2;
}
}
if (LorY==1)
{
PHI_V += wk[i]*(R-absZ) * dtheta/2;
PHI_K += wk[i]*(z/R - signZ) * dtheta/2;
}
}
};
void intSide(REAL &PHI_K, REAL &PHI_V, REAL *v1, REAL *v2, REAL p, REAL kappa, REAL *xk, REAL *wk, int K, int LorY)
{
REAL v21[3];
for (int i=0; i<3; i++)
{
v21[i] = v2[i] - v1[i];
}
REAL L21 = norm(v21);
REAL v21u[3];
ax(v21, v21u, 1/L21, 3);
REAL unit[3] = {0.,0.,1.};
REAL orthog[3];
cross(unit, v21u, orthog);
REAL alpha = dot_prod(v21,v1)/(L21*L21);
REAL rOrthog[3];
axpy(v21, v1, rOrthog, alpha, -1, 3);
//REAL d_toEdge = norm(rOrthog);
REAL v1_neg[3];
ax(v1, v1_neg, -1, 3);
REAL side_vec[3];
cross(v21, v1_neg, side_vec);
REAL rotateToVertLine[9];
for(int i=0; i<3; i++)
{
rotateToVertLine[3*i] = orthog[i];
rotateToVertLine[3*i+1] = v21u[i];
rotateToVertLine[3*i+2] = unit[i];
}
REAL v1new[3];
MV(rotateToVertLine,v1,v1new);
if (v1new[0]<0)
{
ax(v21u, v21u, -1, 3);
ax(orthog, orthog, -1, 3);
ax(rotateToVertLine, rotateToVertLine, -1, 9);
rotateToVertLine[8] = 1.;
MV(rotateToVertLine,v1,v1new);
}
REAL v2new[3], rOrthognew[3];
MV(rotateToVertLine,v2,v2new);
MV(rotateToVertLine,rOrthog,rOrthognew);
REAL x = v1new[0];
if ((v1new[1]>0 && v2new[1]<0) || (v1new[1]<0 && v2new[1]>0))
{
REAL PHI1_K = 0. , PHI2_K = 0.;
REAL PHI1_V = 0. , PHI2_V = 0.;
lineInt(PHI1_K, PHI1_V, p, x, 0, v1new[1], kappa, xk, wk, K, LorY);
lineInt(PHI2_K, PHI2_V, p, x, v2new[1], 0, kappa, xk, wk, K, LorY);
PHI_K += PHI1_K + PHI2_K;
PHI_V += PHI1_V + PHI2_V;
}
else
{
REAL PHI_Kaux = 0., PHI_Vaux = 0.;
lineInt(PHI_Kaux, PHI_Vaux, p, x, v1new[1], v2new[1], kappa, xk, wk, K, LorY);
PHI_K -= PHI_Kaux;
PHI_V -= PHI_Vaux;
}
};
void SA(REAL &PHI_K, REAL &PHI_V, REAL *y, REAL *x, REAL kappa, int same,
REAL K_diag, REAL V_diag, int LorY, REAL *xk, int xkSize, REAL *wk)
{
// Put first panel at origin
REAL y0_panel[3], y1_panel[3], y2_panel[3], x_panel[3];
REAL X[3], Y[3], Z[3];
for (int i=0; i<3;i++)
{
x_panel[i] = x[i] - y[i];
y0_panel[i] = 0.;
y1_panel[i] = y[3+i] - y[i];
y2_panel[i] = y[6+i] - y[i];
X[i] = y1_panel[i];
}
// Find panel coordinate system X: 0->1
cross(y1_panel, y2_panel, Z);
REAL Xnorm = norm(X);
REAL Znorm = norm(Z);
for (int i=0; i<3; i++)
{
X[i] /= Xnorm;
Z[i] /= Znorm;
}
cross(Z,X,Y);
// Rotate the coordinate system to match panel plane
REAL rot_matrix[9];
for (int i=0; i<3; i++)
{
rot_matrix[i] = X[i];
rot_matrix[i+3] = Y[i];
rot_matrix[i+6] = Z[i];
}
REAL panel0_plane[3], panel1_plane[3], panel2_plane[3], x_plane[3];
MV(rot_matrix, y0_panel, panel0_plane);
MV(rot_matrix, y1_panel, panel1_plane);
MV(rot_matrix, y2_panel, panel2_plane);
MV(rot_matrix, x_panel, x_plane);
// Shift origin so it matches collocation point
REAL panel0_final[3], panel1_final[3], panel2_final[3];
for (int i=0; i<3; i++)
{
if (i<2)
{
panel0_final[i] = panel0_plane[i] - x_plane[i];
panel1_final[i] = panel1_plane[i] - x_plane[i];
panel2_final[i] = panel2_plane[i] - x_plane[i];
}
else
{
panel0_final[i] = panel0_plane[i];
panel1_final[i] = panel1_plane[i];
panel2_final[i] = panel2_plane[i];
}
}
// Loop over sides
intSide(PHI_K, PHI_V, panel0_final, panel1_final, x_plane[2], kappa, xk, wk, xkSize, LorY); // Side 0
intSide(PHI_K, PHI_V, panel1_final, panel2_final, x_plane[2], kappa, xk, wk, xkSize, LorY); // Side 1
intSide(PHI_K, PHI_V, panel2_final, panel0_final, x_plane[2], kappa, xk, wk, xkSize, LorY); // Side 2
if (same==1)
{
PHI_K += K_diag;
PHI_V += V_diag;
}
};
void computeDiagonal_cy(REAL *VL, int VLSize, REAL *KL, int KLSize, REAL *VY, int VYSize, REAL *KY, int KYSize,
REAL *triangle, int triangleSize, REAL *centers, int centersSize, REAL kappa,
REAL K_diag, REAL V_diag, REAL *xk, int xkSize, REAL *wk, int wkSize)
{
int N = VLSize, LorY;
REAL PHI_K, PHI_V;
for(int i=0; i<N; i++)
{
REAL panel[9] = {triangle[9*i], triangle[9*i+1], triangle[9*i+2],
triangle[9*i+3], triangle[9*i+4], triangle[9*i+5],
triangle[9*i+6], triangle[9*i+7], triangle[9*i+8]};
REAL center[3] = {centers[3*i], centers[3*i+1], centers[3*i+2]};
PHI_K = 0.;
PHI_V = 0.;
LorY = 1; // Laplace
SA(PHI_K, PHI_V, panel, center, 1e-12, 1,
K_diag, V_diag, LorY, xk, xkSize, wk);
VL[i] = PHI_V;
KL[i] = PHI_K;
PHI_K = 0.;
PHI_V = 0.;
LorY = 2; // Yukawa
SA(PHI_K, PHI_V, panel, center, kappa, 1,
K_diag, V_diag, LorY, xk, xkSize, wk);
VY[i] = PHI_V;
KY[i] = PHI_K;
}
};
void GQ_fine(REAL &PHI_K, REAL &PHI_V, REAL *panel, REAL xi, REAL yi, REAL zi,
REAL kappa, REAL *Xk, REAL *Wk, int K_fine, REAL Area, int LorY)
{
REAL nx, ny, nz;
REAL dx, dy, dz, r, aux;
PHI_K = 0.;
PHI_V = 0.;
aux = 1/(2*Area);
nx = ((panel[4]-panel[1])*(panel[2]-panel[8]) - (panel[5]-panel[2])*(panel[1]-panel[7])) * aux;
ny = ((panel[5]-panel[2])*(panel[0]-panel[6]) - (panel[3]-panel[0])*(panel[2]-panel[8])) * aux;
nz = ((panel[3]-panel[0])*(panel[1]-panel[7]) - (panel[4]-panel[1])*(panel[0]-panel[6])) * aux;
#pragma unroll
for (int kk=0; kk<K_fine; kk++)
{
dx = xi - (panel[0]*Xk[3*kk] + panel[3]*Xk[3*kk+1] + panel[6]*Xk[3*kk+2]);
dy = yi - (panel[1]*Xk[3*kk] + panel[4]*Xk[3*kk+1] + panel[7]*Xk[3*kk+2]);
dz = zi - (panel[2]*Xk[3*kk] + panel[5]*Xk[3*kk+1] + panel[8]*Xk[3*kk+2]);
r = 1/sqrt(dx*dx + dy*dy + dz*dz); // r is 1/r!!!
if (LorY==1)
{
aux = Wk[kk]*Area*r;
PHI_V += aux;
PHI_K += aux*(nx*dx+ny*dy+nz*dz)*(r*r);
}
else
{
aux = Wk[kk]*Area*exp(-kappa*1/r)*r;
PHI_V += aux;
PHI_K += aux*(nx*dx+ny*dy+nz*dz)*r*(kappa+r);
}
}
};
void GQ_fineKt(REAL &PHI_Ktx, REAL &PHI_Kty, REAL &PHI_Ktz, REAL *panel,
REAL xi, REAL yi, REAL zi, REAL kappa, REAL *Xk, REAL *Wk,
int K_fine, REAL Area, int LorY)
{
REAL dx, dy, dz, r, aux;
PHI_Ktx = 0.;
PHI_Kty = 0.;
PHI_Ktz = 0.;
#pragma unroll
for (int kk=0; kk<K_fine; kk++)
{
dx = xi - (panel[0]*Xk[3*kk] + panel[3]*Xk[3*kk+1] + panel[6]*Xk[3*kk+2]);
dy = yi - (panel[1]*Xk[3*kk] + panel[4]*Xk[3*kk+1] + panel[7]*Xk[3*kk+2]);
dz = zi - (panel[2]*Xk[3*kk] + panel[5]*Xk[3*kk+1] + panel[8]*Xk[3*kk+2]);
r = 1/sqrt(dx*dx + dy*dy + dz*dz); // r is 1/r!!!
if (LorY==1)
{
aux = Wk[kk]*Area*r*r*r;
PHI_Ktx -= aux*dx;
PHI_Kty -= aux*dy;
PHI_Ktz -= aux*dz;
}
else
{
aux = Wk[kk]*Area*exp(-kappa*1/r)*r*r*(kappa+r);
PHI_Ktx -= aux*dx;
PHI_Kty -= aux*dy;
PHI_Ktz -= aux*dz;
}
}
};
void GQ_fine_derivative(REAL &dPHI_Kx, REAL &dPHI_Ky, REAL &dPHI_Kz,
REAL &dPHI_Vx, REAL &dPHI_Vy, REAL &dPHI_Vz,
REAL *panel, REAL xi, REAL yi, REAL zi, REAL kappa,
REAL *Xk, REAL *Wk, int K_fine, REAL Area, int LorY)
{
REAL nx, ny, nz;
REAL dx, dy, dz, r, r3, aux;
dPHI_Kx = 0.;
dPHI_Ky = 0.;
dPHI_Kz = 0.;
dPHI_Vx = 0.;
dPHI_Vy = 0.;
dPHI_Vz = 0.;
aux = 1/(2*Area);
nx = ((panel[4]-panel[1])*(panel[2]-panel[8]) - (panel[5]-panel[2])*(panel[1]-panel[7])) * aux;
ny = ((panel[5]-panel[2])*(panel[0]-panel[6]) - (panel[3]-panel[0])*(panel[2]-panel[8])) * aux;
nz = ((panel[3]-panel[0])*(panel[1]-panel[7]) - (panel[4]-panel[1])*(panel[0]-panel[6])) * aux;
#pragma unroll
for (int kk=0; kk<K_fine; kk++)
{
dx = xi - (panel[0]*Xk[3*kk] + panel[3]*Xk[3*kk+1] + panel[6]*Xk[3*kk+2]);
dy = yi - (panel[1]*Xk[3*kk] + panel[4]*Xk[3*kk+1] + panel[7]*Xk[3*kk+2]);
dz = zi - (panel[2]*Xk[3*kk] + panel[5]*Xk[3*kk+1] + panel[8]*Xk[3*kk+2]);
r = 1/sqrt(dx*dx + dy*dy + dz*dz); // r is 1/r!!!
r3 = r*r*r;
if (LorY==1)
{
aux = Wk[kk]*Area*r3;
dPHI_Vx -= dx*aux;
dPHI_Vy -= dy*aux;
dPHI_Vz -= dz*aux;
dPHI_Kx += aux*nx-3*aux*dx*(nx*dx+ny*dy+nz*dz)*(r*r);
dPHI_Ky += aux*ny-3*aux*dy*(nx*dx+ny*dy+nz*dz)*(r*r);
dPHI_Kz += aux*nz-3*aux*dz*(nx*dx+ny*dy+nz*dz)*(r*r);
}
else // this else will never fire as this function is only used to calculate energy (always Laplace)
{
aux = Wk[kk]*Area*exp(-kappa*1/r)*r;
dPHI_Vx += aux;
dPHI_Kx += aux*(nx*dx+ny*dy+nz*dz)*r*(kappa+r);
}
}
};
void direct_c_cy(int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, int AI_int, REAL *phi_reac, int phi_reacSize)
{
int N_source = s_xjSize;
REAL dx, dy, dz, dx_tri, dy_tri, dz_tri, R, R2, R3, R_tri, expKr;
bool L_d, same, condition_an, condition_gq;
#pragma omp parallel for default(none) shared(N_source, xt, xi, yt, yi, zt, zi, tri, Area, eps, threshold, k, s_xj, s_yj, s_zj, LorY, kappa, m, mx, my, mz, triangle, K_diag, sglInt_int, sglInt_ext, Xsk, Wsk, WskSize, mVclean, mKclean, IorE, xtSize, AI_int, phi_reac) private(dx_tri, dy_tri, dz_tri, R_tri, L_d, same, condition_an, condition_gq, dx, dy, dz, R, R2, R3, expKr)
for(int i_tar = 0; i_tar < xtSize; i_tar++)
{
REAL K_aux = 0.0;
REAL V_aux = 0.0;
int aux = 0;
int i = -1;
REAL V_red = 0.0;
REAL K_red = 0.0;
for(int j=0; j<N_source; j++)
{
// Check if panels are far enough for Gauss quadrature
dx_tri = xt[i_tar] - xi[tri[j]];
dy_tri = yt[i_tar] - yi[tri[j]];
dz_tri = zt[i_tar] - zi[tri[j]];
R_tri = sqrt(dx_tri*dx_tri + dy_tri*dy_tri + dz_tri*dz_tri);
L_d = (sqrt(2*Area[tri[j]])/(R_tri+eps)>=threshold);
same = (i==tri[j]);
condition_an = ((same || L_d) && (k[j]==0));
condition_gq = (!L_d);
if(condition_gq)
{
dx = xt[i_tar] - s_xj[j];
dy = yt[i_tar] - s_yj[j];
dz = zt[i_tar] - s_zj[j];
R = sqrt(dx*dx + dy*dy + dz*dz + eps*eps);
R2 = R*R;
R3 = R2*R;
if (LorY==2)
{
expKr = exp(-kappa*R);
V_red += m[j]*expKr/R;
K_red += expKr/R2*(kappa+1/R) * (dx*mx[j] + dy*my[j] + dz*mz[j]);
}
if (LorY==1)
{
V_red += m[j]/R;
K_red += 1/R3*(dx*mx[j] + dy*my[j] + dz*mz[j]);
}
}
if(condition_an)
{
#pragma omp atomic
aux += 1;
REAL panel[9] = {triangle[9*tri[j]], triangle[9*tri[j]+1], triangle[9*tri[j]+2],
triangle[9*tri[j]+3], triangle[9*tri[j]+4], triangle[9*tri[j]+5],
triangle[9*tri[j]+6], triangle[9*tri[j]+7], triangle[9*tri[j]+8]};
REAL PHI_K = 0., PHI_V = 0.;
if (same==1)
{
PHI_K = K_diag;
if (IorE==1)
PHI_V = sglInt_int[j];
else
PHI_V = sglInt_ext[j];
}
else
{
GQ_fine(PHI_K, PHI_V, panel, xt[i_tar], yt[i_tar], zt[i_tar], kappa, Xsk, Wsk, WskSize, Area[tri[j]], LorY);
}
V_red += PHI_V * mVclean[j];
K_red += PHI_K * mKclean[j];
}
}
V_aux += V_red;
K_aux += K_red;
AI_int += aux;
phi_reac[i_tar] = (-K_aux + V_aux) / (4 * 3.14159265358979323846);
}
};
void direct_sort_cy(REAL *K_aux, int K_auxSize, REAL *V_aux, int V_auxSize, int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *interList, int interListSize, int *offTar, int offTarSize, int *sizeTar, int sizeTarSize, int *offSrc, int offSrcSize, int *offTwg, int offTwgSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, REAL *aux, int auxSize)
{
double start, stop;
int CI_start, CI_end, CJ_start, CJ_end, list_start, list_end, CJ;
REAL dx, dy, dz, dx_tri, dy_tri, dz_tri, R, R2, R3, R_tri, expKr, sum_K, sum_V;
bool L_d, same, condition_an, condition_gq;
for (int tarTwg=0; tarTwg<offTarSize; tarTwg++)
{
CI_start = offTar[tarTwg];
CI_end = offTar[tarTwg] + sizeTar[tarTwg];
list_start = offTwg[tarTwg];
list_end = offTwg[tarTwg+1];
#pragma omp parallel for private(sum_K, sum_V, CJ, CJ_start, CJ_end, dx_tri, dy_tri, dz_tri, R_tri, L_d, same, condition_an, condition_gq, dx, dy, dz, R, R2, R3, expKr, start, stop) shared(list_start, list_end, interList, offSrc, triangle, xt, yt, zt, Area, eps, threshold, k, s_xj, s_yj, s_zj, LorY, kappa, m, mx, my, mz, aux, K_diag, IorE, sglInt_int, sglInt_ext, Xsk, XskSize, Wsk, WskSize, mVclean, mKclean, V_aux, K_aux) schedule(runtime)
for(int i=CI_start; i<CI_end; i++)
{
sum_K = 0.;
sum_V = 0.;
for (int lst=list_start; lst<list_end; lst++)
{
CJ = interList[lst];
CJ_start = offSrc[CJ];
CJ_end = offSrc[CJ+1];
for(int j=CJ_start; j<CJ_end; j++)
{
// Check if panels are far enough for Gauss quadrature
int ptr = 9*j;
REAL panel[9] = {triangle[ptr], triangle[ptr+1], triangle[ptr+2],
triangle[ptr+3], triangle[ptr+4], triangle[ptr+5],
triangle[ptr+6], triangle[ptr+7], triangle[ptr+8]};
dx_tri = xt[i] - (panel[0]+panel[3]+panel[6])/3;
dy_tri = yt[i] - (panel[1]+panel[4]+panel[7])/3;
dz_tri = zt[i] - (panel[2]+panel[5]+panel[8])/3;
R_tri = sqrt(dx_tri*dx_tri + dy_tri*dy_tri + dz_tri*dz_tri);
L_d = (sqrt(2*Area[j])/(R_tri+eps)>=threshold);
same = (R_tri<1e-12);
condition_an = ((L_d) && (k[j]==0));
condition_gq = (!L_d);
if(condition_gq)
{
dx = xt[i] - s_xj[j];
dy = yt[i] - s_yj[j];
dz = zt[i] - s_zj[j];
R = sqrt(dx*dx + dy*dy + dz*dz + eps*eps);
R2 = R*R;
R3 = R2*R;
if (LorY==2)
{
expKr = exp(-kappa*R);
sum_V += m[j]*expKr/R;
sum_K += expKr/R2*(kappa+1/R) * (dx*mx[j] + dy*my[j] + dz*mz[j]);
}
if (LorY==1)
{
sum_V += m[j]/R;
sum_K += 1/R3*(dx*mx[j] + dy*my[j] + dz*mz[j]);
}
}
if(condition_an)
{
start = get_time();
aux[0] += 1;
REAL PHI_K = 0., PHI_V = 0.;
if (same==1)
{
PHI_K = K_diag;
if (IorE==1)
PHI_V = sglInt_int[j];
else
PHI_V = sglInt_ext[j];
}
else
{
GQ_fine(PHI_K, PHI_V, panel, xt[i], yt[i], zt[i], kappa, Xsk, Wsk, WskSize, Area[j], LorY);
}
sum_V += PHI_V * mVclean[j];
sum_K += PHI_K * mKclean[j];
stop = get_time();
aux[1] += stop - start;
}
}
}
V_aux[i] += sum_V;
K_aux[i] += sum_K;
}
}
};
void directKt_sort_cy(REAL *Ktx_aux, int Ktx_auxSize, REAL *Kty_aux, int Kty_auxSize, REAL *Ktz_aux, int Ktz_auxSize,
int LorY, REAL *triangle, int triangleSize,
int *k, int kSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize, REAL *s_zj, int s_zjSize,
REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mKclean, int mKcleanSize,
int *interList, int interListSize, int *offTar, int offTarSize, int *sizeTar, int sizeTarSize,
int *offSrc, int offSrcSize, int *offTwg, int offTwgSize, REAL *Area, int AreaSize,
REAL *Xsk, int XskSize, REAL *Wsk, int WskSize, REAL kappa, REAL threshold, REAL eps, REAL *aux, int auxSize)
{
double start,stop;
int CI_start, CI_end, CJ_start, CJ_end, list_start, list_end, CJ;
REAL dx, dy, dz, dx_tri, dy_tri, dz_tri, R, R2, R3, R_tri, expKr, sum_Ktx, sum_Kty, sum_Ktz;
bool L_d, same, condition_an, condition_gq;
for (int tarTwg=0; tarTwg<offTarSize; tarTwg++)
{
CI_start = offTar[tarTwg];
CI_end = offTar[tarTwg] + sizeTar[tarTwg];
list_start = offTwg[tarTwg];
list_end = offTwg[tarTwg+1];
for(int i=CI_start; i<CI_end; i++)
{
sum_Ktx = 0.;
sum_Kty = 0.;
sum_Ktz = 0.;
for (int lst=list_start; lst<list_end; lst++)
{
CJ = interList[lst];
CJ_start = offSrc[CJ];
CJ_end = offSrc[CJ+1];
for(int j=CJ_start; j<CJ_end; j++)
{
// Check if panels are far enough for Gauss quadrature
//start = get_time();
int ptr = 9*j;
REAL panel[9] = {triangle[ptr], triangle[ptr+1], triangle[ptr+2],
triangle[ptr+3], triangle[ptr+4], triangle[ptr+5],
triangle[ptr+6], triangle[ptr+7], triangle[ptr+8]};
dx_tri = xt[i] - (panel[0]+panel[3]+panel[6])/3;
dy_tri = yt[i] - (panel[1]+panel[4]+panel[7])/3;
dz_tri = zt[i] - (panel[2]+panel[5]+panel[8])/3;
R_tri = sqrt(dx_tri*dx_tri + dy_tri*dy_tri + dz_tri*dz_tri);
L_d = (sqrt(2*Area[j])/(R_tri+eps)>=threshold);
same = (R_tri<1e-12);
condition_an = ((L_d) && (k[j]==0));
condition_gq = (!L_d);
if(condition_gq)
{
dx = xt[i] - s_xj[j];
dy = yt[i] - s_yj[j];
dz = zt[i] - s_zj[j];
R = sqrt(dx*dx + dy*dy + dz*dz + eps*eps);
R2 = R*R;
R3 = R2*R;
if (LorY==2)
{
expKr = m[j]*exp(-kappa*R)/R2*(kappa+1/R);
sum_Ktx -= expKr * dx;
sum_Kty -= expKr * dy;
sum_Ktz -= expKr * dz;
}
if (LorY==1)
{
expKr = m[j]/R3;
sum_Ktx -= expKr*dx;
sum_Kty -= expKr*dy;
sum_Ktz -= expKr*dz;
}
}
if(condition_an)
{
start = get_time();
aux[0] += 1;
REAL PHI_Ktx = 0.;
REAL PHI_Kty = 0.;
REAL PHI_Ktz = 0.;
if (same==1)
{
PHI_Ktx = 0;
PHI_Kty = 0;
PHI_Ktz = 0;
}
else
{
GQ_fineKt(PHI_Ktx, PHI_Kty, PHI_Ktz, panel, xt[i], yt[i], zt[i], kappa, Xsk, Wsk, WskSize, Area[j], LorY);
}
sum_Ktx += PHI_Ktx * mKclean[j];
sum_Kty += PHI_Kty * mKclean[j];
sum_Ktz += PHI_Ktz * mKclean[j];
stop = get_time();
aux[1] += stop - start;
}
}
}
Ktx_aux[i] += sum_Ktx;
Kty_aux[i] += sum_Kty;
Ktz_aux[i] += sum_Ktz;
}
}
};
void coulomb_direct_cy(REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *K_aux, int K_auxSize)
{
REAL sum, dx, dy, dz, r;
#pragma omp parallel for default(none) shared(xtSize, K_aux, xt, yt, zt, m) private(dx, dy, dz, r, sum) schedule(runtime)
for(int i=0; i<xtSize; i++)
{
sum = 0.;
for(int j=0; j<xtSize; j++)
{
if (i!=j)
{
dx = xt[i] - xt[j];
dy = yt[i] - yt[j];
dz = zt[i] - zt[j];
r = sqrt(dx*dx + dy*dy + dz*dz);
sum += m[j]/r;
}
}
K_aux[i] = m[i]*sum;
}
};
void direct_c_derivative_cy(REAL *dKx_aux, int dKx_auxSize, REAL *dKy_aux, int dKy_auxSize, REAL *dKz_aux, int dKz_auxSize,
REAL *dVx_aux, int dVx_auxSize, REAL *dVy_aux, int dVy_auxSize, REAL *dVz_aux, int dVz_auxSize,
int LorY, REAL K_diag, REAL V_diag, int IorE, REAL *triangle, int triangleSize,
int *tri, int triSize, int *k, int kSize, REAL *xi, int xiSize, REAL *yi, int yiSize,
REAL *zi, int ziSize, REAL *s_xj, int s_xjSize, REAL *s_yj, int s_yjSize,
REAL *s_zj, int s_zjSize, REAL *xt, int xtSize, REAL *yt, int ytSize, REAL *zt, int ztSize,
REAL *m, int mSize, REAL *mx, int mxSize, REAL *my, int mySize, REAL *mz, int mzSize, REAL *mKclean, int mKcleanSize, REAL *mVclean, int mVcleanSize,
int *target, int targetSize,REAL *Area, int AreaSize, REAL *sglInt_int, int sglInt_intSize, REAL *sglInt_ext, int sglInt_extSize,
REAL *xk, int xkSize, REAL *wk, int wkSize, REAL *Xsk, int XskSize, REAL *Wsk, int WskSize,
REAL kappa, REAL threshold, REAL eps, REAL w0, REAL *aux, int auxSize)
{
double start,stop;
int N_target = targetSize;
int N_source = s_xjSize;
REAL dx, dy, dz, dx_tri, dy_tri, dz_tri, R, R2, R3, R_tri, expKr;
bool L_d, same, condition_an, condition_gq;
for(int i_aux=0; i_aux<N_target; i_aux++)
{
int i = target[i_aux];
for(int j=0; j<N_source; j++)
{
// Check if panels are far enough for Gauss quadrature
dx_tri = xt[i_aux] - xi[tri[j]];
dy_tri = yt[i_aux] - yi[tri[j]];
dz_tri = zt[i_aux] - zi[tri[j]];
R_tri = sqrt(dx_tri*dx_tri + dy_tri*dy_tri + dz_tri*dz_tri);
L_d = (sqrt(2*Area[tri[j]])/(R_tri+eps)>=threshold);
same = (i==tri[j]);
condition_an = ((same || L_d) && (k[j]==0));
condition_gq = (!L_d);
if(condition_gq)
{
//start = get_time();
dx = xt[i_aux] - s_xj[j];
dy = yt[i_aux] - s_yj[j];
dz = zt[i_aux] - s_zj[j];
R = 1/sqrt(dx*dx + dy*dy + dz*dz + eps*eps);
R2 = R*R;
R3 = R2*R;
if (LorY==2) // this if never fires as this function is only used for energy calculations (only laplace)
{
expKr = exp(-kappa*R);
dVx_aux[i_aux] += m[j]*expKr*R;
dKx_aux[i_aux] += expKr*R2*(kappa+1*R) * (dx*mx[j] + dy*my[j] + dz*mz[j]);
}
if (LorY==1)
{
dVx_aux[i_aux] -= m[j]*dx*R3;
dVy_aux[i_aux] -= m[j]*dy*R3;
dVz_aux[i_aux] -= m[j]*dz*R3;
dKx_aux[i_aux] += mx[j]*R3-3*dx*R3*R2*(dx*mx[j] + dy*my[j] + dz*mz[j]);
dKy_aux[i_aux] += my[j]*R3-3*dy*R3*R2*(dx*mx[j] + dy*my[j] + dz*mz[j]);
dKz_aux[i_aux] += mz[j]*R3-3*dz*R3*R2*(dx*mx[j] + dy*my[j] + dz*mz[j]);
}
//stop = get_time();
//aux[1] += stop - start;
}
if(condition_an)
{
aux[0] += 1;
REAL center[3] = {xt[i_aux], yt[i_aux], zt[i_aux]};
REAL panel[9] = {triangle[9*tri[j]], triangle[9*tri[j]+1], triangle[9*tri[j]+2],
triangle[9*tri[j]+3], triangle[9*tri[j]+4], triangle[9*tri[j]+5],
triangle[9*tri[j]+6], triangle[9*tri[j]+7], triangle[9*tri[j]+8]};
REAL dPHI_Kx = 0., dPHI_Ky = 0., dPHI_Kz = 0., dPHI_Vx = 0., dPHI_Vy = 0., dPHI_Vz = 0.;
start = get_time();
if (same==1) // So far, this if will never fire, as we only use this function for energy calculation (never singular)
{
dPHI_Kx = K_diag;
if (IorE==1)
dPHI_Vx = sglInt_int[j];
else
dPHI_Vx = sglInt_ext[j];
}
else
{
GQ_fine_derivative(dPHI_Kx, dPHI_Ky, dPHI_Kz, dPHI_Vx, dPHI_Vy, dPHI_Vz, panel, xt[i_aux], yt[i_aux], zt[i_aux], kappa, Xsk, Wsk, WskSize, Area[tri[j]], LorY);
}
stop = get_time();
aux[1] += stop - start;
// printf("%f \t %f\n",PHI_V,mVclean[j]);
dVx_aux[i_aux] += dPHI_Vx * mVclean[j];
dVy_aux[i_aux] += dPHI_Vy * mVclean[j];
dVz_aux[i_aux] += dPHI_Vz * mVclean[j];
dKx_aux[i_aux] += dPHI_Kx * mKclean[j];
dKy_aux[i_aux] += dPHI_Ky * mKclean[j];
dKz_aux[i_aux] += dPHI_Kz * mKclean[j];
}
}
}
}
|
GB_unop__identity_uint8_fc32.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__identity_uint8_fc32)
// op(A') function: GB (_unop_tran__identity_uint8_fc32)
// C type: uint8_t
// A type: GxB_FC32_t
// cast: uint8_t cij = GB_cast_to_uint8_t ((double) crealf (aij))
// unaryop: cij = aij
#define GB_ATYPE \
GxB_FC32_t
#define GB_CTYPE \
uint8_t
// aij = Ax [pA]
#define GB_GETA(aij,Ax,pA) \
GxB_FC32_t aij = Ax [pA]
#define GB_CX(p) Cx [p]
// unary operator
#define GB_OP(z, x) \
z = x ;
// casting
#define GB_CAST(z, aij) \
uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ;
// cij = op (aij)
#define GB_CAST_OP(pC,pA) \
{ \
/* aij = Ax [pA] */ \
GxB_FC32_t aij = Ax [pA] ; \
/* Cx [pC] = op (cast (aij)) */ \
uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ; \
Cx [pC] = z ; \
}
// disable this operator and use the generic case if these conditions hold
#define GB_DISABLE \
(GxB_NO_IDENTITY || GxB_NO_UINT8 || GxB_NO_FC32)
//------------------------------------------------------------------------------
// Cx = op (cast (Ax)): apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_apply__identity_uint8_fc32)
(
uint8_t *Cx, // Cx and Ax may be aliased
const GxB_FC32_t *Ax,
const int8_t *restrict Ab, // A->b if A is bitmap
int64_t anz,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
int64_t p ;
if (Ab == NULL)
{
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
GxB_FC32_t aij = Ax [p] ;
uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ;
Cx [p] = z ;
}
}
else
{
// bitmap case, no transpose; A->b already memcpy'd into C->b
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (p = 0 ; p < anz ; p++)
{
if (!Ab [p]) continue ;
GxB_FC32_t aij = Ax [p] ;
uint8_t z = GB_cast_to_uint8_t ((double) crealf (aij)) ;
Cx [p] = z ;
}
}
return (GrB_SUCCESS) ;
#endif
}
//------------------------------------------------------------------------------
// C = op (cast (A')): transpose, typecast, and apply a unary operator
//------------------------------------------------------------------------------
GrB_Info GB (_unop_tran__identity_uint8_fc32)
(
GrB_Matrix C,
const GrB_Matrix A,
int64_t *restrict *Workspaces,
const int64_t *restrict A_slice,
int nworkspaces,
int nthreads
)
{
#if GB_DISABLE
return (GrB_NO_VALUE) ;
#else
#include "GB_unop_transpose.c"
return (GrB_SUCCESS) ;
#endif
}
#endif
|
MINDSSCbox.h |
void boxfilter(float* input,float* temp1,float* temp2,
int hw, // mind_step
int m,int n,int o){
int sz=m*n*o;
for(int i=0;i<sz;i++){
temp1[i]=input[i];//copy to temp, initialization
}
////y
for(int k=0;k<o;k++){
for(int j=0;j<n;j++){
for(int i=1;i<m;i++){
temp1[i+j*m+k*m*n]+=temp1[(i-1)+j*m+k*m*n]; //add intensity value but index starting delayed
}
}
}
for(int k=0;k<o;k++){ //iterate over all z dimensions
for(int j=0;j<n;j++){ // for x dim do (or y dim?)
for(int i=0;i<(hw+1);i++){ // [0 to hw]
temp2[i+j*m+k*m*n]=temp1[(i+hw)+j*m+k*m*n]; // -0 at beginning, left of sliding index, copy offset y value?
}
for(int i=(hw+1);i<(m-hw);i++){ //[hw+1 to len-hw) ('box' can move free without hitting a border)
temp2[i+j*m+k*m*n]=temp1[(i+hw)+j*m+k*m*n]-temp1[(i-hw-1)+j*m+k*m*n]; //delta (symmetric y val offset + dy / -dy)
}
for(int i=(m-hw);i<m;i++){ // [len-hw to len)
temp2[i+j*m+k*m*n]=temp1[(m-1)+j*m+k*m*n]-temp1[(i-hw-1)+j*m+k*m*n]; //delta (last value of dim (fixed) - negative offseted value
}
}
}
////x
for(int k=0;k<o;k++){
for(int j=1;j<n;j++){
for(int i=0;i<m;i++){
temp2[i+j*m+k*m*n]+=temp2[i+(j-1)*m+k*m*n]; //add intensity value but reversed axis (other)
}
}
}
for(int k=0;k<o;k++){
for(int i=0;i<m;i++){
for(int j=0;j<(hw+1);j++){ //caution, dimensions were switched
temp1[i+j*m+k*m*n]=temp2[i+(j+hw)*m+k*m*n]; //see above, but for next dim (x)
}
for(int j=(hw+1);j<(n-hw);j++){
temp1[i+j*m+k*m*n]=temp2[i+(j+hw)*m+k*m*n]-temp2[i+(j-hw-1)*m+k*m*n];
}
for(int j=(n-hw);j<n;j++){
temp1[i+j*m+k*m*n]=temp2[i+(n-1)*m+k*m*n]-temp2[i+(j-hw-1)*m+k*m*n];
}
}
}
////z
//add intensity value but last reversed axis z
for(int k=1;k<o;k++){
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
temp1[i+j*m+k*m*n]+=temp1[i+j*m+(k-1)*m*n];
}
}
}
// see above, but now for last axis
for(int j=0;j<n;j++){
for(int i=0;i<m;i++){
for(int k=0;k<(hw+1);k++){
input[i+j*m+k*m*n]=temp1[i+j*m+(k+hw)*m*n];
}
for(int k=(hw+1);k<(o-hw);k++){
input[i+j*m+k*m*n]=temp1[i+j*m+(k+hw)*m*n]-temp1[i+j*m+(k-hw-1)*m*n];
}
for(int k=(o-hw);k<o;k++){
input[i+j*m+k*m*n]=temp1[i+j*m+(o-1)*m*n]-temp1[i+j*m+(k-hw-1)*m*n];
}
}
}
}
void imshift(float* input,float* output,int dx,int dy,int dz,int m,int n,int o){
//shift image with preservation of original image values when shifted area is out of bounds
for(int k=0;k<o;k++){ //z
for(int j=0;j<n;j++){ //x
for(int i=0;i<m;i++){ //y , iterate orig image size
if(i+dy>=0 && i+dy<m &&
j+dx>=0 && j+dx<n &&
k+dz>=0 && k+dz<o) //this is something like the min(max) construct
output[i+j*m+k*m*n]=input[i+dy+(j+dx)*m+(k+dz)*m*n]; //lookup displaced values and return
else
output[i+j*m+k*m*n]=input[i+j*m+k*m*n]; //lookup value w/o displacement (just copy), sth like 'inversed mirroring ad edged = normal image at egdes'
}
}
}
}
/*void *distances(void *threadarg)
{
struct mind_data *my_data;
my_data = (struct mind_data *) threadarg;
float* im1=my_data->im1;
float* d1=my_data->d1;
int qs=my_data->qs;
int ind_d1=my_data->ind_d1;
int m=image_m;
int n=image_n;
int o=image_o;*/
void distances(float* im1,float* d1,int m,int n,int o,int qs,int l){
int sz1=m*n*o;
float* w1=new float[sz1];
int len1=6;//not needed
float* temp1=new float[sz1]; //img size temp
float* temp2=new float[sz1]; //img size temp
int dx[6]={+qs,+qs,-qs,+0, +qs,+0}; //redifinition
int dy[6]={+qs,-qs,+0, -qs,+0, +qs}; //redefinition
int dz[6]={0, +0, +qs,+qs,+qs,+qs}; //redefiniton
//dx, dy, dz could be passed directly to this function from upper call to omit redefinitions
imshift(im1,w1,dx[l],dy[l],dz[l],m,n,o);
for(int i=0;i<sz1;i++){
w1[i]=(w1[i]-im1[i])*(w1[i]-im1[i]); //(0-im[i])^2 = squared img dist from intensity val
}
//3 dim box filter = sth. like blur
boxfilter(w1,temp1,temp2,qs,m,n,o);
for(int i=0;i<sz1;i++){
d1[i+l*sz1]=w1[i];
}
delete[] temp1; delete[] temp2; delete[] w1;
}
//__builtin_popcountll(left[i]^right[i]); absolute hamming distances
void descriptor(uint64_t* mindq,float* im1,
int m,int n,int o, //image dims
int qs){ //mind_step (chain values smaller than quantisation chain)
timeval time1,time2;
//MIND with self-similarity context
//unused. is that 6-neighbourhood?
int dx[6]={+qs,+qs,-qs,+0, +qs,+0};
int dy[6]={+qs,-qs,+0, -qs,+0, +qs};
int dz[6]={+0, +0, +qs,+qs,+qs,+qs};
//3^3 shift combinations (+qs,0,-qs) (x-dir, y-dir, z-dir) but only adjacent placed to origin (no diagonals) = 6 combinations
int sx[12]={-qs,+0, -qs,+0, +0, +qs,+0, +0, +0, -qs,+0, +0}; //is that MIND-SSC?
int sy[12]={+0, -qs,+0, +qs,+0, +0, +0, +qs,+0, +0, +0, -qs};
int sz[12]={+0, +0, +0, +0, -qs,+0, -qs,+0, -qs,+0, -qs,+0};
int index[12]={0,0,1,1,2,2,3,3,4,4,5,5};
float sigma=0.75;//1.0;//0.75;//1.5;
int rho=ceil(sigma*1.5)*2+1; // is unused!
int len1=6; //len dx dy dz
const int len2=12; //len sx sy sz
image_d=12;
int d=12;
int sz1=m*n*o;
pthread_t thread1, thread2, thread3;
//============== DISTANCES USING BOXFILTER ===================
float* d1=new float[sz1*len1]; //img_size * (dx,dy,dz)
gettimeofday(&time1, NULL);
#pragma omp parallel for
for(int l=0;l<len1;l++){ //for all dx, dy, dz
//l iterator controls the shift package (dx,dy,dz)
distances(im1,d1,m,n,o,qs,l); //d1 is returned (stored distances per x,y,z,l dimension, 4-dim)
}
gettimeofday(&time2, NULL);
float timeMIND1=time2.tv_sec+time2.tv_usec/1e6-(time1.tv_sec+time1.tv_usec/1e6);
gettimeofday(&time1, NULL);
//quantisation table
const int val=6;
const unsigned long long power=32;
#pragma omp parallel for
for(int k=0;k<o;k++){ //iterate z
//could be moved out of loop
unsigned int tablei[6]={0,1,3,7,15,31}; //lookup table
float compare[val-1];
for(int i=0;i<val-1;i++){
compare[i]=-log((i+1.5f)/val);//compare is const for every iteration
}
//could be moved out of loop
float mind1[12];//is this correct here? -> could be moved before l_iter loop (only needed within l_iter loop)
for(int j=0;j<n;j++){//iterate x
for(int i=0;i<m;i++){ //iterate y
for(int l=0;l<len2;l++){ // iterate (sx,sy,sz) / index[l] package to get 12 mind values
if(i+sy[l]>=0 && i+sy[l]<m
&& j+sx[l]>=0 && j+sx[l]<n
&& k+sz[l]>=0 && k+sz[l]<o){ //min(max) construct
mind1[l]=d1[i+sy[l]+(j+sx[l])*m+(k+sz[l])*m*n+index[l]*sz1]; //mind1 is 1-dim, size=12
//read offseted distance value
}
else{
mind1[l]=d1[i+j*m+k*m*n+index[l]*sz1]; //(sz1=m*n*o)
//read without (sx,sy,sz) ofset but with l=12 layer offset
}
}
float minval=*min_element(mind1,mind1+len2); //get minimum value of all 12 stored mind1 features
float sumnoise=0.0f;
for(int l=0;l<len2;l++){
mind1[l]-=minval; //reset minimum value of mind1 to 0 and lower others accordingly
sumnoise+=mind1[l]; //accumulate
}
float noise1=max(sumnoise/(float)len2,1e-6f); //rescale accumulated mind features
for(int l=0;l<len2;l++){
mind1[l]/=noise1;
}
unsigned long long accum=0;
unsigned long long tabled1=1;
for(int l=0;l<len2;l++){ //iterate over all mind features
//mind1[l]=exp(-mind1[l]);
int mind1val=0;
for(int c=0;c<val-1;c++){ //accumulate over 5 values
mind1val+=compare[c]>mind1[l]?1:0; //count if mind feature is smaller than compare const
}
//int mind1val=min(max((int)(mind1[l]*val-0.5f),0),val-1);
accum+=tablei[mind1val]*tabled1; //*32^l, propably this was done because of casting to long long
tabled1*=power;
}
mindq[i+j*m+k*m*n]=accum; //one mind value for every coordinate xyz
}
}
}
gettimeofday(&time2, NULL);
float timeMIND2=time2.tv_sec+time2.tv_usec/1e6-(time1.tv_sec+time1.tv_usec/1e6);
delete[] d1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.