file_path stringlengths 19 84 | content stringlengths 235 1.29M |
|---|---|
./openacc-vv/serial_loop_reduction_multiply_general.F90 | #ifndef T1
!T1:serial,reduction,combined-constructs,loop,V:2.6-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
REAL(8),DIMENSION(10):: a, b
REAL(8):: reduced, host_reduced
INTEGER:: errors, x, y
errors = 0
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
DO y = 1, LOOPCOUNT
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
reduced = 1
host_reduced = 1
DO x = 1, 10
host_reduced = host_reduced * (a(x) + b(x))
END DO
!$acc data copyin(a(1:10), b(1:10))
!$acc serial loop reduction(*:reduced)
DO x = 1, 10
reduced = reduced * (a(x) + b(x))
END DO
!$acc end data
IF (abs(host_reduced - reduced) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_x_eqv_expr_end.F90 | #ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: randoms
LOGICAL,DIMENSION(LOOPCOUNT, 10):: a !Data
LOGICAL,DIMENSION(LOOPCOUNT):: totals, totals_comparison
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(randoms)
DO x = 1, LOOPCOUNT
DO y = 1, 10
IF (randoms(x, y) > .5) THEN
a(x, y) = .TRUE.
ELSE
a(x, y) = .FALSE.
END IF
END DO
END DO
totals = .FALSE.
totals_comparison = .FALSE.
!$acc data copyin(a(1:LOOPCOUNT,1:10)) copy(totals(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic
totals(x) = totals(x) .EQV. a(x, y)
!$acc end atomic
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
totals_comparison(x) = totals_comparison(x) .EQV. a(x, y)
END DO
END DO
DO x = 1, LOOPCOUNT
IF (totals_comparison(x) .NEQV. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-npb/CG/CG/cg.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB CG code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
//// //
//// The OpenACC C version of the NAS CG code is developed by the //
//// HPCTools Group of University of Houston and derived from the serial //
//// C version developed by SNU and Fortran versions in "NPB3.3-SER" //
//// developed by NAS. //
//// //
//// Permission to use, copy, distribute and modify this software for any //
//// purpose with or without fee is hereby granted. This software is //
//// provided "as is" without express or implied warranty. //
//// //
//// Send comments or suggestions for this OpenACC version to //
//// hpctools@cs.uh.edu //
////
//// Information on NPB 3.3, including the technical report, the original //
//// specifications, source code, results and information on how to submit //
//// new results, is available at: //
//// //
//// http://www.nas.nasa.gov/Software/NPB/ //
//// //
////-------------------------------------------------------------------------//
//
////-------------------------------------------------------------------------//
//// Authors: Rengan Xu, Sunita Chandrasekaran, Barbara Chapman //
////-------------------------------------------------------------------------//
//---------------------------------------------------------------------
// NPB CG OpenACC version
//---------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "globals.h"
#include "randdp.h"
#include "timers.h"
#include "print_results.h"
#include <openacc.h>
//---------------------------------------------------------------------
unsigned int nz = (NA*(NONZER+1)*(NONZER+1));
unsigned int naz = (NA*(NONZER+1));
unsigned int na = NA;
/* common / main_int_mem / */
static int colidx[NZ];
static int rowstr[NA+1];
static int iv[NA];
static int arow[NA];
static int acol[NAZ];
/* common / main_flt_mem / */
static double aelt[NAZ];
static double a[NZ];
static double x[NA+2];
static double z[NA+2];
static double p[NA+2];
static double q[NA+2];
static double r[NA+2];
/* common / partit_size / */
static int naa;
static int nzz;
static int firstrow;
static int lastrow;
static int firstcol;
static int lastcol;
/* common /urando/ */
static double amult;
static double tran;
/* common /timers/ */
static logical timeron;
//---------------------------------------------------------------------
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm);
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[]);
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift);
static void sprnvc(int n, int nz, int nn1, double v[], int iv[]);
static int icnvrt(double x, int ipwr2);
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val);
static int conj_calls = 0;
static int loop_iter = 0;
//---------------------------------------------------------------------
int main(int argc, char *argv[])
{
int i, j, k, it;
int end;
double zeta;
double rnorm;
double norm_temp1, norm_temp2;
double t, mflops, tmax;
char Class;
int verified;
double zeta_verify_value, epsilon, err;
char *t_names[T_last];
acc_init(acc_device_default);
for (i = 0; i < T_last; i++) {
timer_clear(i);
}
FILE *fp;
if ((fp = fopen("timer.flag", "r")) != NULL) {
timeron = true;
t_names[T_init] = "init";
t_names[T_bench] = "benchmk";
t_names[T_conj_grad] = "conjgd";
fclose(fp);
} else {
timeron = false;
}
timer_start(T_init);
firstrow = 0;
lastrow = NA-1;
firstcol = 0;
lastcol = NA-1;
if (NA == 1400 && NONZER == 7 && NITER == 15 && SHIFT == 10) {
Class = 'S';
zeta_verify_value = 8.5971775078648;
} else if (NA == 7000 && NONZER == 8 && NITER == 15 && SHIFT == 12) {
Class = 'W';
zeta_verify_value = 10.362595087124;
} else if (NA == 14000 && NONZER == 11 && NITER == 15 && SHIFT == 20) {
Class = 'A';
zeta_verify_value = 17.130235054029;
} else if (NA == 75000 && NONZER == 13 && NITER == 75 && SHIFT == 60) {
Class = 'B';
zeta_verify_value = 22.712745482631;
} else if (NA == 150000 && NONZER == 15 && NITER == 75 && SHIFT == 110) {
Class = 'C';
zeta_verify_value = 28.973605592845;
} else if (NA == 1500000 && NONZER == 21 && NITER == 100 && SHIFT == 500) {
Class = 'D';
zeta_verify_value = 52.514532105794;
} else if (NA == 9000000 && NONZER == 26 && NITER == 100 && SHIFT == 1500) {
Class = 'E';
zeta_verify_value = 77.522164599383;
} else {
Class = 'U';
}
printf("\n\n NAS Parallel Benchmarks (NPB3.3-ACC-C) - CG Benchmark\n\n");
printf(" Size: %11d\n", NA);
printf(" Iterations: %5d\n", NITER);
printf("\n");
naa = NA;
nzz = NZ;
//---------------------------------------------------------------------
// Inialize random number generator
//---------------------------------------------------------------------
tran = 314159265.0;
amult = 1220703125.0;
zeta = randlc(&tran, amult);
//---------------------------------------------------------------------
//
//---------------------------------------------------------------------
makea(naa, nzz, a, colidx, rowstr,
firstrow, lastrow, firstcol, lastcol,
arow,
(int (*)[NONZER+1])(void*)acol,
(double (*)[NONZER+1])(void*)aelt,
iv);
//---------------------------------------------------------------------
// Note: as a result of the above call to makea:
// values of j used in indexing rowstr go from 0 --> lastrow-firstrow
// values of colidx which are col indexes go from firstcol --> lastcol
// So:
// Shift the col index vals from actual (firstcol --> lastcol )
// to local, i.e., (0 --> lastcol-firstcol)
//---------------------------------------------------------------------
for (j = 0; j < lastrow - firstrow + 1; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
colidx[k] = colidx[k] - firstcol;
}
}
#pragma acc data copyin(colidx[0:nz],a[0:nz], \
rowstr[0:na+1]) \
create(x[0:na+2],z[0:na+2], \
p[0:na+2],q[0:na+2], \
r[0:na+2])
{
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
int na_gangs = NA+1;
#pragma acc kernels loop gang((na_gangs+127)/128) vector(128)
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
end = lastcol - firstcol + 1;
#pragma acc kernels loop gang((end+127)/128) vector(128)
for (j = 0; j < end; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = 0.0;
p[j] = 0.0;
}
zeta = 0.0;
//---------------------------------------------------------------------
//---->
// Do one iteration untimed to init all code and data page tables
//----> (then reinit, start timing, to niter its)
//---------------------------------------------------------------------
for (it = 1; it <= 1; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma acc parallel loop num_gangs((end+127)/128) num_workers(4) \
vector_length(32) reduction(+:norm_temp2)
for (j = 0; j < end; j++) {
//norm_temp1 = norm_temp1 + x[j] * z[j];
norm_temp2 = norm_temp2 + z[j] * z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma acc kernels loop gang((end+127)/128) vector(128)
for (j = 0; j < end; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of do one iteration untimed
//---------------------------------------------------------------------
// set starting vector to (1, 1, .... 1)
//---------------------------------------------------------------------
na_gangs = NA+1;
#pragma acc kernels loop gang((na_gangs+127)/128) vector(128)
for (i = 0; i < NA+1; i++) {
x[i] = 1.0;
}
zeta = 0.0;
timer_stop(T_init);
printf(" Initialization time = %15.3f seconds\n", timer_read(T_init));
timer_start(T_bench);
//---------------------------------------------------------------------
//---->
// Main Iteration for inverse power method
//---->
//---------------------------------------------------------------------
for (it = 1; it <= NITER; it++) {
//---------------------------------------------------------------------
// The call to the conjugate gradient routine:
//---------------------------------------------------------------------
conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm);
//---------------------------------------------------------------------
// zeta = shift + 1/(x.z)
// So, first: (x.z)
// Also, find norm of z
// So, first: (z.z)
//---------------------------------------------------------------------
norm_temp1 = 0.0;
norm_temp2 = 0.0;
#pragma acc parallel loop gang worker vector num_gangs((end+127)/128) num_workers(4) \
vector_length(32) reduction(+:norm_temp1,norm_temp2)
for (j = 0; j < end; j++) {
norm_temp1 = norm_temp1 + x[j]*z[j];
norm_temp2 = norm_temp2 + z[j]*z[j];
}
norm_temp2 = 1.0 / sqrt(norm_temp2);
zeta = SHIFT + 1.0 / norm_temp1;
if (it == 1)
printf("\n iteration ||r|| zeta\n");
printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta);
//---------------------------------------------------------------------
// Normalize z to obtain x
//---------------------------------------------------------------------
#pragma acc kernels loop gang((end+127)/128) vector(128)
for (j = 0; j < end; j++) {
x[j] = norm_temp2 * z[j];
}
} // end of main iter inv pow meth
timer_stop(T_bench);
}/*end acc data*/
//---------------------------------------------------------------------
// End of timed section
//---------------------------------------------------------------------
t = timer_read(T_bench);
printf(" Benchmark completed\n");
epsilon = 1.0e-10;
if (Class != 'U') {
err = fabs(zeta - zeta_verify_value) / zeta_verify_value;
if (err <= epsilon) {
verified = true;
printf(" VERIFICATION SUCCESSFUL\n");
printf(" Zeta is %20.13E\n", zeta);
printf(" Error is %20.13E\n", err);
} else {
verified = false;
printf(" VERIFICATION FAILED\n");
printf(" Zeta %20.13E\n", zeta);
printf(" The correct zeta is %20.13E\n", zeta_verify_value);
}
} else {
verified = false;
printf(" Problem size unknown\n");
printf(" NO VERIFICATION PERFORMED\n");
}
if (t != 0.0) {
mflops = (double)(2*NITER*NA)
* (3.0+(double)(NONZER*(NONZER+1))
+ 25.0*(5.0+(double)(NONZER*(NONZER+1)))
+ 3.0) / t / 1000000.0;
} else {
mflops = 0.0;
}
print_results("CG", Class, NA, 0, 0,
NITER, t,
mflops, " floating point",
verified, NPBVERSION, COMPILETIME,
CS1, CS2, CS3, CS4, CS5, CS6, CS7);
//---------------------------------------------------------------------
// More timers
//---------------------------------------------------------------------
if (timeron) {
tmax = timer_read(T_bench);
if (tmax == 0.0) tmax = 1.0;
printf(" SECTION Time (secs)\n");
for (i = 0; i < T_last; i++) {
t = timer_read(i);
if (i == T_init) {
printf(" %8s:%9.3f\n", t_names[i], t);
} else {
printf(" %8s:%9.3f (%6.2f%%)\n", t_names[i], t, t*100.0/tmax);
if (i == T_conj_grad) {
t = tmax - t;
printf(" --> %8s:%9.3f (%6.2f%%)\n", "rest", t, t*100.0/tmax);
}
}
}
}
acc_shutdown(acc_device_default);
printf("conj calls=%d, loop iter = %d. \n", conj_calls, loop_iter);
return 0;
}
//---------------------------------------------------------------------
// Floaging point arrays here are named as in NPB1 spec discussion of
// CG algorithm
//---------------------------------------------------------------------
static void conj_grad(int colidx[],
int rowstr[],
double x[],
double z[],
double a[],
double p[],
double q[],
double r[],
double *rnorm)
{
int j, k,tmp1,tmp2,tmp3;
int end;
int cgit, cgitmax = 25;
double d, sum, rho, rho0, alpha, beta;
double sum_array[NA+2];
conj_calls ++;
rho = 0.0;
unsigned int num_gangs = 0;
#pragma acc data present(colidx[0:nz], \
rowstr[0:na+1], \
x[0:na+2],z[0:na+2], \
a[0:nz],p[0:na+2], \
q[0:na+2],r[0:na+2])
{
//---------------------------------------------------------------------
// Initialize the CG algorithm:
//---------------------------------------------------------------------
#pragma acc kernels loop gang((naa+127)/128) vector(128) independent
for (j = 0; j < naa; j++) {
q[j] = 0.0;
z[j] = 0.0;
r[j] = x[j];
p[j] = r[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
//num_gangs = (lastcol - firstcol + 1)/128;
#pragma acc parallel loop gang worker vector num_gangs((lastcol-firstcol+1+127)/128) \
num_workers(4) vector_length(32) reduction(+:rho)
for (j = 0; j < lastcol - firstcol + 1; j++) {
rho = rho + r[j]*r[j];
}
//---------------------------------------------------------------------
//---->
// The conj grad iteration loop
//---->
//---------------------------------------------------------------------
//#pragma acc kernels loop private(cgit,j,k)
for (cgit = 1; cgit <= cgitmax; cgit++) {
//#pragma acc update host(p[0:NA+2])
//---------------------------------------------------------------------
// q = A.p
// The partition submatrix-vector multiply: use workspace w
//---------------------------------------------------------------------
//
// NOTE: this version of the multiply is actually (slightly: maybe %5)
// faster on the sp2 on 16 nodes than is the unrolled-by-2 version
// below. On the Cray t3d, the reverse is true, i.e., the
// unrolled-by-two version is some 10% faster.
// The unrolled-by-8 version below is significantly faster
// on the Cray t3d - overall speed of code is 1.5 times faster.
/*
for (j = 0; j < lastrow - firstrow + 1; j++) {
sum_array[j]=0.0;
}
for (j = 0; j < lastrow - firstrow + 1; j++) {
tmp1=rowstr[j];
tmp2=rowstr[j+1];
for (k = tmp1; k < tmp2; k++) {
tmp3=colidx[k];
sum_array[j] = sum_array[j] + a[k]*p[tmp3];
}
q[j] = sum_array[j];
}
*/
loop_iter ++;
//num_gangs = (lastrow - firstrow + 1)/128;
end = lastrow - firstrow + 1;
#pragma acc parallel num_gangs(end) num_workers(4) vector_length(32)
{
#pragma acc loop gang
for (j = 0; j < end; j++) {
tmp1 = rowstr[j];
tmp2 = rowstr[j+1];
sum = 0.0;
#pragma acc loop worker vector reduction(+:sum)
for (k = tmp1; k < tmp2; k++) {
tmp3 = colidx[k];
sum = sum + a[k]*p[tmp3];
}
q[j] = sum;
}
}
//---------------------------------------------------------------------
// Obtain p.q
//---------------------------------------------------------------------
d = 0.0;
end = lastcol - firstcol + 1;
#pragma acc parallel num_gangs((end+127)/128) num_workers(4) vector_length(32)
{
#pragma acc loop gang worker vector reduction(+:d)
for (j = 0; j < end; j++) {
d = d + p[j]*q[j];
}
}
//---------------------------------------------------------------------
// Obtain alpha = rho / (p.q)
//---------------------------------------------------------------------
alpha = rho / d;
//---------------------------------------------------------------------
// Save a temporary of rho
//---------------------------------------------------------------------
rho0 = rho;
//---------------------------------------------------------------------
// Obtain z = z + alpha*p
// and r = r - alpha*q
//---------------------------------------------------------------------
rho = 0.0;
#pragma acc kernels loop gang((end+1023)/1024) vector(1024) independent
for (j = 0; j < end; j++) {
z[j] = z[j] + alpha*p[j];
r[j] = r[j] - alpha*q[j];
}
//---------------------------------------------------------------------
// rho = r.r
// Now, obtain the norm of r: First, sum squares of r elements locally...
//---------------------------------------------------------------------
#pragma acc parallel num_gangs((end+127)/128) num_workers(4) vector_length(32)
{
#pragma acc loop gang worker vector reduction(+:rho)
for (j = 0; j < end; j++)
{
rho = rho + r[j]*r[j];
}
}
//---------------------------------------------------------------------
// Obtain beta:
//---------------------------------------------------------------------
beta = rho / rho0;
//---------------------------------------------------------------------
// p = r + beta*p
//---------------------------------------------------------------------
#pragma acc kernels loop gang((end+127)/128) vector(128) independent
for (j = 0; j < end; j++) {
p[j] = r[j] + beta*p[j];
}
} // end of do cgit=1,cgitmax
//---------------------------------------------------------------------
// Compute residual norm explicitly: ||r|| = ||x - A.z||
// First, form A.z
// The partition submatrix-vector multiply
//---------------------------------------------------------------------
end = lastrow - firstrow + 1;
//num_gangs = end/128;
#pragma acc parallel loop gang num_gangs(end) \
num_workers(4) vector_length(32)
for (j = 0; j < end; j++) {
tmp1=rowstr[j];
tmp2=rowstr[j+1];
d = 0.0;
#pragma acc loop worker vector reduction(+:d)
for (k = tmp1; k < tmp2; k++) {
tmp3=colidx[k];
d = d + a[k]*z[tmp3];
}
r[j] = d;
}
//---------------------------------------------------------------------
// At this point, r contains A.z
//---------------------------------------------------------------------
sum = 0.0;
//num_gangs = (lastcol-firstcol+1)/128;
#pragma acc parallel loop gang worker vector \
num_gangs((lastcol-firstcol+1+127)/128) \
num_workers(4) vector_length(32) \
reduction(+:sum)
for (j = 0; j < lastcol-firstcol+1; j++) {
d = x[j] - r[j];
sum = sum + d*d;
}
}/*end acc data*/
*rnorm = sqrt(sum);
}
//---------------------------------------------------------------------
// generate the test problem for benchmark 6
// makea generates a sparse matrix with a
// prescribed sparsity distribution
//
// parameter type usage
//
// input
//
// n i number of cols/rows of matrix
// nz i nonzeros as declared array size
// rcond r*8 condition number
// shift r*8 main diagonal shift
//
// output
//
// a r*8 array for nonzeros
// colidx i col indices
// rowstr i row pointers
//
// workspace
//
// iv, arow, acol i
// aelt r*8
//---------------------------------------------------------------------
static void makea(int n,
int nz,
double a[],
int colidx[],
int rowstr[],
int firstrow,
int lastrow,
int firstcol,
int lastcol,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int iv[])
{
int iouter, ivelt, nzv, nn1;
int ivc[NONZER+1];
double vc[NONZER+1];
//---------------------------------------------------------------------
// nonzer is approximately (int(sqrt(nnza /n)));
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// nn1 is the smallest power of two not less than n
//---------------------------------------------------------------------
nn1 = 1;
do {
nn1 = 2 * nn1;
} while (nn1 < n);
//---------------------------------------------------------------------
// Generate nonzero positions and save for the use in sparse.
//---------------------------------------------------------------------
for (iouter = 0; iouter < n; iouter++) {
nzv = NONZER;
sprnvc(n, nzv, nn1, vc, ivc);
vecset(n, vc, ivc, &nzv, iouter+1, 0.5);
arow[iouter] = nzv;
for (ivelt = 0; ivelt < nzv; ivelt++) {
acol[iouter][ivelt] = ivc[ivelt] - 1;
aelt[iouter][ivelt] = vc[ivelt];
}
}
//---------------------------------------------------------------------
// ... make the sparse matrix from list of elements with duplicates
// (iv is used as workspace)
//---------------------------------------------------------------------
sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol,
aelt, firstrow, lastrow,
iv, RCOND, SHIFT);
}
//---------------------------------------------------------------------
// rows range from firstrow to lastrow
// the rowstr pointers are defined for nrows = lastrow-firstrow+1 values
//---------------------------------------------------------------------
static void sparse(double a[],
int colidx[],
int rowstr[],
int n,
int nz,
int nozer,
int arow[],
int acol[][NONZER+1],
double aelt[][NONZER+1],
int firstrow,
int lastrow,
int nzloc[],
double rcond,
double shift)
{
int nrows;
//---------------------------------------------------
// generate a sparse matrix from a list of
// [col, row, element] tri
//---------------------------------------------------
int i, j, j1, j2, nza, k, kk, nzrow, jcol;
double size, scale, ratio, va;
logical cont40;
//---------------------------------------------------------------------
// how many rows of result
//---------------------------------------------------------------------
nrows = lastrow - firstrow + 1;
//---------------------------------------------------------------------
// ...count the number of triples in each row
//---------------------------------------------------------------------
for (j = 0; j < nrows+1; j++) {
rowstr[j] = 0;
}
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza] + 1;
rowstr[j] = rowstr[j] + arow[i];
}
}
rowstr[0] = 0;
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] + rowstr[j-1];
}
nza = rowstr[nrows] - 1;
//---------------------------------------------------------------------
// ... rowstr(j) now is the location of the first nonzero
// of row j of a
//---------------------------------------------------------------------
if (nza > nz) {
printf("Space for matrix elements exceeded in sparse\n");
printf("nza, nzmax = %d, %d\n", nza, nz);
exit(EXIT_FAILURE);
}
//---------------------------------------------------------------------
// ... preload data pages
//---------------------------------------------------------------------
for (j = 0; j < nrows; j++) {
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
a[k] = 0.0;
colidx[k] = -1;
}
nzloc[j] = 0;
}
//---------------------------------------------------------------------
// ... generate actual values by summing duplicates
//---------------------------------------------------------------------
size = 1.0;
ratio = pow(rcond, (1.0 / (double)(n)));
for (i = 0; i < n; i++) {
for (nza = 0; nza < arow[i]; nza++) {
j = acol[i][nza];
scale = size * aelt[i][nza];
for (nzrow = 0; nzrow < arow[i]; nzrow++) {
jcol = acol[i][nzrow];
va = aelt[i][nzrow] * scale;
//--------------------------------------------------------------------
// ... add the identity * rcond to the generated matrix to bound
// the smallest eigenvalue from below by rcond
//--------------------------------------------------------------------
if (jcol == j && j == i) {
va = va + rcond - shift;
}
cont40 = false;
for (k = rowstr[j]; k < rowstr[j+1]; k++) {
if (colidx[k] > jcol) {
//----------------------------------------------------------------
// ... insert colidx here orderly
//----------------------------------------------------------------
for (kk = rowstr[j+1]-2; kk >= k; kk--) {
if (colidx[kk] > -1) {
a[kk+1] = a[kk];
colidx[kk+1] = colidx[kk];
}
}
colidx[k] = jcol;
a[k] = 0.0;
cont40 = true;
break;
} else if (colidx[k] == -1) {
colidx[k] = jcol;
cont40 = true;
break;
} else if (colidx[k] == jcol) {
//--------------------------------------------------------------
// ... mark the duplicated entry
//--------------------------------------------------------------
nzloc[j] = nzloc[j] + 1;
cont40 = true;
break;
}
}
if (cont40 == false) {
printf("internal error in sparse: i=%d\n", i);
exit(EXIT_FAILURE);
}
a[k] = a[k] + va;
}
}
size = size * ratio;
}
//---------------------------------------------------------------------
// ... remove empty entries and generate final results
//---------------------------------------------------------------------
for (j = 1; j < nrows; j++) {
nzloc[j] = nzloc[j] + nzloc[j-1];
}
for (j = 0; j < nrows; j++) {
if (j > 0) {
j1 = rowstr[j] - nzloc[j-1];
} else {
j1 = 0;
}
j2 = rowstr[j+1] - nzloc[j];
nza = rowstr[j];
for (k = j1; k < j2; k++) {
a[k] = a[nza];
colidx[k] = colidx[nza];
nza = nza + 1;
}
}
for (j = 1; j < nrows+1; j++) {
rowstr[j] = rowstr[j] - nzloc[j-1];
}
nza = rowstr[nrows] - 1;
}
//---------------------------------------------------------------------
// generate a sparse n-vector (v, iv)
// having nzv nonzeros
//
// mark(i) is set to 1 if position i is nonzero.
// mark is all zero on entry and is reset to all zero before exit
// this corrects a performance bug found by John G. Lewis, caused by
// reinitialization of mark on every one of the n calls to sprnvc
//---------------------------------------------------------------------
static void sprnvc(int n, int nz, int nn1, double v[], int iv[])
{
int nzv, ii, i;
double vecelt, vecloc;
nzv = 0;
while (nzv < nz) {
vecelt = randlc(&tran, amult);
//---------------------------------------------------------------------
// generate an integer between 1 and n in a portable manner
//---------------------------------------------------------------------
vecloc = randlc(&tran, amult);
i = icnvrt(vecloc, nn1) + 1;
if (i > n) continue;
//---------------------------------------------------------------------
// was this integer generated already?
//---------------------------------------------------------------------
logical was_gen = false;
for (ii = 0; ii < nzv; ii++) {
if (iv[ii] == i) {
was_gen = true;
break;
}
}
if (was_gen) continue;
v[nzv] = vecelt;
iv[nzv] = i;
nzv = nzv + 1;
}
}
//---------------------------------------------------------------------
// scale a double precision number x in (0,1) by a power of 2 and chop it
//---------------------------------------------------------------------
static int icnvrt(double x, int ipwr2)
{
return (int)(ipwr2 * x);
}
//---------------------------------------------------------------------
// set ith element of sparse vector (v, iv) with
// nzv nonzeros to val
//---------------------------------------------------------------------
static void vecset(int n, double v[], int iv[], int *nzv, int i, double val)
{
int k;
logical set;
set = false;
for (k = 0; k < *nzv; k++) {
if (iv[k] == i) {
v[k] = val;
set = true;
}
}
if (set == false) {
v[*nzv] = val;
iv[*nzv] = i;
*nzv = *nzv + 1;
}
}
|
./openacc-vv/wait_if.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,wait,async,if,V:2.7-3.3
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
real_t *f = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = rand() / (real_t)(RAND_MAX / 10);
f[x] = 0.0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n], e[0:n]) create(c[0:n], f[0:n])
{
#pragma acc parallel async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel async(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
f[x] = d[x] + e[x];
}
}
#pragma acc update host(c[0:n], f[0:n]) wait(1, 2) if(true)
}
for (int x = 0; x < n; ++x){
if (abs(c[x] - (a[x] + b[x])) > PRECISION){
err++;
}
if (abs(f[x] - (d[x] + e[x])) > PRECISION){
err++;
}
}
return err;
}
#endif
#ifndef T2
//T2:parallel,wait,async,if,V:2.7-3.3
int test2(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
real_t *f = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = rand() / (real_t)(RAND_MAX / 10);
f[x] = 0.0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n], e[0:n]) create(c[0:n], f[0:n])
{
#pragma acc parallel async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel async(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
f[x] = d[x] + e[x];
}
}
#pragma acc update host(c[0:n], f[0:n]) wait(1) if(true)
#pragma acc update host(c[0:n], f[0:n]) wait(2) if(true)
}
for (int x = 0; x < n; ++x){
if (abs(c[x] - (a[x] + b[x])) > PRECISION){
err++;
}
if (abs(f[x] - (d[x] + e[x])) > PRECISION){
err++;
}
}
return err;
}
#endif
#ifndef T3
//T3:parallel,wait,async,if,V:2.7-3.3
int test3(){
int err = 0;
srand(time(NULL));
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
real_t *f = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = rand() / (real_t)(RAND_MAX / 10);
f[x] = 0.0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n], e[0:n]) create(c[0:n], f[0:n])
{
#pragma acc parallel async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel async(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
f[x] = d[x] + e[x];
}
}
#pragma acc update host(c[0:n], f[0:n]) wait(1, 2) if(false)
}
for (int x = 0; x < n; ++x){
if (c[x] > PRECISION){
err++;
}
if (f[x] > PRECISION){
err++;
}
}
return err;
}
#endif
#ifndef T4
//T4:parallel,wait,async,if,V:2.7-3.3
int test4(){
int err = 0;
srand(time(NULL));
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
real_t *f = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = rand() / (real_t)(RAND_MAX / 10);
f[x] = 0.0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n], e[0:n]) create(c[0:n], f[0:n])
{
#pragma acc parallel async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel async(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
f[x] = d[x] + e[x];
}
}
#pragma acc update host(c[0:n], f[0:n]) wait(1) if(false)
#pragma acc update host(c[0:n], f[0:n]) wait(2) if(false)
}
for (int x = 0; x < n; ++x){
if (c[x] > PRECISION){
err++;
}
if (f[x] > PRECISION){
err++;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test1();
}
if (failed){
failcode += (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test2();
}
if (failed){
failcode += (1 << 1);
}
#endif
#ifndef T3
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test3();
}
if (failed){
failcode += (1 << 2);
}
#endif
#ifndef T4
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test4();
}
if (failed){
failcode += (1 << 3);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_expr_minus_x.cpp | #include "acc_testsuite.h"
bool possible_result(real_t * remaining_combinations, int length, real_t current_value, real_t test_value){
if (length == 0){
if (fabs(current_value - test_value) > PRECISION){
return true;
}
else {
return false;
}
}
real_t * passed = new real_t[(length - 1)];
for (int x = 0; x < length; ++x){
for (int y = 0; y < x; ++y){
passed[y] = remaining_combinations[y];
}
for (int y = x + 1; y < length; ++y){
passed[y - 1] = remaining_combinations[y];
}
if (possible_result(passed, length - 1, remaining_combinations[x] - current_value, test_value)){
delete[] passed;
return true;
}
}
delete[] passed;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *totals = new real_t[((n/10) + 1)];
int indexer = 0;
real_t * passed = new real_t[10];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < (n/10) + 1; ++x){
totals[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:(n/10) + 1])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic
totals[x%((int) (n/10) + 1)] = a[x] - totals[x%((int) (n/10) + 1)];
}
}
}
for (int x = 0; x < (n/10) + 1; ++x){
indexer = x;
while (indexer < n){
passed[indexer/((int) (n/10) + 1)] = a[indexer];
indexer += (n/10) + 1;
}
if (!(possible_result(passed, 10, 0, totals[x]))){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/parallel_reduction.F90 | #ifndef T1
!T1:parallel,reduction,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a !Data
REAL(8) :: results = 0
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
!$acc data copyin(a(1:LOOPCOUNT))
!$acc parallel reduction(+:results)
!$acc loop
DO x = 1, LOOPCOUNT
results = results + a(x)
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
results = results - a(x)
END DO
IF (abs(results) .gt. PRECISION) THEN
errors = errors + 1
END IF
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_plus_equals.c | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
real_t *totals = (real_t *)malloc((n/10 + 1) * sizeof(real_t));
real_t *totals_comparison = (real_t *)malloc((n/10 + 1) * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 0;
totals_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(totals[0:n/10 + 1])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic
totals[x%(n/10 + 1)] += a[x] * b[x];
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x%(n/10 + 1)] += a[x] * b[x];
}
for (int x = 0; x < n/10 + 1; ++x){
if (fabs(totals_comparison[x] - totals[x]) > (n/10 + 1) * PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_update_min_expr_list_x_end.F90 | #ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b !Data
REAL(8),DIMENSION(LOOPCOUNT/10 + 1):: totals, totals_comparison
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
totals = 1
totals_comparison = 1
!$acc data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT)) copy(totals(1:(LOOPCOUNT/10 + 1)))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
!$acc atomic update
totals(MOD(x, LOOPCOUNT/10 + 1) + 1) = min(a(x), b(x), totals(MOD(x, LOOPCOUNT/10 + 1) + 1))
!$acc end atomic
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
totals_comparison(MOD(x, LOOPCOUNT/10 + 1) + 1) = min(totals_comparison(MOD(x, LOOPCOUNT/10 + 1) + 1), a(x), b(x))
END DO
DO x = 1, LOOPCOUNT/10 + 1
IF (totals_comparison(x) .NE. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/exit_data_copyout_reference_counts.F90 | #ifndef T1
!T1:data,executable-data,devonly,construct-independent,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
INTEGER,DIMENSION(1):: devtest
devtest(1) = 1
!$acc enter data copyin(devtest(1:1))
!$acc parallel present(devtest(1:1))
devtest(1) = 0
!$acc end parallel
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
IF (devtest(1) .eq. 1) THEN
!$acc enter data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT), c(1:LOOPCOUNT))
!$acc data copyin(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = c(x) + a(x) + b(x)
END DO
!$acc end parallel
!$acc exit data delete(a(1:LOOPCOUNT), b(1:LOOPCOUNT)) copyout(c(1:LOOPCOUNT))
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(c(x)) .gt. PRECISION) THEN
errors = errors + 1
EXIT
END IF
END DO
END IF
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
#ifndef T2
!T2:data,executable-data,devonly,construct-independent,V:2.0-2.7
LOGICAL FUNCTION test2()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
INTEGER,DIMENSION(1):: devtest
devtest(1) = 1
!$acc enter data copyin(devtest(1:1))
!$acc parallel present(devtest(1:1))
devtest(1) = 0
!$acc end parallel
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc enter data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT), c(1:LOOPCOUNT))
!$acc data copyin(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = c(x) + a(x) + b(x)
END DO
!$acc end parallel
!$acc end data
!$acc exit data copyout(c(1:LOOPCOUNT)) delete(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (a(x) + b(x))) .gt. PRECISION) THEN
errors = errors + 2
EXIT
END IF
END DO
IF (errors .eq. 0) THEN
test2 = .FALSE.
ELSE
test2 = .TRUE.
END IF
END
#endif
#ifndef T3
!T3:data,executable-data,devonly,construct-independent,V:2.0-2.7
LOGICAL FUNCTION test3()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
INTEGER,DIMENSION(1):: devtest
devtest(1) = 1
!$acc enter data copyin(devtest(1:1))
!$acc parallel present(devtest(1:1))
devtest(1) = 0
!$acc end parallel
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc enter data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT), c(1:LOOPCOUNT))
!$acc enter data copyin(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = c(x) + a(x) + b(x)
END DO
!$acc end parallel
!$acc exit data delete(c(1:LOOPCOUNT))
!$acc exit data delete(a(1:LOOPCOUNT), b(1:LOOPCOUNT)) copyout(c(1:LOOPCOUNT))
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (a(x) + b(x))) .gt. PRECISION) THEN
errors = errors + 4
EXIT
END IF
END DO
IF (errors .eq. 0) THEN
test3 = .FALSE.
ELSE
test3 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
#ifndef T2
LOGICAL :: test2
#endif
#ifndef T3
LOGICAL :: test3
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
#ifndef T2
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test2()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 1
failed = .FALSE.
END IF
#endif
#ifndef T3
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test3()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 2
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_update_preincrement.c | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
int *distribution = (int *)malloc(10 * sizeof(int));
int *distribution_comparison = (int *)malloc(10 * sizeof(int));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < 10; ++x){
distribution[x] = 0;
distribution_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(distribution[0:10])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc loop
for (int y = 0; y < n; ++y){
#pragma acc atomic update
++distribution[(int) (a[x]*b[y]/10)];
}
}
}
}
for (int x = 0; x < n; ++x){
for (int y = 0; y < n; ++y){
distribution_comparison[(int) (a[x]*b[y]/10)]++;
}
}
for (int x = 0; x < 10; ++x){
if (distribution_comparison[x] != distribution[x]){
err += 1;
break;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./SPECaccel/benchspec/ACCEL/557.pcsp/src/error.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB SP code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
#include "header.h"
#include <math.h>
//---------------------------------------------------------------------
// this function computes the norm of the difference between the
// computed solution and the exact solution
//---------------------------------------------------------------------
void error_norm(double rms[5])
{
int i, j, k, m, d;
double xi, eta, zeta, u_exact[5], add;
for (m = 0; m < 5; m++) {
rms[m] = 0.0;
}
for (k = 0; k <= grid_points[2]-1; k++) {
zeta = (double)k * dnzm1;
for (j = 0; j <= grid_points[1]-1; j++) {
eta = (double)j * dnym1;
for (i = 0; i <= grid_points[0]-1; i++) {
xi = (double)i * dnxm1;
exact_solution(xi, eta, zeta, u_exact);
for (m = 0; m < 5; m++) {
add = u[m][k][j][i]-u_exact[m];
rms[m] = rms[m] + add*add;
}
}
}
}
for (m = 0; m < 5; m++) {
for (d = 0; d < 3; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
void rhs_norm(double rms[5])
{
int i, j, k, d, m;
double add;
double rms0, rms1,rms2,rms3,rms4;
rms0=0.0;
rms1=0.0;
rms2=0.0;
rms3=0.0;
rms4=0.0;
#pragma omp target map(tofrom: rms0,rms1,rms2,rms3,rms4) //present(rhs)
#ifdef SPEC_USE_INNER_SIMD
#pragma omp teams distribute parallel for collapse(2) private(i) reduction(+:rms0,rms1,rms2,rms3,rms4)
#else
#pragma omp teams distribute parallel for simd collapse(3) reduction(+:rms0,rms1,rms2,rms3,rms4) private(add)
#endif
for (k = 1; k <= nz2; k++) {
for (j = 1; j <= ny2; j++) {
#ifdef SPEC_USE_INNER_SIMD
#pragma omp simd reduction(+:rms0,rms1,rms2,rms3,rms4) private(add)
#endif
for (i = 1; i <= nx2; i++) {
add = rhs[0][k][j][i];
rms0 = rms0 + add*add;
add = rhs[1][k][j][i];
rms1 = rms1 + add*add;
add = rhs[2][k][j][i];
rms2 = rms2 + add*add;
add = rhs[3][k][j][i];
rms3 = rms3 + add*add;
add = rhs[4][k][j][i];
rms4 = rms4 + add*add;
}
}
}
rms[0]=rms0;
rms[1]=rms1;
rms[2]=rms2;
rms[3]=rms3;
rms[4]=rms4;
for (m = 0; m < 5; m++) {
for (d = 0; d < 3; d++) {
rms[m] = rms[m] / (double)(grid_points[d]-2);
}
rms[m] = sqrt(rms[m]);
}
}
|
./openacc-vv/serial_loop_reduction_bitxor_loop.c | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,loop,reduction,combined-constructs,V:2.6-3.2
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(10 * sizeof(unsigned int));
unsigned int temp = 0;
for (int x = 0; x < 10*n; ++x){
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
a[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
}
for (int x = 0; x < 10; ++x){
c[x] = 0;
}
#pragma acc data copyin(a[0:10*n]) copy(b[0:10*n], c[0:10])
{
#pragma acc serial loop private(temp)
for (int x = 0; x < 10; ++x){
temp = 0;
#pragma acc loop worker reduction(^:temp)
for (int y = 0; y < n; ++y){
temp = temp ^ a[x * n + y];
}
c[x] = temp;
#pragma acc loop worker
for (int y = 0; y < n; ++y){
b[x * n + y] = b[x * n + y] + c[x];
}
}
}
for (int x = 0; x < 10; ++x){
temp = 0;
for (int y = 0; y < n; ++y){
temp = temp ^ a[x * n + y];
}
if (temp != c[x]){
err += 1;
}
for (int y = 0; y < n; ++y){
if (b[x * n + y] != b_copy[x * n + y] + c[x]){
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/serial_loop_seq.c | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,loop,combined-constructs,V:2.6-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * b = (real_t *)malloc(n * sizeof(real_t));
real_t temp = 0.0;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
}
#pragma acc data copyin(a[0:n]) copy(b[0:n])
{
#pragma acc serial loop seq
for (int x = 1; x < n; ++x){
b[x] = b[x-1] + a[x];
}
}
for (int x = 1; x < n; ++x){
temp += a[x];
if (fabs(b[x] - temp) > PRECISION){
err = 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/serial_loop_reduction_bitor_general.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,loop,reduction,combined-constructs,V:2.6-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(n * sizeof(unsigned int));
unsigned int b = 0;
unsigned int host_b;
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
for (int x = 0; x < n; ++x){
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX > false_margin){
for (int z = 0; z < y; ++z){
temp *= 2;
}
a[x] += temp;
temp = 1;
}
}
}
#pragma acc data copyin(a[0:n])
{
#pragma acc serial loop reduction(|:b)
for (int x = 0; x < n; ++x){
b = b | a[x];
}
}
host_b = a[0];
for (int x = 1; x < n; ++x){
host_b = host_b | a[x];
}
if (b != host_b){
err = 1;
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./PhysiCell_GPU/sample_projects/virus_macrophage/config/PhysiCell_settings.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
/*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2019, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
-->
<!--
<user_details />
-->
<PhysiCell_settings version="devel-version">
<domain>
<x_min>-500</x_min>
<x_max>500</x_max>
<y_min>-500</y_min>
<y_max>500</y_max>
<z_min>-10</z_min>
<z_max>10</z_max>
<dx>20</dx>
<dy>20</dy>
<dz>20</dz>
<use_2D>true</use_2D>
</domain>
<overall>
<max_time units="min">1440</max_time> <!-- 5 days * 24 h * 60 min -->
<time_units>min</time_units>
<space_units>micron</space_units>
</overall>
<parallel>
<omp_num_threads>4</omp_num_threads>
</parallel>
<save>
<folder>output</folder> <!-- use . for root -->
<full_data>
<interval units="min">60</interval>
<enable>true</enable>
</full_data>
<SVG>
<interval units="min">10</interval>
<enable>true</enable>
</SVG>
<legacy_data>
<enable>false</enable>
</legacy_data>
</save>
<microenvironment_setup>
<variable name="virus" units="particles/micron^3" ID="0">
<physical_parameter_set>
<diffusion_coefficient units="micron^2/min">1000</diffusion_coefficient>
<decay_rate units="1/min">0</decay_rate>
</physical_parameter_set>
<initial_condition units="particles/micron^3">0</initial_condition>
<Dirichlet_boundary_condition units="particles/micron^3" enabled="false">0</Dirichlet_boundary_condition>
</variable>
<options>
<calculate_gradients>true</calculate_gradients>
<track_internalized_substrates_in_each_agent>true</track_internalized_substrates_in_each_agent>
<!-- not yet supported -->
<initial_condition type="matlab" enabled="false">
<filename>./config/initial.mat</filename>
</initial_condition>
<!-- not yet supported -->
<dirichlet_nodes type="matlab" enabled="false">
<filename>./config/dirichlet.mat</filename>
</dirichlet_nodes>
</options>
</microenvironment_setup>
<user_parameters>
<random_seed type="int" units="dimensionless" hidden="true">0</random_seed>
<!-- example parameters from the template -->
<!-- virus properties -->
<viral_replication_rate type="double" units="viral particles/min" description="rate at which infected cells create new viral particles">0.4167</viral_replication_rate>
<min_virion_count type="double" units="none" description="minimum number of virions to start replication">1</min_virion_count>
<burst_virion_count type="double" units="none" description="max virion load, where infected cells lyse to release viral particles">100</burst_virion_count>
<viral_internalization_rate type="double" units="1/min" description="internalization rate for viral particles">10</viral_internalization_rate>
<viral_diffusion_coefficient type="double" units="micron^2/min" description="diffusion coefficient for viral particles">1e3</viral_diffusion_coefficient>
<number_of_infected_cells type="int" units="none" description="initial number of infected cells">1</number_of_infected_cells>
<!-- virus diffusion coefficient ~ 1e3 micron^2/min : https://bionumbers.hms.harvard.edu/bionumber.aspx?id=105894 -->
<!-- macrophage properties -->
<number_of_macrophages type="int" units="none" description="initial number of macrophages">50</number_of_macrophages>
<min_virion_detection_threshold type="double" units="none" description="minimal viral load for microphages to detect as infected">1</min_virion_detection_threshold>
<virus_digestion_rate type="double" units="1/min" description="rate that macrophages digest internalized viral particles">0.01</virus_digestion_rate>
<macrophage_persistence_time type="double" units="min">15</macrophage_persistence_time>
<macrophage_migration_speed type="double" units="micron/min">1</macrophage_migration_speed>
<macrophage_migration_bias type="double" units="dimensionless">0.1</macrophage_migration_bias>
<macrophage_relative_adhesion type="double" units="dimensionless">0.05</macrophage_relative_adhesion>
</user_parameters>
</PhysiCell_settings>
|
./SPECaccel/benchspec/ACCEL/551.ppalm/data/test/input/ENVPAR | &envpar run_identifier = 'acc_small', host = 'unknown',
write_binary = 'false', tasks_per_node = 1,
maximum_cpu_time_allowed = 999999.,
revision = 'Rev: ',
local_dvrserver_running = .FALSE. /
|
./openacc-vv/atomic_structured_divided_equals_assign.cpp | #include "acc_testsuite.h"
bool is_possible(real_t* a, real_t* b, real_t* c, int length, real_t prev){
if (length == 0){
return true;
}
real_t *passed_a = new real_t[(length - 1)];
real_t *passed_b = new real_t[(length - 1)];
real_t *passed_c = new real_t[(length - 1)];
for (int x = 0; x < length; ++x){
if (fabs(c[x] - (prev / (a[x] + b[x]))) < PRECISION){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
passed_c[y] = c[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
passed_c[y - 1] = c[y];
}
if (is_possible(passed_a, passed_b, passed_c, length - 1, c[x])){
delete[] passed_a;
delete[] passed_b;
delete[] passed_c;
return true;
}
}
}
delete[] passed_a;
delete[] passed_b;
delete[] passed_c;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *totals = new real_t[(n/10 + 1)];
real_t *totals_comparison = new real_t[(n/10 + 1)];
real_t *temp_a = new real_t[10];
real_t *temp_b = new real_t[10];
real_t *temp_c = new real_t[10];
int temp_iterator;
int ab_iterator;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 1;
totals_comparison[x] = 1;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(totals[0:n/10 + 1]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
totals[x/10] /= (a[x] + b[x]);
c[x] = totals[x/10];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x/10] /= a[x] + b[x];
}
for (int x = 0; x < 10; ++x){
if (fabs(totals_comparison[x] - totals[x]) > PRECISION){
err += 1;
break;
}
}
for (int x = 0; x < n; x = x + 10){
temp_iterator = 0;
for (ab_iterator = x; ab_iterator < n && ab_iterator < x + 10; ab_iterator+= 1){
temp_a[temp_iterator] = a[ab_iterator];
temp_b[temp_iterator] = b[ab_iterator];
temp_c[temp_iterator] = c[ab_iterator];
temp_iterator++;
}
if (!(is_possible(temp_a, temp_b, temp_c, temp_iterator, 1))){
err++;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_capture_rshift_equals.cpp | #include "acc_testsuite.h"
bool is_possible(unsigned int a, unsigned int* b, int length, unsigned int prev){
if (length == 0){
return true;
}
unsigned int passed_a = 0;
unsigned int *passed_b = (unsigned int *)malloc((length - 1) * sizeof(unsigned int));
for (int x = 0; x < length; ++x){
if ((b[x] == prev>>1 && ((a>>x)%2)==1) || ((a>>x)%2==0 && b[x] == prev)){
for (int y = 0; y < x; ++y){
if ((a>>y)%2 == 1){
passed_a += 1<<y;
}
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
if ((a>>y) % 2 == 1){
passed_a += 1<<(y - 1);
}
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, b[x])){
delete[] passed_b;
return true;
}
}
}
delete[] passed_b;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int *a = (unsigned int *)malloc(n * sizeof(int));
unsigned int *b = (unsigned int *)malloc(n * sizeof(int));
unsigned int *c = (unsigned int *)malloc(7 * n * sizeof(int));
unsigned int passed = 1<<8;
for (int x = 0; x < n; ++x){
a[x] = 1<<8;
for (int y = 0; y < 7; ++y){
if ((rand()/(real_t) (RAND_MAX)) > .5){
b[x] += 1<<y;
}
}
}
#pragma acc data copyin(b[0:n]) copy(a[0:n]) copyout(c[0:7*n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc loop
for (int y = 0; y < 7; ++y){
c[x * 7 + y] = a[x];
if ((b[x]>>y)%2 == 1){
#pragma acc atomic capture
c[x * 7 + y] = a[x] >>= 1;
}
}
}
}
}
for (int x = 0; x < n; ++x){
for (int y = 0; y < 7; ++y){
if ((b[x]>>y)%2 == 1){
a[x] <<= 1;
}
}
if (a[x] != 1<<8){
err += 1;
}
}
for (int x = 0; x < n; ++x){
if (!is_possible(b[x], &(c[x * 7]), 7, passed)){
err++;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./PhysiCell_GPU/unit_tests/substrate_internalization/config/PhysiCell_settings.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
/*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
-->
<!--
<user_details />
-->
<PhysiCell_settings version="devel-version">
<domain>
<x_min>-500</x_min>
<x_max>500</x_max>
<y_min>-500</y_min>
<y_max>500</y_max>
<z_min>-10</z_min>
<z_max>10</z_max>
<dx>20</dx>
<dy>20</dy>
<dz>20</dz>
<use_2D>true</use_2D>
</domain>
<overall>
<max_time units="min">1440</max_time> <!-- 5 days * 24 h * 60 min -->
<time_units>min</time_units>
<space_units>micron</space_units>
</overall>
<parallel>
<omp_num_threads>4</omp_num_threads>
</parallel>
<save>
<folder>output</folder> <!-- use . for root -->
<full_data>
<interval units="min">60</interval>
<enable>true</enable>
</full_data>
<SVG>
<interval units="min">6</interval>
<enable>true</enable>
</SVG>
<legacy_data>
<enable>false</enable>
</legacy_data>
</save>
<user_parameters>
<random_seed type="int" units="dimensionless">0</random_seed>
<!-- example parameters from the template -->
<!-- motile cell type parameters -->
<motile_cell_persistence_time type="double" units="min">15</motile_cell_persistence_time>
<motile_cell_migration_speed type="double" units="micron/min">0.5</motile_cell_migration_speed>
<motile_cell_relative_adhesion type="double" units="dimensionless">0.05</motile_cell_relative_adhesion>
<motile_cell_apoptosis_rate type="double" units="1/min">0.0</motile_cell_apoptosis_rate>
<motile_cell_relative_cycle_entry_rate type="double" units="dimensionless">0.1</motile_cell_relative_cycle_entry_rate>
</user_parameters>
</PhysiCell_settings>
|
./SPEChpc/benchspec/HPC/628.pot3d_s/src/hdf5/H5HFiblock.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*-------------------------------------------------------------------------
*
* Created: H5HFiblock.c
* Apr 10 2006
* Quincey Koziol <koziol@ncsa.uiuc.edu>
*
* Purpose: Indirect block routines for fractal heaps.
*
*-------------------------------------------------------------------------
*/
/****************/
/* Module Setup */
/****************/
#include "H5HFmodule.h" /* This source code file is part of the H5HF module */
/***********/
/* Headers */
/***********/
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5Fprivate.h" /* File access */
#include "H5HFpkg.h" /* Fractal heaps */
#include "H5MFprivate.h" /* File memory management */
#include "H5VMprivate.h" /* Vectors and arrays */
/****************/
/* Local Macros */
/****************/
/******************/
/* Local Typedefs */
/******************/
/********************/
/* Package Typedefs */
/********************/
/********************/
/* Local Prototypes */
/********************/
static herr_t H5HF__iblock_pin(H5HF_indirect_t *iblock);
static herr_t H5HF__iblock_unpin(H5HF_indirect_t *iblock);
static herr_t H5HF__man_iblock_root_halve(H5HF_indirect_t *root_iblock);
static herr_t H5HF__man_iblock_root_revert(H5HF_indirect_t *root_iblock);
/*********************/
/* Package Variables */
/*********************/
/* Declare a free list to manage the H5HF_indirect_t struct */
H5FL_DEFINE(H5HF_indirect_t);
/* Declare a free list to manage the H5HF_indirect_ent_t sequence information */
H5FL_SEQ_DEFINE(H5HF_indirect_ent_t);
/* Declare a free list to manage the H5HF_indirect_filt_ent_t sequence information */
H5FL_SEQ_DEFINE(H5HF_indirect_filt_ent_t);
/* Declare a free list to manage the H5HF_indirect_t * sequence information */
H5FL_SEQ_DEFINE(H5HF_indirect_ptr_t);
/*****************************/
/* Library Private Variables */
/*****************************/
/*******************/
/* Local Variables */
/*******************/
/*-------------------------------------------------------------------------
* Function: H5HF__iblock_pin
*
* Purpose: Pin an indirect block in memory
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@hdfgroup.org
* Aug 17 2006
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF__iblock_pin(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Sanity checks */
HDassert(iblock);
/* Mark block as un-evictable */
if(H5AC_pin_protected_entry(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTPIN, FAIL, "unable to pin fractal heap indirect block")
/* If this indirect block has a parent, update it's child iblock pointer */
if(iblock->parent) {
H5HF_indirect_t *par_iblock = iblock->parent; /* Parent indirect block */
unsigned indir_idx; /* Index in parent's child iblock pointer array */
/* Sanity check */
HDassert(par_iblock->child_iblocks);
HDassert(iblock->par_entry >= (iblock->hdr->man_dtable.max_direct_rows
* iblock->hdr->man_dtable.cparam.width));
/* Compute index in parent's child iblock pointer array */
indir_idx = iblock->par_entry - (iblock->hdr->man_dtable.max_direct_rows
* iblock->hdr->man_dtable.cparam.width);
/* Set pointer to pinned indirect block in parent */
HDassert(par_iblock->child_iblocks[indir_idx] == NULL);
par_iblock->child_iblocks[indir_idx] = iblock;
} /* end if */
else {
/* Check for pinning the root indirect block */
if(iblock->block_off == 0) {
/* Sanity check - shouldn't be recursively pinning root indirect block */
HDassert(0 == (iblock->hdr->root_iblock_flags & H5HF_ROOT_IBLOCK_PINNED));
/* Check if we should set the root iblock pointer */
if(0 == iblock->hdr->root_iblock_flags) {
HDassert(NULL == iblock->hdr->root_iblock);
iblock->hdr->root_iblock = iblock;
} /* end if */
/* Indicate that the root indirect block is pinned */
iblock->hdr->root_iblock_flags |= H5HF_ROOT_IBLOCK_PINNED;
} /* end if */
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__iblock_pin() */
/*-------------------------------------------------------------------------
* Function: H5HF__iblock_unpin
*
* Purpose: Unpin an indirect block in the metadata cache
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@hdfgroup.org
* Aug 17 2006
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF__iblock_unpin(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Sanity check */
HDassert(iblock);
/* Mark block as evictable again */
if(H5AC_unpin_entry(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPIN, FAIL, "unable to unpin fractal heap indirect block")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__iblock_unpin() */
/*-------------------------------------------------------------------------
* Function: H5HF_iblock_incr
*
* Purpose: Increment reference count on shared indirect block
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 27 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_iblock_incr(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/* Sanity checks */
HDassert(iblock);
HDassert(iblock->block_off == 0 || iblock->parent);
/* Mark block as un-evictable when a child block is depending on it */
if(iblock->rc == 0)
if(H5HF__iblock_pin(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTPIN, FAIL, "unable to pin fractal heap indirect block")
/* Increment reference count on shared indirect block */
iblock->rc++;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_iblock_incr() */
/*-------------------------------------------------------------------------
* Function: H5HF__iblock_decr
*
* Purpose: Decrement reference count on shared indirect block
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 27 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__iblock_decr(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/* Sanity check */
HDassert(iblock);
/* Decrement reference count on shared indirect block */
iblock->rc--;
/* Check for last reference to block */
if(iblock->rc == 0) {
/* If this indirect block has a parent, reset it's child iblock pointer */
if(iblock->parent) {
H5HF_indirect_t *par_iblock = iblock->parent; /* Parent indirect block */
unsigned indir_idx; /* Index in parent's child iblock pointer array */
/* Sanity check */
HDassert(par_iblock->child_iblocks);
HDassert(iblock->par_entry >= (iblock->hdr->man_dtable.max_direct_rows
* iblock->hdr->man_dtable.cparam.width));
/* Compute index in parent's child iblock pointer array */
indir_idx = iblock->par_entry - (iblock->hdr->man_dtable.max_direct_rows
* iblock->hdr->man_dtable.cparam.width);
/* Reset pointer to pinned child indirect block in parent */
HDassert(par_iblock->child_iblocks[indir_idx]);
par_iblock->child_iblocks[indir_idx] = NULL;
} /* end if */
else {
/* Check for root indirect block */
if(iblock->block_off == 0) {
/* Sanity check - shouldn't be recursively unpinning root indirect block */
HDassert(iblock->hdr->root_iblock_flags & H5HF_ROOT_IBLOCK_PINNED);
/* Check if we should reset the root iblock pointer */
if(H5HF_ROOT_IBLOCK_PINNED == iblock->hdr->root_iblock_flags) {
HDassert(NULL != iblock->hdr->root_iblock);
iblock->hdr->root_iblock = NULL;
} /* end if */
/* Indicate that the root indirect block is unpinned */
iblock->hdr->root_iblock_flags &= (unsigned)(~(H5HF_ROOT_IBLOCK_PINNED));
} /* end if */
} /* end else */
/* Check if the block is still in the cache */
if(!iblock->removed_from_cache) {
/* Unpin the indirect block, making it evictable again */
if(H5HF__iblock_unpin(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPIN, FAIL, "unable to unpin fractal heap indirect block")
} /* end if */
else {
/* Destroy the indirect block */
if(H5HF_man_iblock_dest(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to destroy fractal heap indirect block")
} /* end else */
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__iblock_decr() */
/*-------------------------------------------------------------------------
* Function: H5HF_iblock_dirty
*
* Purpose: Mark indirect block as dirty
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 21 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_iblock_dirty(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/* Sanity check */
HDassert(iblock);
/* Mark indirect block as dirty in cache */
if(H5AC_mark_entry_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTMARKDIRTY, FAIL, "unable to mark fractal heap indirect block as dirty")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_iblock_dirty() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_root_create
*
* Purpose: Create root indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* May 2 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_root_create(H5HF_hdr_t *hdr, size_t min_dblock_size)
{
H5HF_indirect_t *iblock; /* Pointer to indirect block */
haddr_t iblock_addr; /* Indirect block's address */
hsize_t acc_dblock_free; /* Accumulated free space in direct blocks */
hbool_t have_direct_block; /* Flag to indicate a direct block already exists */
hbool_t did_protect; /* Whether we protected the indirect block or not */
unsigned nrows; /* Number of rows for root indirect block */
unsigned u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/* Check for allocating entire root indirect block initially */
if(hdr->man_dtable.cparam.start_root_rows == 0)
nrows = hdr->man_dtable.max_root_rows;
else {
unsigned rows_needed; /* Number of rows needed to get to direct block size */
unsigned block_row_off; /* Row offset from larger block sizes */
nrows = hdr->man_dtable.cparam.start_root_rows;
block_row_off = H5VM_log2_of2((uint32_t)min_dblock_size) - H5VM_log2_of2((uint32_t)hdr->man_dtable.cparam.start_block_size);
if(block_row_off > 0)
block_row_off++; /* Account for the pair of initial rows of the initial block size */
rows_needed = 1 + block_row_off;
if(nrows < rows_needed)
nrows = rows_needed;
} /* end else */
/* Allocate root indirect block */
if(H5HF__man_iblock_create(hdr, NULL, 0, nrows, hdr->man_dtable.max_root_rows, &iblock_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTALLOC, FAIL, "can't allocate fractal heap indirect block")
/* Move current direct block (used as root) into new indirect block */
/* Lock new indirect block */
if(NULL == (iblock = H5HF__man_iblock_protect(hdr, iblock_addr, nrows, NULL, 0, FALSE, H5AC__NO_FLAGS_SET, &did_protect)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, FAIL, "unable to protect fractal heap indirect block")
/* Check if there's already a direct block as root) */
have_direct_block = H5F_addr_defined(hdr->man_dtable.table_addr);
if(have_direct_block) {
H5HF_direct_t *dblock; /* Pointer to direct block to query */
/* Lock first (root) direct block */
if(NULL == (dblock = H5HF__man_dblock_protect(hdr, hdr->man_dtable.table_addr, hdr->man_dtable.cparam.start_block_size, NULL, 0, H5AC__NO_FLAGS_SET)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, FAIL, "unable to protect fractal heap direct block")
/* Attach direct block to new root indirect block */
dblock->parent = iblock;
dblock->par_entry = 0;
/* Destroy flush dependency between direct block and header */
if(H5AC_destroy_flush_dependency(dblock->fd_parent, dblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNDEPEND, FAIL, "unable to destroy flush dependency")
dblock->fd_parent = NULL;
/* Create flush dependency between direct block and new root indirect block */
if(H5AC_create_flush_dependency(iblock, dblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEPEND, FAIL, "unable to create flush dependency")
dblock->fd_parent = iblock;
if(H5HF_man_iblock_attach(iblock, 0, hdr->man_dtable.table_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTATTACH, FAIL, "can't attach root direct block to parent indirect block")
/* Check for I/O filters on this heap */
if(hdr->filter_len > 0) {
/* Set the pipeline filter information from the header */
iblock->filt_ents[0].size = hdr->pline_root_direct_size;
iblock->filt_ents[0].filter_mask = hdr->pline_root_direct_filter_mask;
/* Reset the header's pipeline information */
hdr->pline_root_direct_size = 0;
hdr->pline_root_direct_filter_mask = 0;
} /* end if */
/* Scan free space sections to set any 'parent' pointers to new indirect block */
if(H5HF__space_create_root(hdr, iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSET, FAIL, "can't set free space section info to new root indirect block")
/* Unlock first (previously the root) direct block */
if(H5AC_unprotect(hdr->f, H5AC_FHEAP_DBLOCK, hdr->man_dtable.table_addr, dblock, H5AC__NO_FLAGS_SET) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap direct block")
dblock = NULL;
} /* end if */
/* Start iterator at correct location */
if(H5HF_hdr_start_iter(hdr, iblock, (hsize_t)(have_direct_block ? hdr->man_dtable.cparam.start_block_size : 0), have_direct_block) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't initialize block iterator")
/* Check for skipping over direct blocks, in order to get to large enough block */
if(min_dblock_size > hdr->man_dtable.cparam.start_block_size)
/* Add skipped blocks to heap's free space */
if(H5HF__hdr_skip_blocks(hdr, iblock, have_direct_block,
((nrows - 1) * hdr->man_dtable.cparam.width) - have_direct_block) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't add skipped blocks to heap's free space")
/* Mark indirect block as modified */
if(H5HF_iblock_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDIRTY, FAIL, "can't mark indirect block as dirty")
/* Unprotect root indirect block (it's pinned by the iterator though) */
if(H5HF__man_iblock_unprotect(iblock, H5AC__DIRTIED_FLAG, did_protect) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap indirect block")
iblock = NULL;
/* Point heap header at new indirect block */
hdr->man_dtable.curr_root_rows = nrows;
hdr->man_dtable.table_addr = iblock_addr;
/* Compute free space in direct blocks referenced from entries in root indirect block */
acc_dblock_free = 0;
for(u = 0; u < nrows; u++)
acc_dblock_free += hdr->man_dtable.row_tot_dblock_free[u] * hdr->man_dtable.cparam.width;
/* Account for potential initial direct block */
if(have_direct_block)
acc_dblock_free -= hdr->man_dtable.row_tot_dblock_free[0];
/* Extend heap to cover new root indirect block */
if(H5HF_hdr_adjust_heap(hdr, hdr->man_dtable.row_block_off[nrows], (hssize_t)acc_dblock_free) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTEXTEND, FAIL, "can't increase space to cover root direct block")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_root_create() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_root_double
*
* Purpose: Double size of root indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Apr 17 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_root_double(H5HF_hdr_t *hdr, size_t min_dblock_size)
{
H5HF_indirect_t *iblock; /* Pointer to root indirect block */
haddr_t new_addr; /* New address of indirect block */
hsize_t acc_dblock_free; /* Accumulated free space in direct blocks */
hsize_t next_size; /* The previous value of the "next size" for the new block iterator */
hsize_t old_iblock_size; /* Old size of indirect block */
unsigned next_row; /* The next row to allocate block in */
unsigned next_entry; /* The previous value of the "next entry" for the new block iterator */
unsigned new_next_entry = 0;/* The new value of the "next entry" for the new block iterator */
unsigned min_nrows = 0; /* Min. # of direct rows */
unsigned old_nrows; /* Old # of rows */
unsigned new_nrows; /* New # of rows */
hbool_t skip_direct_rows = FALSE; /* Whether we are skipping direct rows */
size_t u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/* Get "new block" iterator information */
if(H5HF_man_iter_curr(&hdr->next_block, &next_row, NULL, &next_entry, &iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "unable to retrieve current block iterator location")
next_size = hdr->man_dtable.row_block_size[next_row];
/* Make certain the iterator is at the root indirect block */
HDassert(iblock->parent == NULL);
HDassert(iblock->block_off == 0);
/* Keep this for later */
old_nrows = iblock->nrows;
/* Check for skipping over direct block rows */
if(iblock->nrows < hdr->man_dtable.max_direct_rows && min_dblock_size > next_size) {
/* Sanity check */
HDassert(min_dblock_size > hdr->man_dtable.cparam.start_block_size);
/* Set flag */
skip_direct_rows = TRUE;
/* Make certain we allocate at least the required row for the block requested */
min_nrows = 1 + H5HF_dtable_size_to_row(&hdr->man_dtable, min_dblock_size);
/* Set the information for the next block, of the appropriate size */
new_next_entry = (min_nrows - 1) * hdr->man_dtable.cparam.width;
} /* end if */
/* Compute new # of rows in indirect block */
new_nrows = MAX(min_nrows, MIN(2 * iblock->nrows, iblock->max_rows));
/* Check if the indirect block is NOT currently allocated in temp. file space */
/* (temp. file space does not need to be freed) */
if(!H5F_IS_TMP_ADDR(hdr->f, iblock->addr))
/* Free previous indirect block disk space */
if(H5MF_xfree(hdr->f, H5FD_MEM_FHEAP_IBLOCK, iblock->addr, (hsize_t)iblock->size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to free fractal heap indirect block file space")
/* Compute size of buffer needed for new indirect block */
iblock->nrows = new_nrows;
old_iblock_size = iblock->size;
iblock->size = H5HF_MAN_INDIRECT_SIZE(hdr, iblock->nrows);
/* Allocate [temporary] space for the new indirect block on disk */
if(H5F_USE_TMP_SPACE(hdr->f)) {
if(HADDR_UNDEF == (new_addr = H5MF_alloc_tmp(hdr->f, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end if */
else {
if(HADDR_UNDEF == (new_addr = H5MF_alloc(hdr->f, H5FD_MEM_FHEAP_IBLOCK, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end else */
/* Resize pinned indirect block in the cache, if its changed size */
if(old_iblock_size != iblock->size) {
if(H5AC_resize_entry(iblock, (size_t)iblock->size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTRESIZE, FAIL, "unable to resize fractal heap indirect block")
} /* end if */
/* Move object in cache, if it actually was relocated */
if(H5F_addr_ne(iblock->addr, new_addr)) {
if(H5AC_move_entry(hdr->f, H5AC_FHEAP_IBLOCK, iblock->addr, new_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTMOVE, FAIL, "unable to move fractal heap root indirect block")
iblock->addr = new_addr;
} /* end if */
/* Re-allocate child block entry array */
if(NULL == (iblock->ents = H5FL_SEQ_REALLOC(H5HF_indirect_ent_t, iblock->ents, (size_t)(iblock->nrows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "memory allocation failed for direct entries")
/* Check for skipping over rows and add free section for skipped rows */
if(skip_direct_rows)
/* Add skipped blocks to heap's free space */
if(H5HF__hdr_skip_blocks(hdr, iblock, next_entry, (new_next_entry - next_entry)) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't add skipped blocks to heap's free space")
/* Initialize new direct block entries in rows added */
acc_dblock_free = 0;
for(u = (old_nrows * hdr->man_dtable.cparam.width); u < (iblock->nrows * hdr->man_dtable.cparam.width); u++) {
unsigned row = (unsigned)(u / hdr->man_dtable.cparam.width); /* Row for current entry */
iblock->ents[u].addr = HADDR_UNDEF;
acc_dblock_free += hdr->man_dtable.row_tot_dblock_free[row];
} /* end for */
/* Check for needing to re-allocate filtered entry array */
if(hdr->filter_len > 0 && old_nrows < hdr->man_dtable.max_direct_rows) {
unsigned dir_rows; /* Number of direct rows in this indirect block */
/* Compute the number of direct rows for this indirect block */
dir_rows = MIN(iblock->nrows, hdr->man_dtable.max_direct_rows);
HDassert(dir_rows > old_nrows);
/* Re-allocate filtered direct block entry array */
if(NULL == (iblock->filt_ents = H5FL_SEQ_REALLOC(H5HF_indirect_filt_ent_t, iblock->filt_ents, (size_t)(dir_rows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "memory allocation failed for filtered direct entries")
/* Initialize new entries allocated */
for(u = (old_nrows * hdr->man_dtable.cparam.width); u < (dir_rows * hdr->man_dtable.cparam.width); u++) {
iblock->filt_ents[u].size = 0;
iblock->filt_ents[u].filter_mask = 0;
} /* end for */
} /* end if */
/* Check for needing to re-allocate child iblock pointer array */
if(iblock->nrows > hdr->man_dtable.max_direct_rows) {
unsigned indir_rows; /* Number of indirect rows in this indirect block */
unsigned old_indir_rows; /* Previous number of indirect rows in this indirect block */
/* Compute the number of direct rows for this indirect block */
indir_rows = iblock->nrows - hdr->man_dtable.max_direct_rows;
/* Re-allocate child indirect block array */
if(NULL == (iblock->child_iblocks = H5FL_SEQ_REALLOC(H5HF_indirect_ptr_t, iblock->child_iblocks, (size_t)(indir_rows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "memory allocation failed for filtered direct entries")
/* Compute the previous # of indirect rows in this block */
if(old_nrows < hdr->man_dtable.max_direct_rows)
old_indir_rows = 0;
else
old_indir_rows = old_nrows - hdr->man_dtable.max_direct_rows;
/* Initialize new entries allocated */
for(u = (old_indir_rows * hdr->man_dtable.cparam.width); u < (indir_rows * hdr->man_dtable.cparam.width); u++)
iblock->child_iblocks[u] = NULL;
} /* end if */
/* Mark indirect block as dirty */
if(H5HF_iblock_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDIRTY, FAIL, "can't mark indirect block as dirty")
/* Update other shared header info */
hdr->man_dtable.curr_root_rows = new_nrows;
hdr->man_dtable.table_addr = new_addr;
/* Extend heap to cover new root indirect block */
if(H5HF_hdr_adjust_heap(hdr, 2 * hdr->man_dtable.row_block_off[new_nrows - 1], (hssize_t)acc_dblock_free) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTEXTEND, FAIL, "can't increase space to cover root direct block")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_root_double() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_root_halve
*
* Purpose: Halve size of root indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Jun 12 2006
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF__man_iblock_root_halve(H5HF_indirect_t *iblock)
{
H5HF_hdr_t *hdr = iblock->hdr; /* Pointer to heap header */
haddr_t new_addr; /* New address of indirect block */
hsize_t acc_dblock_free; /* Accumulated free space in direct blocks */
hsize_t old_size; /* Old size of indirect block */
unsigned max_child_row; /* Row for max. child entry */
unsigned old_nrows; /* Old # of rows */
unsigned new_nrows; /* New # of rows */
unsigned u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/* Sanity check */
HDassert(iblock);
HDassert(iblock->parent == NULL);
HDassert(hdr);
/* Compute maximum row used by child of indirect block */
max_child_row = iblock->max_child / hdr->man_dtable.cparam.width;
/* Compute new # of rows in root indirect block */
new_nrows = (unsigned)1 << (1 + H5VM_log2_gen((uint64_t)max_child_row));
/* Check if the indirect block is NOT currently allocated in temp. file space */
/* (temp. file space does not need to be freed) */
if(!H5F_IS_TMP_ADDR(hdr->f, iblock->addr))
/* Free previous indirect block disk space */
if(H5MF_xfree(hdr->f, H5FD_MEM_FHEAP_IBLOCK, iblock->addr, (hsize_t)iblock->size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to free fractal heap indirect block file space")
/* Compute free space in rows to delete */
acc_dblock_free = 0;
for(u = new_nrows; u < iblock->nrows; u++)
acc_dblock_free += hdr->man_dtable.row_tot_dblock_free[u] * hdr->man_dtable.cparam.width;
/* Compute size of buffer needed for new indirect block */
old_nrows = iblock->nrows;
iblock->nrows = new_nrows;
old_size = iblock->size;
iblock->size = H5HF_MAN_INDIRECT_SIZE(hdr, iblock->nrows);
/* Allocate [temporary] space for the new indirect block on disk */
if(H5F_USE_TMP_SPACE(hdr->f)) {
if(HADDR_UNDEF == (new_addr = H5MF_alloc_tmp(hdr->f, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end if */
else {
if(HADDR_UNDEF == (new_addr = H5MF_alloc(hdr->f, H5FD_MEM_FHEAP_IBLOCK, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end else */
/* Resize pinned indirect block in the cache, if it has changed size */
if(old_size != iblock->size) {
if(H5AC_resize_entry(iblock, (size_t)iblock->size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTRESIZE, FAIL, "unable to resize fractal heap indirect block")
} /* end if */
/* Move object in cache, if it actually was relocated */
if(H5F_addr_ne(iblock->addr, new_addr)) {
if(H5AC_move_entry(hdr->f, H5AC_FHEAP_IBLOCK, iblock->addr, new_addr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSPLIT, FAIL, "unable to move fractal heap root indirect block")
iblock->addr = new_addr;
} /* end if */
/* Re-allocate child block entry array */
if(NULL == (iblock->ents = H5FL_SEQ_REALLOC(H5HF_indirect_ent_t, iblock->ents, (size_t)(iblock->nrows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for direct entries")
/* Check for needing to re-allocate filtered entry array */
if(hdr->filter_len > 0 && new_nrows < hdr->man_dtable.max_direct_rows) {
/* Re-allocate filtered direct block entry array */
if(NULL == (iblock->filt_ents = H5FL_SEQ_REALLOC(H5HF_indirect_filt_ent_t, iblock->filt_ents, (size_t)(iblock->nrows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "memory allocation failed for filtered direct entries")
} /* end if */
/* Check for needing to re-allocate child iblock pointer array */
if(old_nrows > hdr->man_dtable.max_direct_rows) {
/* Check for shrinking away child iblock pointer array */
if(iblock->nrows > hdr->man_dtable.max_direct_rows) {
unsigned indir_rows; /* Number of indirect rows in this indirect block */
/* Compute the number of direct rows for this indirect block */
indir_rows = iblock->nrows - hdr->man_dtable.max_direct_rows;
/* Re-allocate child indirect block array */
if(NULL == (iblock->child_iblocks = H5FL_SEQ_REALLOC(H5HF_indirect_ptr_t, iblock->child_iblocks, (size_t)(indir_rows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_HEAP, H5E_NOSPACE, FAIL, "memory allocation failed for filtered direct entries")
} /* end if */
else
iblock->child_iblocks = (H5HF_indirect_ptr_t *)H5FL_SEQ_FREE(H5HF_indirect_ptr_t, iblock->child_iblocks);
} /* end if */
/* Mark indirect block as dirty */
if(H5HF_iblock_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDIRTY, FAIL, "can't mark indirect block as dirty")
/* Update other shared header info */
hdr->man_dtable.curr_root_rows = new_nrows;
hdr->man_dtable.table_addr = new_addr;
/* Shrink heap to only cover new root indirect block */
if(H5HF_hdr_adjust_heap(hdr, 2 * hdr->man_dtable.row_block_off[new_nrows - 1], -(hssize_t)acc_dblock_free) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSHRINK, FAIL, "can't reduce space to cover root direct block")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_root_halve() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_root_revert
*
* Purpose: Revert root indirect block back to root direct block
*
* Note: Any sections left pointing to the old root indirect block
* will be cleaned up by the free space manager
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* May 31 2006
*
*-------------------------------------------------------------------------
*/
static herr_t
H5HF__man_iblock_root_revert(H5HF_indirect_t *root_iblock)
{
H5HF_hdr_t *hdr; /* Pointer to heap's header */
H5HF_direct_t *dblock = NULL; /* Pointer to new root indirect block */
haddr_t dblock_addr; /* Direct block's address in the file */
size_t dblock_size; /* Direct block's size */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_STATIC
/*
* Check arguments.
*/
HDassert(root_iblock);
/* Set up local convenience variables */
hdr = root_iblock->hdr;
dblock_addr = root_iblock->ents[0].addr;
dblock_size = hdr->man_dtable.cparam.start_block_size;
/* Get pointer to last direct block */
if(NULL == (dblock = H5HF__man_dblock_protect(hdr, dblock_addr, dblock_size, root_iblock, 0, H5AC__NO_FLAGS_SET)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, FAIL, "unable to protect fractal heap direct block")
HDassert(dblock->parent == root_iblock);
HDassert(dblock->par_entry == 0);
/* Check for I/O filters on this heap */
if(hdr->filter_len > 0) {
/* Set the header's pipeline information from the indirect block */
hdr->pline_root_direct_size = root_iblock->filt_ents[0].size;
hdr->pline_root_direct_filter_mask = root_iblock->filt_ents[0].filter_mask;
} /* end if */
/* Destroy flush dependency between old root iblock and new root direct block */
if(H5AC_destroy_flush_dependency(dblock->fd_parent, dblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNDEPEND, FAIL, "unable to destroy flush dependency")
dblock->fd_parent = NULL;
/* Detach direct block from parent */
if(H5HF__man_iblock_detach(dblock->parent, 0) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTATTACH, FAIL, "can't detach direct block from parent indirect block")
dblock->parent = NULL;
dblock->par_entry = 0;
/* Create flush dependency between header and new root direct block */
if(H5AC_create_flush_dependency(hdr, dblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEPEND, FAIL, "unable to create flush dependency")
dblock->fd_parent = hdr;
/* Point root at direct block */
hdr->man_dtable.curr_root_rows = 0;
hdr->man_dtable.table_addr = dblock_addr;
/* Reset 'next block' iterator */
if(H5HF_hdr_reset_iter(hdr, (hsize_t)dblock_size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTRELEASE, FAIL, "can't reset block iterator")
/* Extend heap to just cover first direct block */
if(H5HF_hdr_adjust_heap(hdr, (hsize_t)hdr->man_dtable.cparam.start_block_size, (hssize_t)hdr->man_dtable.row_tot_dblock_free[0]) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTEXTEND, FAIL, "can't increase space to cover root direct block")
/* Scan free space sections to reset any 'parent' pointers */
if(H5HF__space_revert_root(hdr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTRESET, FAIL, "can't reset free space section info")
done:
if(dblock && H5AC_unprotect(hdr->f, H5AC_FHEAP_DBLOCK, dblock_addr, dblock, H5AC__NO_FLAGS_SET) < 0)
HDONE_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap direct block")
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_root_revert() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_alloc_row
*
* Purpose: Allocate a "single" section for an object, out of a
* "row" section.
*
* Note: Creates necessary direct & indirect blocks
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* July 6 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_alloc_row(H5HF_hdr_t *hdr, H5HF_free_section_t **sec_node)
{
H5HF_indirect_t *iblock = NULL; /* Pointer to indirect block */
H5HF_free_section_t *old_sec_node = *sec_node; /* Pointer to old indirect section node */
unsigned dblock_entry; /* Entry for direct block */
hbool_t iblock_held = FALSE; /* Flag to indicate that indirect block is held */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(sec_node && old_sec_node);
HDassert(old_sec_node->u.row.row < hdr->man_dtable.max_direct_rows);
/* Check for serialized row section, or serialized / deleted indirect
* section under it. */
if(old_sec_node->sect_info.state == H5FS_SECT_SERIALIZED
|| (H5FS_SECT_SERIALIZED == old_sec_node->u.row.under->sect_info.state)
|| (TRUE == old_sec_node->u.row.under->u.indirect.u.iblock->removed_from_cache))
/* Revive row and / or indirect section */
if(H5HF__sect_row_revive(hdr, old_sec_node) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTREVIVE, FAIL, "can't revive indirect section")
/* Get a pointer to the indirect block covering the section */
if(NULL == (iblock = H5HF_sect_row_get_iblock(old_sec_node)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "can't retrieve indirect block for row section")
/* Hold indirect block in memory, until direct block can point to it */
if(H5HF_iblock_incr(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINC, FAIL, "can't increment reference count on shared indirect block")
iblock_held = TRUE;
/* Reduce (& possibly re-add) 'row' section */
if(H5HF__sect_row_reduce(hdr, old_sec_node, &dblock_entry) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSHRINK, FAIL, "can't reduce row section node")
/* Create direct block & single section */
if(H5HF__man_dblock_create(hdr, iblock, dblock_entry, NULL, sec_node) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTALLOC, FAIL, "can't allocate fractal heap direct block")
done:
/* Release hold on indirect block */
if(iblock_held)
if(H5HF__iblock_decr(iblock) < 0)
HDONE_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't decrement reference count on shared indirect block")
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_alloc_row() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_create
*
* Purpose: Allocate & initialize a managed indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 6 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_create(H5HF_hdr_t *hdr, H5HF_indirect_t *par_iblock,
unsigned par_entry, unsigned nrows, unsigned max_rows, haddr_t *addr_p)
{
H5HF_indirect_t *iblock = NULL; /* Pointer to indirect block */
size_t u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(nrows > 0);
HDassert(addr_p);
/*
* Allocate file and memory data structures.
*/
if(NULL == (iblock = H5FL_MALLOC(H5HF_indirect_t)))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for fractal heap indirect block")
/* Reset the metadata cache info for the heap header */
HDmemset(&iblock->cache_info, 0, sizeof(H5AC_info_t));
/* Share common heap information */
iblock->hdr = hdr;
if(H5HF_hdr_incr(hdr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINC, FAIL, "can't increment reference count on shared heap header")
/* Set info for indirect block */
iblock->rc = 0;
iblock->nrows = nrows;
iblock->max_rows = max_rows;
iblock->removed_from_cache = FALSE;
/* Compute size of buffer needed for indirect block */
iblock->size = H5HF_MAN_INDIRECT_SIZE(hdr, iblock->nrows);
/* Allocate child block entry array */
if(NULL == (iblock->ents = H5FL_SEQ_MALLOC(H5HF_indirect_ent_t, (size_t)(iblock->nrows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for block entries")
/* Initialize indirect block entry tables */
for(u = 0; u < (iblock->nrows * hdr->man_dtable.cparam.width); u++)
iblock->ents[u].addr = HADDR_UNDEF;
/* Check for I/O filters to apply to this heap */
if(hdr->filter_len > 0) {
unsigned dir_rows; /* Number of direct rows in this indirect block */
/* Compute the number of direct rows for this indirect block */
dir_rows = MIN(iblock->nrows, hdr->man_dtable.max_direct_rows);
/* Allocate & initialize indirect block filtered entry array */
if(NULL == (iblock->filt_ents = H5FL_SEQ_CALLOC(H5HF_indirect_filt_ent_t, (size_t)(dir_rows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for block entries")
} /* end if */
else
iblock->filt_ents = NULL;
/* Check if we have any indirect block children */
if(iblock->nrows > hdr->man_dtable.max_direct_rows) {
unsigned indir_rows; /* Number of indirect rows in this indirect block */
/* Compute the number of indirect rows for this indirect block */
indir_rows = iblock->nrows - hdr->man_dtable.max_direct_rows;
/* Allocate & initialize child indirect block pointer array */
if(NULL == (iblock->child_iblocks = H5FL_SEQ_CALLOC(H5HF_indirect_ptr_t, (size_t)(indir_rows * hdr->man_dtable.cparam.width))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "memory allocation failed for block entries")
} /* end if */
else
iblock->child_iblocks = NULL;
/* Allocate [temporary] space for the indirect block on disk */
if(H5F_USE_TMP_SPACE(hdr->f)) {
if(HADDR_UNDEF == (*addr_p = H5MF_alloc_tmp(hdr->f, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end if */
else {
if(HADDR_UNDEF == (*addr_p = H5MF_alloc(hdr->f, H5FD_MEM_FHEAP_IBLOCK, (hsize_t)iblock->size)))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "file allocation failed for fractal heap indirect block")
} /* end else */
iblock->addr = *addr_p;
/* Attach to parent indirect block, if there is one */
iblock->parent = par_iblock;
iblock->par_entry = par_entry;
if(iblock->parent) {
/* Attach new block to parent */
if(H5HF_man_iblock_attach(iblock->parent, par_entry, *addr_p) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTATTACH, FAIL, "can't attach indirect block to parent indirect block")
/* Compute the indirect block's offset in the heap's address space */
/* (based on parent's block offset) */
iblock->block_off = par_iblock->block_off;
iblock->block_off += hdr->man_dtable.row_block_off[par_entry / hdr->man_dtable.cparam.width];
iblock->block_off += hdr->man_dtable.row_block_size[par_entry / hdr->man_dtable.cparam.width] * (par_entry % hdr->man_dtable.cparam.width);
/* Set indirect block parent as flush dependency parent */
iblock->fd_parent = par_iblock;
} /* end if */
else {
iblock->block_off = 0; /* Must be the root indirect block... */
/* Set heap header as flush dependency parent */
iblock->fd_parent = hdr;
} /* end else */
/* Update indirect block's statistics */
iblock->nchildren = 0;
iblock->max_child = 0;
/* Cache the new indirect block */
if(H5AC_insert_entry(hdr->f, H5AC_FHEAP_IBLOCK, *addr_p, iblock, H5AC__NO_FLAGS_SET) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINIT, FAIL, "can't add fractal heap indirect block to cache")
done:
if(ret_value < 0)
if(iblock)
if(H5HF_man_iblock_dest(iblock) < 0)
HDONE_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to destroy fractal heap indirect block")
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_create() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_protect
*
* Purpose: Convenience wrapper around H5AC_protect on an indirect block
*
* Return: Pointer to indirect block on success, NULL on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Apr 17 2006
*
*-------------------------------------------------------------------------
*/
H5HF_indirect_t *
H5HF__man_iblock_protect(H5HF_hdr_t *hdr, haddr_t iblock_addr,
unsigned iblock_nrows, H5HF_indirect_t *par_iblock, unsigned par_entry,
hbool_t must_protect, unsigned flags, hbool_t *did_protect)
{
H5HF_parent_t par_info; /* Parent info for loading block */
H5HF_indirect_t *iblock = NULL; /* Indirect block from cache */
hbool_t should_protect = FALSE; /* Whether we should protect the indirect block or not */
H5HF_indirect_t *ret_value = NULL; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(H5F_addr_defined(iblock_addr));
HDassert(iblock_nrows > 0);
HDassert(did_protect);
/* only H5AC__READ_ONLY_FLAG may appear in flags */
HDassert((flags & (unsigned)(~H5AC__READ_ONLY_FLAG)) == 0);
/* Check if we are allowed to use existing pinned iblock pointer */
if(!must_protect) {
/* Check for this block already being pinned */
if(par_iblock) {
unsigned indir_idx; /* Index in parent's child iblock pointer array */
/* Sanity check */
HDassert(par_iblock->child_iblocks);
HDassert(par_entry >= (hdr->man_dtable.max_direct_rows
* hdr->man_dtable.cparam.width));
/* Compute index in parent's child iblock pointer array */
indir_idx = par_entry - (hdr->man_dtable.max_direct_rows
* hdr->man_dtable.cparam.width);
/* Check for pointer to pinned indirect block in parent */
if(par_iblock->child_iblocks[indir_idx])
iblock = par_iblock->child_iblocks[indir_idx];
else
should_protect = TRUE;
} /* end if */
else {
/* Check for root indirect block */
if(H5F_addr_eq(iblock_addr, hdr->man_dtable.table_addr)) {
/* Check for valid pointer to pinned indirect block in root */
if(H5HF_ROOT_IBLOCK_PINNED == hdr->root_iblock_flags) {
/* Sanity check */
HDassert(NULL != hdr->root_iblock);
/* Return the pointer to the pinned root indirect block */
iblock = hdr->root_iblock;
} /* end if */
else {
/* Sanity check */
HDassert(NULL == hdr->root_iblock);
should_protect = TRUE;
} /* end else */
} /* end if */
else
should_protect = TRUE;
} /* end else */
} /* end if */
/* Check for protecting indirect block */
if(must_protect || should_protect) {
H5HF_iblock_cache_ud_t cache_udata; /* User-data for callback */
/* Set up parent info */
par_info.hdr = hdr;
par_info.iblock = par_iblock;
par_info.entry = par_entry;
/* Set up user data for protect call */
cache_udata.f = hdr->f;
cache_udata.par_info = &par_info;
cache_udata.nrows = &iblock_nrows;
/* Protect the indirect block */
if(NULL == (iblock = (H5HF_indirect_t *)H5AC_protect(hdr->f, H5AC_FHEAP_IBLOCK, iblock_addr, &cache_udata, flags)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, NULL, "unable to protect fractal heap indirect block")
/* Set the indirect block's address */
iblock->addr = iblock_addr;
/* Check for root indirect block */
if(iblock->block_off == 0) {
/* Sanity check - shouldn't be recursively protecting root indirect block */
HDassert(0 == (hdr->root_iblock_flags & H5HF_ROOT_IBLOCK_PROTECTED));
/* Check if we should set the root iblock pointer */
if(0 == hdr->root_iblock_flags) {
HDassert(NULL == hdr->root_iblock);
hdr->root_iblock = iblock;
} /* end if */
/* Indicate that the root indirect block is protected */
hdr->root_iblock_flags |= H5HF_ROOT_IBLOCK_PROTECTED;
} /* end if */
/* Indicate that the indirect block was protected */
*did_protect = TRUE;
} /* end if */
else
/* Indicate that the indirect block was _not_ protected */
*did_protect = FALSE;
/* Set the return value */
ret_value = iblock;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_protect() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_unprotect
*
* Purpose: Convenience wrapper around H5AC_unprotect on an indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@hdfgroup.org
* Aug 17 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_unprotect(H5HF_indirect_t *iblock, unsigned cache_flags,
hbool_t did_protect)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(iblock);
/* Check if we previously protected this indirect block */
/* (as opposed to using an existing pointer to a pinned child indirect block) */
if(did_protect) {
/* Check for root indirect block */
if(iblock->block_off == 0) {
/* Sanity check - shouldn't be recursively unprotecting root indirect block */
HDassert(iblock->hdr->root_iblock_flags & H5HF_ROOT_IBLOCK_PROTECTED);
/* Check if we should reset the root iblock pointer */
if(H5HF_ROOT_IBLOCK_PROTECTED == iblock->hdr->root_iblock_flags) {
HDassert(NULL != iblock->hdr->root_iblock);
iblock->hdr->root_iblock = NULL;
} /* end if */
/* Indicate that the root indirect block is unprotected */
iblock->hdr->root_iblock_flags &= (unsigned)(~(H5HF_ROOT_IBLOCK_PROTECTED));
} /* end if */
/* Unprotect the indirect block */
if(H5AC_unprotect(iblock->hdr->f, H5AC_FHEAP_IBLOCK, iblock->addr, iblock, cache_flags) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap indirect block")
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_unprotect() */
/*-------------------------------------------------------------------------
* Function: H5HF_man_iblock_attach
*
* Purpose: Attach a child block (direct or indirect) to an indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* May 30 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_man_iblock_attach(H5HF_indirect_t *iblock, unsigned entry, haddr_t child_addr)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(iblock);
HDassert(H5F_addr_defined(child_addr));
HDassert(!H5F_addr_defined(iblock->ents[entry].addr));
/* Increment the reference count on this indirect block */
if(H5HF_iblock_incr(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTINC, FAIL, "can't increment reference count on shared indirect block")
/* Point at the child block */
iblock->ents[entry].addr = child_addr;
/* Check for I/O filters on this heap */
if(iblock->hdr->filter_len > 0) {
unsigned row; /* Row for entry */
/* Sanity check */
HDassert(iblock->filt_ents);
/* Compute row for entry */
row = entry / iblock->hdr->man_dtable.cparam.width;
/* If this is a direct block, set its initial size */
if(row < iblock->hdr->man_dtable.max_direct_rows)
iblock->filt_ents[entry].size = iblock->hdr->man_dtable.row_block_size[row];
} /* end if */
/* Check for max. entry used */
if(entry > iblock->max_child)
iblock->max_child = entry;
/* Increment the # of child blocks */
iblock->nchildren++;
/* Mark indirect block as modified */
if(H5HF_iblock_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDIRTY, FAIL, "can't mark indirect block as dirty")
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_man_iblock_attach() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_detach
*
* Purpose: Detach a child block (direct or indirect) from an indirect block
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* May 31 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_detach(H5HF_indirect_t *iblock, unsigned entry)
{
H5HF_hdr_t *hdr; /* Fractal heap header */
H5HF_indirect_t *del_iblock = NULL; /* Pointer to protected indirect block, when deleting */
unsigned row; /* Row for entry */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(iblock);
HDassert(iblock->nchildren);
/* Set up convenience variables */
hdr = iblock->hdr;
/* Reset address of entry */
iblock->ents[entry].addr = HADDR_UNDEF;
/* Compute row for entry */
row = entry / hdr->man_dtable.cparam.width;
/* Check for I/O filters on this heap */
if(hdr->filter_len > 0) {
/* Sanity check */
HDassert(iblock->filt_ents);
/* If this is a direct block, reset its initial size */
if(row < hdr->man_dtable.max_direct_rows) {
iblock->filt_ents[entry].size = 0;
iblock->filt_ents[entry].filter_mask = 0;
} /* end if */
} /* end if */
/* Check for indirect block being detached */
if(row >= hdr->man_dtable.max_direct_rows) {
unsigned indir_idx; /* Index in parent's child iblock pointer array */
/* Sanity check */
HDassert(iblock->child_iblocks);
/* Compute index in child iblock pointer array */
indir_idx = entry - (hdr->man_dtable.max_direct_rows * hdr->man_dtable.cparam.width);
/* Sanity check */
HDassert(iblock->child_iblocks[indir_idx]);
/* Reset pointer to child indirect block in parent */
iblock->child_iblocks[indir_idx] = NULL;
} /* end if */
/* Decrement the # of child blocks */
/* (If the number of children drop to 0, the indirect block will be
* removed from the heap when its ref. count drops to zero and the
* metadata cache calls the indirect block destructor)
*/
iblock->nchildren--;
/* Reduce the max. entry used, if necessary */
if(entry == iblock->max_child) {
if(iblock->nchildren > 0)
while(!H5F_addr_defined(iblock->ents[iblock->max_child].addr))
iblock->max_child--;
else
iblock->max_child = 0;
} /* end if */
/* If this is the root indirect block handle some special cases */
if(iblock->block_off == 0) {
/* If the number of children drops to 1, and that child is the first
* direct block in the heap, convert the heap back to using a root
* direct block
*/
if(iblock->nchildren == 1 && H5F_addr_defined(iblock->ents[0].addr))
if(H5HF__man_iblock_root_revert(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSHRINK, FAIL, "can't convert root indirect block back to root direct block")
/* If the indirect block wasn't removed already (by reverting it) */
if(!iblock->removed_from_cache) {
/* Check for reducing size of root indirect block */
if(iblock->nchildren > 0 && hdr->man_dtable.cparam.start_root_rows != 0
&& entry > iblock->max_child) {
unsigned max_child_row; /* Row for max. child entry */
/* Compute information needed for determining whether to reduce size of root indirect block */
max_child_row = iblock->max_child / hdr->man_dtable.cparam.width;
/* Check if the root indirect block should be reduced */
if(iblock->nrows > 1 && max_child_row <= (iblock->nrows / 2))
if(H5HF__man_iblock_root_halve(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSHRINK, FAIL, "can't reduce size of root indirect block")
} /* end if */
} /* end if */
} /* end if */
/* If the indirect block wasn't removed already (by reverting it) */
if(!iblock->removed_from_cache) {
/* Mark indirect block as modified */
if(H5HF_iblock_dirty(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDIRTY, FAIL, "can't mark indirect block as dirty")
/* Check for last child being removed from indirect block */
if(iblock->nchildren == 0) {
hbool_t did_protect = FALSE; /* Whether the indirect block was protected */
/* If this indirect block's refcount is >1, then it's being deleted
* from the fractal heap (since its nchildren == 0), but is still
* referred to from free space sections in the heap (refcount >1).
* Its space in the file needs to be freed now, and it also needs
* to be removed from the metadata cache now, in case the space in
* the file is reused by another piece of metadata that is inserted
* into the cache before the indirect block's entry is evicted
* (having two entries at the same address would be an error, from
* the cache's perspective).
*/
/* Lock indirect block for deletion */
if(NULL == (del_iblock = H5HF__man_iblock_protect(hdr, iblock->addr, iblock->nrows, iblock->parent, iblock->par_entry, TRUE, H5AC__NO_FLAGS_SET, &did_protect)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, FAIL, "unable to protect fractal heap indirect block")
HDassert(did_protect == TRUE);
/* Check for deleting root indirect block (and no root direct block) */
if(iblock->block_off == 0 && hdr->man_dtable.curr_root_rows > 0)
/* Reset header information back to "empty heap" state */
if(H5HF__hdr_empty(hdr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTSHRINK, FAIL, "can't make heap empty")
/* Detach from parent indirect block */
if(iblock->parent) {
/* Destroy flush dependency between indirect block and parent */
if(H5AC_destroy_flush_dependency(iblock->fd_parent, iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNDEPEND, FAIL, "unable to destroy flush dependency")
iblock->fd_parent = NULL;
/* Detach from parent indirect block */
if(H5HF__man_iblock_detach(iblock->parent, iblock->par_entry) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTATTACH, FAIL, "can't detach from parent indirect block")
iblock->parent = NULL;
iblock->par_entry = 0;
} /* end if */
} /* end if */
} /* end if */
/* Decrement the reference count on this indirect block if we're not deleting it */
/* (should be after iblock needs to be modified, so that potential 'unpin'
* on this indirect block doesn't invalidate the 'iblock' variable, if it's
* not being deleted)
*/
if(H5HF__iblock_decr(iblock) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't decrement reference count on shared indirect block")
iblock = NULL;
/* Delete indirect block from cache, if appropriate */
if(del_iblock) {
unsigned cache_flags = H5AC__NO_FLAGS_SET; /* Flags for unprotect */
hbool_t took_ownership = FALSE; /* Flag to indicate that block ownership has transitioned */
/* If the refcount is still >0, unpin the block and take ownership
* from the cache, otherwise let the cache destroy it.
*/
if(del_iblock->rc > 0) {
cache_flags |= (H5AC__DELETED_FLAG | H5AC__TAKE_OWNERSHIP_FLAG);
cache_flags |= H5AC__UNPIN_ENTRY_FLAG;
took_ownership = TRUE;
} /* end if */
else {
/* Entry should be removed from the cache */
cache_flags |= H5AC__DELETED_FLAG;
/* If the indirect block is in real file space, tell
* the cache to free its file space as well.
*/
if(!H5F_IS_TMP_ADDR(hdr->f, del_iblock->addr))
cache_flags |= H5AC__FREE_FILE_SPACE_FLAG;
} /* end else */
/* Unprotect the indirect block, with appropriate flags */
if(H5HF__man_iblock_unprotect(del_iblock, cache_flags, TRUE) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap indirect block")
/* if took ownership, free file space & mark block as removed from cache */
if(took_ownership) {
/* Free indirect block disk space, if it's in real space */
if(!H5F_IS_TMP_ADDR(hdr->f, del_iblock->addr))
if(H5MF_xfree(hdr->f, H5FD_MEM_FHEAP_IBLOCK, del_iblock->addr, (hsize_t)del_iblock->size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to free fractal heap indirect block file space")
del_iblock->addr = HADDR_UNDEF;
/* Mark block as removed from the cache */
del_iblock->removed_from_cache = TRUE;
} /* end if */
} /* end if */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_detach() */
/*-------------------------------------------------------------------------
* Function: H5HF_man_iblock_entry_addr
*
* Purpose: Retrieve the address of an indirect block's child
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* July 10 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_man_iblock_entry_addr(H5HF_indirect_t *iblock, unsigned entry, haddr_t *child_addr)
{
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(iblock);
HDassert(child_addr);
/* Retrieve address of entry */
*child_addr = iblock->ents[entry].addr;
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5HF_man_iblock_entry_addr() */
/*-------------------------------------------------------------------------
* Function: H5HF__man_iblock_delete
*
* Purpose: Delete a managed indirect block
*
* Note: This routine does _not_ modify any indirect block that points
* to this indirect block, it is assumed that the whole heap is
* being deleted in a top-down fashion.
*
* Return: SUCCEED/FAIL
*
* Programmer: Quincey Koziol
* koziol@hdfgroup.org
* Aug 7 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_delete(H5HF_hdr_t *hdr, haddr_t iblock_addr,
unsigned iblock_nrows, H5HF_indirect_t *par_iblock, unsigned par_entry)
{
H5HF_indirect_t *iblock; /* Pointer to indirect block */
unsigned row, col; /* Current row & column in indirect block */
unsigned entry; /* Current entry in row */
unsigned cache_flags = H5AC__NO_FLAGS_SET; /* Flags for unprotecting indirect block */
hbool_t did_protect; /* Whether we protected the indirect block or not */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(H5F_addr_defined(iblock_addr));
HDassert(iblock_nrows > 0);
/* Lock indirect block */
if(NULL == (iblock = H5HF__man_iblock_protect(hdr, iblock_addr, iblock_nrows, par_iblock, par_entry, TRUE, H5AC__NO_FLAGS_SET, &did_protect)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTPROTECT, FAIL, "unable to protect fractal heap indirect block")
HDassert(iblock->nchildren > 0);
HDassert(did_protect == TRUE);
/* Iterate over rows in this indirect block */
entry = 0;
for(row = 0; row < iblock->nrows; row++) {
/* Iterate over entries in this row */
for(col = 0; col < hdr->man_dtable.cparam.width; col++, entry++) {
/* Check for child entry at this position */
if(H5F_addr_defined(iblock->ents[entry].addr)) {
/* Are we in a direct or indirect block row */
if(row < hdr->man_dtable.max_direct_rows) {
hsize_t dblock_size; /* Size of direct block on disk */
/* Check for I/O filters on this heap */
if(hdr->filter_len > 0)
dblock_size = iblock->filt_ents[entry].size;
else
dblock_size = hdr->man_dtable.row_block_size[row];
/* Delete child direct block */
if(H5HF__man_dblock_delete(hdr->f, iblock->ents[entry].addr, dblock_size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to release fractal heap child direct block")
} /* end if */
else {
hsize_t row_block_size; /* The size of blocks in this row */
unsigned child_nrows; /* Number of rows in new indirect block */
/* Get the row's block size */
row_block_size = (hsize_t)hdr->man_dtable.row_block_size[row];
/* Compute # of rows in next child indirect block to use */
child_nrows = H5HF_dtable_size_to_rows(&hdr->man_dtable, row_block_size);
/* Delete child indirect block */
if(H5HF__man_iblock_delete(hdr, iblock->ents[entry].addr, child_nrows, iblock, entry) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTFREE, FAIL, "unable to release fractal heap child indirect block")
} /* end else */
} /* end if */
} /* end for */
} /* end row */
#ifndef NDEBUG
{
unsigned iblock_status = 0; /* Indirect block's status in the metadata cache */
/* Check the indirect block's status in the metadata cache */
if(H5AC_get_entry_status(hdr->f, iblock_addr, &iblock_status) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "unable to check metadata cache status for indirect block")
/* Check if indirect block is pinned */
HDassert(!(iblock_status & H5AC_ES__IS_PINNED));
}
#endif /* NDEBUG */
/* Indicate that the indirect block should be deleted */
cache_flags |= H5AC__DIRTIED_FLAG | H5AC__DELETED_FLAG;
/* If the indirect block is in real file space, tell
* the cache to free its file space as well.
*/
if (!H5F_IS_TMP_ADDR(hdr->f, iblock_addr))
cache_flags |= H5AC__FREE_FILE_SPACE_FLAG;
done:
/* Unprotect the indirect block, with appropriate flags */
if(iblock && H5HF__man_iblock_unprotect(iblock, cache_flags, did_protect) < 0)
HDONE_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap indirect block")
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_delete() */
/*-------------------------------------------------------------------------
*
* Function: H5HF__man_iblock_size
*
* Purpose: Gather storage used for the indirect block in fractal heap
*
* Return: non-negative on success, negative on error
*
* Programmer: Vailin Choi
* July 12 2007
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_size(H5F_t *f, H5HF_hdr_t *hdr, haddr_t iblock_addr,
unsigned nrows, H5HF_indirect_t *par_iblock, unsigned par_entry, hsize_t *heap_size)
{
H5HF_indirect_t *iblock = NULL; /* Pointer to indirect block */
hbool_t did_protect; /* Whether we protected the indirect block or not */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(f);
HDassert(hdr);
HDassert(H5F_addr_defined(iblock_addr));
HDassert(heap_size);
/* Protect the indirect block */
if(NULL == (iblock = H5HF__man_iblock_protect(hdr, iblock_addr, nrows, par_iblock, par_entry, FALSE, H5AC__READ_ONLY_FLAG, &did_protect)))
HGOTO_ERROR(H5E_HEAP, H5E_CANTLOAD, FAIL, "unable to load fractal heap indirect block")
/* Accumulate size of this indirect block */
*heap_size += iblock->size;
/* Indirect entries in this indirect block */
if(iblock->nrows > hdr->man_dtable.max_direct_rows) {
unsigned first_row_bits; /* Number of bits used bit addresses in first row */
unsigned num_indirect_rows; /* Number of rows of blocks in each indirect block */
unsigned entry; /* Current entry in row */
size_t u; /* Local index variable */
entry = hdr->man_dtable.max_direct_rows * hdr->man_dtable.cparam.width;
first_row_bits = H5VM_log2_of2((uint32_t)hdr->man_dtable.cparam.start_block_size) +
H5VM_log2_of2(hdr->man_dtable.cparam.width);
num_indirect_rows =
(H5VM_log2_gen(hdr->man_dtable.row_block_size[hdr->man_dtable.max_direct_rows]) - first_row_bits) + 1;
for(u = hdr->man_dtable.max_direct_rows; u < iblock->nrows; u++, num_indirect_rows++) {
size_t v; /* Local index variable */
for(v = 0; v < hdr->man_dtable.cparam.width; v++, entry++)
if(H5F_addr_defined(iblock->ents[entry].addr))
if(H5HF__man_iblock_size(f, hdr, iblock->ents[entry].addr, num_indirect_rows, iblock, entry, heap_size) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTLOAD, FAIL, "unable to get fractal heap storage info for indirect block")
} /* end for */
} /* end if */
done:
/* Release the indirect block */
if(iblock && H5HF__man_iblock_unprotect(iblock, H5AC__NO_FLAGS_SET, did_protect) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTUNPROTECT, FAIL, "unable to release fractal heap indirect block")
iblock = NULL;
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_size() */
/*-------------------------------------------------------------------------
*
* Function: H5HF_man_iblock_parent_info
*
* Purpose: Determine the parent block's offset and entry location
* (within it's parent) of an indirect block, given its offset
* within the heap.
*
* Return: Non-negative on success / Negative on failure
*
* Programmer: Quincey Koziol
* koziol@lbl.gov
* Jan 14 2018
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF__man_iblock_parent_info(const H5HF_hdr_t *hdr, hsize_t block_off,
hsize_t *ret_par_block_off, unsigned *ret_entry)
{
hsize_t par_block_off; /* Offset of parent within heap */
hsize_t prev_par_block_off; /* Offset of previous parent block within heap */
unsigned row, col; /* Row & column for block */
unsigned prev_row = 0, prev_col = 0;/* Previous row & column for block */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_PACKAGE
/*
* Check arguments.
*/
HDassert(hdr);
HDassert(block_off > 0);
HDassert(ret_entry);
/* Look up row & column for object */
if(H5HF_dtable_lookup(&hdr->man_dtable, block_off, &row, &col) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTCOMPUTE, FAIL, "can't compute row & column of block")
/* Sanity check - first lookup must be an indirect block */
HDassert(row >= hdr->man_dtable.max_direct_rows);
/* Traverse down, until a direct block at the offset is found, then
* use previous (i.e. parent's) offset, row, and column.
*/
prev_par_block_off = par_block_off = 0;
while(row >= hdr->man_dtable.max_direct_rows) {
/* Retain previous parent block offset */
prev_par_block_off = par_block_off;
/* Compute the new parent indirect block's offset in the heap's address space */
/* (based on previous block offset) */
par_block_off += hdr->man_dtable.row_block_off[row];
par_block_off += hdr->man_dtable.row_block_size[row] * col;
/* Preserve current row & column */
prev_row = row;
prev_col = col;
/* Look up row & column in new indirect block for object */
if(H5HF_dtable_lookup(&hdr->man_dtable, (block_off - par_block_off), &row, &col) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTCOMPUTE, FAIL, "can't compute row & column of block")
} /* end while */
/* Sanity check */
HDassert(row == 0);
HDassert(col == 0);
/* Set return parameters */
*ret_par_block_off = prev_par_block_off;
*ret_entry = (prev_row * hdr->man_dtable.cparam.width) + prev_col;
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF__man_iblock_par_info() */
/*-------------------------------------------------------------------------
* Function: H5HF_man_iblock_dest
*
* Purpose: Destroys a fractal heap indirect block in memory.
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 6 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_man_iblock_dest(H5HF_indirect_t *iblock)
{
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(iblock);
HDassert(iblock->rc == 0);
/* Decrement reference count on shared info */
HDassert(iblock->hdr);
if(H5HF_hdr_decr(iblock->hdr) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't decrement reference count on shared heap header")
if(iblock->parent)
if(H5HF__iblock_decr(iblock->parent) < 0)
HGOTO_ERROR(H5E_HEAP, H5E_CANTDEC, FAIL, "can't decrement reference count on shared indirect block")
/* Release entry tables */
if(iblock->ents)
iblock->ents = H5FL_SEQ_FREE(H5HF_indirect_ent_t, iblock->ents);
if(iblock->filt_ents)
iblock->filt_ents = H5FL_SEQ_FREE(H5HF_indirect_filt_ent_t, iblock->filt_ents);
if(iblock->child_iblocks)
iblock->child_iblocks = H5FL_SEQ_FREE(H5HF_indirect_ptr_t, iblock->child_iblocks);
/* Free fractal heap indirect block info */
iblock = H5FL_FREE(H5HF_indirect_t, iblock);
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_man_iblock_dest() */
|
./openacc-vv/serial_copy.c | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,data,data-region,V:2.6-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * a_host = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
a_host[x] = a[x];
}
#pragma acc serial copy(a[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
a[x] = 2 * a[x];
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (2 * a_host[x])) > PRECISION){
err = 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/acc_async_test.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:async,runtime,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = 0;
}
#pragma acc enter data copyin(a[0:n], b[0:n]) create(c[0:n]) async(1)
#pragma acc enter data copyin(d[0:n]) create(e[0:n]) async(2)
#pragma acc parallel present(a[0:n], b[0:n], c[0:n]) async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel present(c[0:n], d[0:n], e[0:n]) async(1) wait(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
e[x] = c[x] + d[x];
}
}
#pragma acc exit data copyout(e[0:n]) async(1)
while (!acc_async_test(1));
for (int x = 0; x < n; ++x){
if (fabs(e[x] - (a[x] + b[x] + d[x])) > PRECISION){
err += 1;
}
}
return err;
}
#endif
#ifndef T2
//T2:async,runtime,construct-independent,V:1.0-2.7
int test2(){
int err = 0;
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n]) create(c[0:n]) copyout(e[0:n])
{
#pragma acc parallel present(a[0:n], b[0:n], c[0:n]) async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] = a[x] + b[x];
}
}
#pragma acc parallel present(c[0:n], d[0:n], e[0:n]) async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
e[x] = c[x] + d[x];
}
}
while (!acc_async_test(1));
}
for (int x = 0; x < n; ++x) {
if (fabs(e[x] - (a[x] + b[x] + d[x])) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
#ifndef T3
//T3:async,runtime,construct-independent,V:2.5-2.7
int test3() {
int err = 0;
real_t* a = new real_t[n];
real_t* b = new real_t[n];
real_t* c = new real_t[n];
real_t* d = new real_t[n];
real_t* e = new real_t[n];
int async_val = acc_get_default_async();
for (int x = 0; x < n; ++x) {
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n], d[0:n]) create(c[0:n]) copyout(e[0:n])
{
#pragma acc parallel present(a[0:n], b[0:n], c[0:n]) async
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] = a[x] + b[x];
}
}
#pragma acc parallel present(c[0:n], d[0:n], e[0:n]) async
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
e[x] = c[x] + d[x];
}
}
while (!acc_async_test(async_val));
}
for (int x = 0; x < n; ++x) {
if (fabs(e[x] - (a[x] + b[x] + d[x])) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
#ifndef T3
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x) {
failed = failed + test3();
}
if (failed != 0) {
failcode = failcode + (1 << 2);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_vector_blocking.c | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * b = (real_t *)malloc(n * sizeof(real_t));
real_t * c = (real_t *)malloc(n * sizeof(real_t));
real_t multiplyer = 1;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copyout(c[0:n])
{
#pragma acc kernels
{
#pragma acc loop vector
for (int x = 0; x < n; ++x){
c[x] = (a[x] + b[x]) * multiplyer;
}
multiplyer += 1;
#pragma acc loop vector
for (int x = 0; x < n; ++x){
c[x] += (a[x] + b[x]) * multiplyer;
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(c[x] - 3 * (a[x] + b[x])) > PRECISION){
err + 1;
break;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_structured_predecrement_assign.c | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
int *c = (int *)malloc(n * sizeof(int));
int *distribution = (int *)malloc(10 * sizeof(int));
int *distribution_comparison = (int *)malloc(10 * sizeof(int));
bool found = false;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < 10; ++x){
distribution[x] = 0;
distribution_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(distribution[0:10]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
--distribution[(int) (a[x]*b[x]/10)];
c[x] = distribution[(int) (a[x]*b[x]/10)];
}
}
}
}
for (int x = 0; x < n; ++x){
distribution_comparison[(int) (a[x]*b[x]/10)]--;
}
for (int x = 0; x < 10; ++x){
if (distribution_comparison[x] != distribution[x]){
err += 1;
break;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y > distribution[x]; --y){
for (int z = 0; z < n; ++z){
if (c[z] == y - 1 && x == (int) (a[z] * b[z] / 10)){
found = true;
break;
}
}
if (!found){
err++;
}
found = false;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_capture_expr_minus_x.c | #include "acc_testsuite.h"
bool is_possible(real_t* a, real_t* b, int length, real_t prev){
if (length == 0){
return true;
}
real_t *passed_a = (real_t *)malloc((length - 1) * sizeof(real_t));
real_t *passed_b = (real_t *)malloc((length - 1) * sizeof(real_t));
for (int x = 0; x < length; ++x){
if (fabs(b[x] - (a[x] - prev)) < PRECISION){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, b[x])){
free(passed_a);
free(passed_b);
return true;
}
}
}
free(passed_a);
free(passed_b);
return false;
}
bool possible_result(real_t * remaining_combinations, int length, real_t current_value, real_t test_value){
if (length == 0){
if (fabs(current_value - test_value) > PRECISION){
return true;
}
else {
return false;
}
}
real_t * passed = (real_t *)malloc((length - 1) * sizeof(real_t));
for (int x = 0; x < length; ++x){
for (int y = 0; y < x; ++y){
passed[y] = remaining_combinations[y];
}
for (int y = x + 1; y < length; ++y){
passed[y - 1] = remaining_combinations[y];
}
if (possible_result(passed, length - 1, remaining_combinations[x] - current_value, test_value)){
free(passed);
return true;
}
}
free(passed);
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
real_t *totals = (real_t *)malloc(((n/10) + 1) * sizeof(real_t));
int indexer = 0;
real_t * passed = (real_t *)malloc(10 * sizeof(real_t));
real_t *passed_a = (real_t *)malloc(10 * sizeof(real_t));
real_t *passed_b = (real_t *)malloc(10 * sizeof(real_t));
int passed_indexer;
int absolute_indexer;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < (n/10) + 1; ++x){
totals[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:(n/10) + 1]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
b[x] = totals[x%((int) (n/10) + 1)] = a[x] - totals[x%((int) (n/10) + 1)];
}
}
}
for (int x = 0; x < (n/10) + 1; ++x){
indexer = x;
while (indexer < n){
passed[indexer/((int) (n/10) + 1)] = a[indexer];
indexer += (n/10) + 1;
}
if (!(possible_result(passed, 10, 0, totals[x]))){
err += 1;
}
}
for (int x = 0; x < n/10 + 1; ++x){
for (passed_indexer = 0, absolute_indexer = x; absolute_indexer < n; passed_indexer++, absolute_indexer += n/10 + 1){
passed_a[passed_indexer] = a[absolute_indexer];
passed_b[passed_indexer] = b[absolute_indexer];
}
if (!is_possible(passed_a, passed_b, passed_indexer, 0)){
err += 1;
}
break;
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./SPECaccel/benchspec/ACCEL/351.palm/src/cpu_statistics.F90 | SUBROUTINE cpu_statistics
!--------------------------------------------------------------------------------!
! This file is part of PALM.
!
! PALM is free software: you can redistribute it and/or modify it under the terms
! of the GNU General Public License as published by the Free Software Foundation,
! either version 3 of the License, or (at your option) any later version.
!
! PALM is distributed in the hope that it will be useful, but WITHOUT ANY
! WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
! A PARTICULAR PURPOSE. See the GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License along with
! PALM. If not, see <http://www.gnu.org/licenses/>.
!
! Copyright 1997-2012 Leibniz University Hannover
!--------------------------------------------------------------------------------!
!
! Current revisions:
! -----------------
!
!
! Former revisions:
! -----------------
! $Id: cpu_statistics.f90 1112 2013-03-09 00:34:37Z raasch $
!
! 1111 2013-03-08 23:54:10Z raasch
! output of grid point numbers and average CPU time per grid point and timestep
!
! 1092 2013-02-02 11:24:22Z raasch
! unused variables removed
!
! 1036 2012-10-22 13:43:42Z raasch
! code put under GPL (PALM 3.9)
!
! 1015 2012-09-27 09:23:24Z raasch
! output of accelerator board information
!
! 683 2011-02-09 14:25:15Z raasch
! output of handling of ghostpoint exchange
!
! 622 2010-12-10 08:08:13Z raasch
! output of handling of collective operations
!
! 222 2009-01-12 16:04:16Z letzel
! Bugfix for nonparallel execution
!
! 197 2008-09-16 15:29:03Z raasch
! Format adjustments in order to allow CPU# > 999,
! data are collected from PE0 in an ordered sequence which seems to avoid
! hanging of processes on SGI-ICE
!
! 82 2007-04-16 15:40:52Z raasch
! Preprocessor directives for old systems removed
!
! RCS Log replace by Id keyword, revision history cleaned up
!
! Revision 1.13 2006/04/26 12:10:51 raasch
! Output of number of threads per task, max = min in case of 1 PE
!
! Revision 1.1 1997/07/24 11:11:11 raasch
! Initial revision
!
!
! Description:
! ------------
! Analysis and output of the cpu-times measured. All PE results are collected
! on PE0 in order to calculate the mean cpu-time over all PEs and other
! statistics. The output is sorted according to the amount of cpu-time consumed
! and output on PE0.
!------------------------------------------------------------------------------!
USE control_parameters
USE cpulog
USE indices, ONLY: nx, ny, nz
USE pegrid
IMPLICIT NONE
INTEGER :: i, ii(1), iii, sender
REAL :: average_cputime
REAL, SAVE :: norm = 1.0
REAL, DIMENSION(:), ALLOCATABLE :: pe_max, pe_min, pe_rms, sum
REAL, DIMENSION(:,:), ALLOCATABLE :: pe_log_points
!
!-- Compute cpu-times in seconds
log_point%mtime = log_point%mtime / norm
log_point%sum = log_point%sum / norm
log_point%vector = log_point%vector / norm
WHERE ( log_point%counts /= 0 )
log_point%mean = log_point%sum / log_point%counts
END WHERE
!
!-- Collect cpu-times from all PEs and calculate statistics
IF ( myid == 0 ) THEN
!
!-- Allocate and initialize temporary arrays needed for statistics
ALLOCATE( pe_max( SIZE( log_point ) ), pe_min( SIZE( log_point ) ), &
pe_rms( SIZE( log_point ) ), &
pe_log_points( SIZE( log_point ), 0:numprocs-1 ) )
pe_min = log_point%sum
pe_max = log_point%sum ! need to be set in case of 1 PE
pe_rms = 0.0
#if defined( __parallel )
!
!-- Receive data from all PEs
DO i = 1, numprocs-1
CALL MPI_RECV( pe_max(1), SIZE( log_point ), MPI_REAL, &
i, i, comm2d, status, ierr )
sender = status(MPI_SOURCE)
pe_log_points(:,sender) = pe_max
ENDDO
pe_log_points(:,0) = log_point%sum ! Results from PE0
!
!-- Calculate mean of all PEs, store it on log_point%sum
!-- and find minimum and maximum
DO iii = 1, SIZE( log_point )
DO i = 1, numprocs-1
log_point(iii)%sum = log_point(iii)%sum + pe_log_points(iii,i)
pe_min(iii) = MIN( pe_min(iii), pe_log_points(iii,i) )
pe_max(iii) = MAX( pe_max(iii), pe_log_points(iii,i) )
ENDDO
log_point(iii)%sum = log_point(iii)%sum / numprocs
!
!-- Calculate rms
DO i = 0, numprocs-1
pe_rms(iii) = pe_rms(iii) + ( &
pe_log_points(iii,i) - log_point(iii)%sum &
)**2
ENDDO
pe_rms(iii) = SQRT( pe_rms(iii) / numprocs )
ENDDO
ELSE
!
!-- Send data to PE0 (pe_max is used as temporary storage to send
!-- the data in order to avoid sending the data type log)
ALLOCATE( pe_max( SIZE( log_point ) ) )
pe_max = log_point%sum
CALL MPI_SEND( pe_max(1), SIZE( log_point ), MPI_REAL, 0, myid, comm2d, &
ierr )
#endif
ENDIF
!
!-- Write cpu-times
IF ( myid == 0 ) THEN
!
!-- Re-store sums
ALLOCATE( sum( SIZE( log_point ) ) )
WHERE ( log_point%counts /= 0 )
sum = log_point%sum
ELSEWHERE
sum = -1.0
ENDWHERE
!
!-- Get total time in order to calculate CPU-time per gridpoint and timestep
IF ( nr_timesteps_this_run /= 0 ) THEN
average_cputime = log_point(1)%sum / REAL( (nx+1) * (ny+1) * nz ) / &
REAL( nr_timesteps_this_run ) * 1E6 ! in micro-sec
ELSE
average_cputime = -1.0
ENDIF
!
!-- Write cpu-times sorted by size
CALL check_open( 18 )
#if defined( __parallel )
WRITE ( 18, 100 ) TRIM( run_description_header ), &
numprocs * threads_per_task, pdims(1), pdims(2), &
threads_per_task, nx+1, ny+1, nz, nr_timesteps_this_run, &
average_cputime
IF ( num_acc_per_node /= 0 ) WRITE ( 18, 108 ) num_acc_per_node
WRITE ( 18, 110 )
#else
WRITE ( 18, 100 ) TRIM( run_description_header ), &
numprocs * threads_per_task, 1, 1, &
threads_per_task, nx+1, ny+1, nz, nr_timesteps_this_run, &
average_cputime
IF ( num_acc_per_node /= 0 ) WRITE ( 18, 109 ) num_acc_per_node
WRITE ( 18, 110 )
#endif
DO
ii = MAXLOC( sum )
i = ii(1)
IF ( sum(i) /= -1.0 ) THEN
WRITE ( 18, 102 ) &
log_point(i)%place, log_point(i)%sum, &
log_point(i)%sum / log_point(1)%sum * 100.0, &
log_point(i)%counts, pe_min(i), pe_max(i), pe_rms(i)
sum(i) = -1.0
ELSE
EXIT
ENDIF
ENDDO
ENDIF
!
!-- The same procedure again for the individual measurements.
!
!-- Compute cpu-times in seconds
log_point_s%mtime = log_point_s%mtime / norm
log_point_s%sum = log_point_s%sum / norm
log_point_s%vector = log_point_s%vector / norm
WHERE ( log_point_s%counts /= 0 )
log_point_s%mean = log_point_s%sum / log_point_s%counts
END WHERE
!
!-- Collect cpu-times from all PEs and calculate statistics
#if defined( __parallel )
!
!-- Set barrier in order to avoid that PE0 receives log_point_s-data
!-- while still busy with receiving log_point-data (see above)
CALL MPI_BARRIER( comm2d, ierr )
#endif
IF ( myid == 0 ) THEN
!
!-- Initialize temporary arrays needed for statistics
pe_min = log_point_s%sum
pe_max = log_point_s%sum ! need to be set in case of 1 PE
pe_rms = 0.0
#if defined( __parallel )
!
!-- Receive data from all PEs
DO i = 1, numprocs-1
CALL MPI_RECV( pe_max(1), SIZE( log_point ), MPI_REAL, &
MPI_ANY_SOURCE, MPI_ANY_TAG, comm2d, status, ierr )
sender = status(MPI_SOURCE)
pe_log_points(:,sender) = pe_max
ENDDO
pe_log_points(:,0) = log_point_s%sum ! Results from PE0
!
!-- Calculate mean of all PEs, store it on log_point_s%sum
!-- and find minimum and maximum
DO iii = 1, SIZE( log_point )
DO i = 1, numprocs-1
log_point_s(iii)%sum = log_point_s(iii)%sum + pe_log_points(iii,i)
pe_min(iii) = MIN( pe_min(iii), pe_log_points(iii,i) )
pe_max(iii) = MAX( pe_max(iii), pe_log_points(iii,i) )
ENDDO
log_point_s(iii)%sum = log_point_s(iii)%sum / numprocs
!
!-- Calculate rms
DO i = 0, numprocs-1
pe_rms(iii) = pe_rms(iii) + ( &
pe_log_points(iii,i) - log_point_s(iii)%sum &
)**2
ENDDO
pe_rms(iii) = SQRT( pe_rms(iii) / numprocs )
ENDDO
ELSE
!
!-- Send data to PE0 (pe_max is used as temporary storage to send
!-- the data in order to avoid sending the data type log)
pe_max = log_point_s%sum
CALL MPI_SEND( pe_max(1), SIZE( log_point ), MPI_REAL, 0, 0, comm2d, &
ierr )
#endif
ENDIF
!
!-- Write cpu-times
IF ( myid == 0 ) THEN
!
!-- Re-store sums
WHERE ( log_point_s%counts /= 0 )
sum = log_point_s%sum
ELSEWHERE
sum = -1.0
ENDWHERE
!
!-- Write cpu-times sorted by size
WRITE ( 18, 101 )
DO
ii = MAXLOC( sum )
i = ii(1)
IF ( sum(i) /= -1.0 ) THEN
WRITE ( 18, 102 ) &
log_point_s(i)%place, log_point_s(i)%sum, &
log_point_s(i)%sum / log_point(1)%sum * 100.0, &
log_point_s(i)%counts, pe_min(i), pe_max(i), pe_rms(i)
sum(i) = -1.0
ELSE
EXIT
ENDIF
ENDDO
!
!-- Output of handling of MPI operations
IF ( collective_wait ) THEN
WRITE ( 18, 103 )
ELSE
WRITE ( 18, 104 )
ENDIF
IF ( synchronous_exchange ) THEN
WRITE ( 18, 105 )
ELSE
WRITE ( 18, 106 )
ENDIF
!
!-- Empty lines in order to create a gap to the results of the model
!-- continuation runs
WRITE ( 18, 107 )
!
!-- Unit 18 is not needed anymore
CALL close_file( 18 )
ENDIF
100 FORMAT (A/11('-')//'CPU measures for ',I5,' PEs (',I5,'(x) * ',I5,'(y', &
&') tasks *',I5,' threads):'// &
'gridpoints (x/y/z): ',20X,I5,' * ',I5,' * ',I5/ &
'nr of timesteps: ',22X,I6/ &
'cpu time per grid point and timestep: ',5X,F8.5,' * 10**-6 s')
101 FORMAT (/'special measures:'/ &
&'-----------------------------------------------------------', &
&'--------------------')
102 FORMAT (A20,2X,F9.3,2X,F7.2,1X,I7,3(1X,F9.3))
103 FORMAT (/'Barriers are set in front of collective operations')
104 FORMAT (/'No barriers are set in front of collective operations')
105 FORMAT (/'Exchange of ghostpoints via MPI_SENDRCV')
106 FORMAT (/'Exchange of ghostpoints via MPI_ISEND/MPI_IRECV')
107 FORMAT (//)
108 FORMAT ('Accelerator boards per node: ',14X,I2)
109 FORMAT ('Accelerator boards: ',23X,I2)
110 FORMAT ('----------------------------------------------------------', &
&'------------'//&
&'place: mean counts min ', &
&' max rms'/ &
&' sec. % sec. ', &
&' sec. sec.'/ &
&'-----------------------------------------------------------', &
&'-------------------')
END SUBROUTINE cpu_statistics
|
./openacc-vv/set_device_type_num_nvidia.F90 | #ifndef T1
!T1:runtime,construct-independent,internal-control-values,set,nonvalidating,V:2.5-2.7
LOGICAL FUNCTION test1()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: device_num
INTEGER :: device_type
INTEGER :: errors = 0
device_type = acc_get_device_type()
device_num = acc_get_device_num(device_type)
!$acc set device_type(nvidia) device_num(device_num)
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/serial_loop_reduction_bitand_loop.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,loop,reduction,combined-constructs,V:2.6-3.2
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(10 * sizeof(unsigned int));
unsigned int* host_c = (unsigned int *)malloc(10 * sizeof(unsigned int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
for (int x = 0; x < 10 * n; ++x){
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX < false_margin){
for (int z = 0; z < y; ++z){
temp *= 2;
}
a[x] += temp;
temp = 1;
}
}
}
#pragma acc data copyin(a[0:10 * n]) copy(b[0:10 * n], c[0:10])
{
#pragma acc serial
{
#pragma acc loop gang private(temp)
for (int y = 0; y < 10; ++y){
temp = a[y * n];
#pragma acc loop worker reduction(&:temp)
for (int x = 1; x < n; ++x){
temp = temp & a[y * n + x];
}
c[y] = temp;
#pragma acc loop worker
for (int x = 0; x < n; ++x){
b[y * n + x] = b[y * n + x] + c[y];
}
}
}
}
for (int x = 0; x < 10; ++x){
host_c[x] = a[x * n];
for (int y = 1; y < n; ++y){
host_c[x] = host_c[x] & a[x * n + y];
}
if (host_c[x] != c[x]){
err += 1;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (b[x * n + y] != b_copy[x * n + y] + c[x]){
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/exit_data_finalize.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:data,executable-data,reference-counting,construct-independent,V:2.5-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
int * devtest = (int *)malloc(sizeof(int));
devtest[0] = 1;
#pragma acc enter data copyin(devtest[0:1])
#pragma acc parallel
{
devtest[0] = 0;
}
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
#pragma acc enter data copyin(a[0:n], b[0:n], c[0:n])
#pragma acc enter data create(a[0:n], b[0:n], c[0:n])
#pragma acc parallel present(a[0:n], b[0:n], c[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc exit data copyout(a[0:n], b[0:n], c[0:n])
if (devtest[0] == 1){
for (int x = 0; x < n; ++x){
if (fabs(c[x]) > PRECISION) {
err += 1;
}
}
}
#pragma acc exit data copyout(c[0:n]) delete(a[0:n], b[0:n])
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (a[x] + b[x])) > PRECISION){
err += 1;
}
}
return err;
}
#endif
#ifndef T2
//T2:data,executable-data,reference-counting,construct-independent,V:2.5-2.7
int test2(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
}
#pragma acc enter data copyin(a[0:n], b[0:n], c[0:n])
#pragma acc enter data copyin(a[0:n], b[0:n], c[0:n])
#pragma acc parallel present(a[0:n], b[0:n], c[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc exit data delete(a[0:n], b[0:n]) copyout(c[0:n]) finalize
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (a[x] + b[x])) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
return failcode;
}
|
./SPECaccel/benchspec/ACCEL/357.csp/src/sp.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB SP code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
//---------------------------------------------------------------------
// program SP
//---------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include "header.h"
#include "print_results.h"
/* common /global/ */
int grid_points[3], nx2, ny2, nz2;
logical timeron;
/* common /constants/ */
double tx1, tx2, tx3, ty1, ty2, ty3, tz1, tz2, tz3,
dx1, dx2, dx3, dx4, dx5, dy1, dy2, dy3, dy4,
dy5, dz1, dz2, dz3, dz4, dz5, dssp, dt,
ce[5][13], dxmax, dymax, dzmax, xxcon1, xxcon2,
xxcon3, xxcon4, xxcon5, dx1tx1, dx2tx1, dx3tx1,
dx4tx1, dx5tx1, yycon1, yycon2, yycon3, yycon4,
yycon5, dy1ty1, dy2ty1, dy3ty1, dy4ty1, dy5ty1,
zzcon1, zzcon2, zzcon3, zzcon4, zzcon5, dz1tz1,
dz2tz1, dz3tz1, dz4tz1, dz5tz1, dnxm1, dnym1,
dnzm1, c1c2, c1c5, c3c4, c1345, conz1, c1, c2,
c3, c4, c5, c4dssp, c5dssp, dtdssp, dttx1, bt,
dttx2, dtty1, dtty2, dttz1, dttz2, c2dttx1,
c2dtty1, c2dttz1, comz1, comz4, comz5, comz6,
c3c4tx3, c3c4ty3, c3c4tz3, c2iv, con43, con16;
/* common /fields/ */
double u[5][KMAX][JMAXP+1][IMAXP+1];
double us [KMAX][JMAXP+1][IMAXP+1];
double vs [KMAX][JMAXP+1][IMAXP+1];
double ws [KMAX][JMAXP+1][IMAXP+1];
double qs [KMAX][JMAXP+1][IMAXP+1];
double rho_i [KMAX][JMAXP+1][IMAXP+1];
double speed [KMAX][JMAXP+1][IMAXP+1];
double square [KMAX][JMAXP+1][IMAXP+1];
double rhs[5][KMAX][JMAXP+1][IMAXP+1];
double forcing[5][KMAX][JMAXP+1][IMAXP+1];
/* common /work_1d/ */
double cv [PROBLEM_SIZE];
double rhon[PROBLEM_SIZE];
double rhos[PROBLEM_SIZE];
double rhoq[PROBLEM_SIZE];
double cuf [PROBLEM_SIZE];
double q [PROBLEM_SIZE];
double ue [PROBLEM_SIZE][5];
double buf[PROBLEM_SIZE][5];
/* common /work_lhs/ */
double lhs [IMAXP+1][IMAXP+1][5];
double lhsp[IMAXP+1][IMAXP+1][5];
double lhsm[IMAXP+1][IMAXP+1][5];
int main(int argc, char *argv[])
{
int i, niter, step, n3;
double mflops, t, tmax, trecs[t_last+1];
logical verified;
char Class;
char *t_names[t_last+1];
//---------------------------------------------------------------------
// Read input file (if it exists), else take
// defaults from parameters
//---------------------------------------------------------------------
FILE *fp;
if ((fp = fopen("timer.flag", "r")) != NULL) {
timeron = true;
t_names[t_total] = "total";
t_names[t_rhsx] = "rhsx";
t_names[t_rhsy] = "rhsy";
t_names[t_rhsz] = "rhsz";
t_names[t_rhs] = "rhs";
t_names[t_xsolve] = "xsolve";
t_names[t_ysolve] = "ysolve";
t_names[t_zsolve] = "zsolve";
t_names[t_rdis1] = "redist1";
t_names[t_rdis2] = "redist2";
t_names[t_tzetar] = "tzetar";
t_names[t_ninvr] = "ninvr";
t_names[t_pinvr] = "pinvr";
t_names[t_txinvr] = "txinvr";
t_names[t_add] = "add";
fclose(fp);
} else {
timeron = false;
}
printf("\n\n NAS Parallel Benchmarks (NPB3.3-OMP) - SP Benchmark\n\n");
if ((fp = fopen("inputsp.data", "r")) != NULL) {
int result;
printf(" Reading from input file inputsp.data\n");
result = fscanf(fp, "%d", &niter);
while (fgetc(fp) != '\n');
result = fscanf(fp, "%lf", &dt);
while (fgetc(fp) != '\n');
result = fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]);
fclose(fp);
} else {
printf(" No input file inputsp.data. Using compiled defaults\n");
niter = NITER_DEFAULT;
dt = DT_DEFAULT;
grid_points[0] = PROBLEM_SIZE;
grid_points[1] = PROBLEM_SIZE;
grid_points[2] = PROBLEM_SIZE;
}
printf(" Size: %4dx%4dx%4d\n",
grid_points[0], grid_points[1], grid_points[2]);
printf(" Iterations: %4d dt: %10.6f\n", niter, dt);
printf("\n");
if ((grid_points[0] > IMAX) ||
(grid_points[1] > JMAX) ||
(grid_points[2] > KMAX) ) {
printf(" %d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]);
printf(" Problem size too big for compiled array sizes\n");
return 0;
}
nx2 = grid_points[0] - 2;
ny2 = grid_points[1] - 2;
nz2 = grid_points[2] - 2;
set_constants();
#pragma acc data create(u,us,vs,ws,qs,rho_i,speed,square,forcing,rhs)
{
exact_rhs();
initialize();
//---------------------------------------------------------------------
// do one time step to touch all code, and reinitialize
//---------------------------------------------------------------------
adi();
initialize();
for (step = 1; step <= niter; step++) {
if ((step % 20) == 0 || step == 1) {
printf(" Time step %4d\n", step);
}
adi();
}
#pragma acc update host(u)
verify(niter, &Class, &verified);
mflops = 0.0;
} /*end acc data*/
print_results("SP", Class, grid_points[0],
grid_points[1], grid_points[2], niter,
tmax, mflops, " floating point",
verified, NPBVERSION,COMPILETIME, CS1, CS2, CS3, CS4, CS5,
CS6);
return 0;
}
|
./openacc-vv/atomic_structured_expr_bitand_x_assign.c | #include "acc_testsuite.h"
bool is_possible(int* a, int* b, int length, int prev){
if (length == 0){
return true;
}
int *passed_a = (int *)malloc((length - 1) * sizeof(int));
int *passed_b = (int *)malloc((length - 1) * sizeof(int));
for (int x = 0; x < length; ++x){
if (b[x] == (prev & a[x])){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, b[x])){
free(passed_a);
free(passed_b);
return true;
}
}
}
free(passed_a);
free(passed_b);
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
int *a = (int *)malloc(n * sizeof(int));
int *b = (int *)malloc(n * sizeof(int));
int *totals = (int *)malloc((n/10 + 1) * sizeof(int));
int *totals_comparison = (int *)malloc((n/10 + 1) * sizeof(int));
int *temp_a = (int *)malloc(10 * sizeof(int));
int *temp_b = (int *)malloc(10 * sizeof(int));
int temp_iterator;
int ab_iterator;
for (int x = 0; x < n; ++x){
for (int y = 0; y < 8; ++y){
if (rand()/(real_t)(RAND_MAX) < .933){ //.933 gets close to a 50/50 distribution for a collescence of 10 values
a[x] += 1<<y;
}
}
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 0;
totals_comparison[x] = 0;
for (int y = 0; y < 8; ++y){
totals[x] += 1<<y;
totals_comparison[x] += 1<<y;
}
}
for (int x = 0; x < n; ++x){
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:n/10 + 1]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
totals[x/10] = a[x] & totals[x/10];
b[x] = totals[x/10];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x/10] &= a[x];
}
for (int x = 0; x < (n/10 + 1); ++x){
if (totals_comparison[x] != totals[x]){
err += 1;
break;
}
}
for (int x = 0; x < n; x = x + 10){
temp_iterator = 0;
for (ab_iterator = x; ab_iterator < n && ab_iterator < x + 10; ab_iterator+= 1){
temp_a[temp_iterator] = a[ab_iterator];
temp_b[temp_iterator] = b[ab_iterator];
}
if (!is_possible(temp_a, temp_b, temp_iterator, 1)){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_num_workers.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,V:2.5-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * restrict a = new real_t[n];
real_t * restrict b = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n])
{
#pragma acc kernels loop num_workers(16)
for (int x = 0; x < n; ++x){
b[x] = a[x];
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - b[x]) > PRECISION){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_structured_expr_bitor_x_assign.cpp | #include "acc_testsuite.h"
bool is_possible(int* a, int* b, int length, int prev){
if (length == 0){
return true;
}
int *passed_a = new int[(length - 1)];
int *passed_b = new int[(length - 1)];
for (int x = 0; x < length; ++x){
if (b[x] == (prev | a[x])){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, b[x])){
delete[] passed_a;
delete[] passed_b;
return true;
}
}
}
delete[] passed_a;
delete[] passed_b;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
int *a = new int[n];
int *b = new int[n];
int *totals = new int[(n/10 + 1)];
int *totals_comparison = new int[(n/10 + 1)];
int *temp_a = new int[10];
int *temp_b = new int[10];
int temp_iterator;
int ab_iterator;
for (int x = 0; x < n; ++x){
for (int y = 0; y < 8; ++y){
if (rand()/(real_t)(RAND_MAX) < .933){ //.933 gets close to a 50/50 distribution for a collescence of 10 values
a[x] += 1<<y;
}
}
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 0;
totals_comparison[x] = 0;
for (int y = 0; y < 8; ++y){
totals[x] += 1<<y;
totals_comparison[x] += 1<<y;
}
}
for (int x = 0; x < n; ++x){
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:n/10 + 1]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
totals[x/10] = a[x] | totals[x/10];
b[x] = totals[x/10];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x/10] |= a[x];
}
for (int x = 0; x < (n/10 + 1); ++x){
if (totals_comparison[x] != totals[x]){
err += 1;
break;
}
}
for (int x = 0; x < n; x = x + 10){
temp_iterator = 0;
for (ab_iterator = x; ab_iterator < n && ab_iterator < x + 10; ab_iterator+= 1){
temp_a[temp_iterator] = a[ab_iterator];
temp_b[temp_iterator] = b[ab_iterator];
}
if (!is_possible(temp_a, temp_b, temp_iterator, 1)){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_reduction_multiply_vector_loop.F90 | #ifndef T1
!T1:kernels,private,reduction,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(10 * LOOPCOUNT):: a, b !Data
REAL(8),DIMENSION(10) :: c
REAL(8) :: temp
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
a = (999.4 + a) / 1000
b = (999.4 + b) / 1000
!$acc data copyin(a(1:10*LOOPCOUNT), b(1:10*LOOPCOUNT)) copyout(c(1:10))
!$acc parallel loop private(temp)
DO x = 0, 9
temp = 1
!$acc loop vector reduction(*:temp)
DO y = 1, LOOPCOUNT
temp = temp * (a(x * LOOPCOUNT + y) + b(x * LOOPCOUNT + y))
END DO
c(x + 1) = temp
END DO
!$acc end data
DO x = 0, 9
temp = 1
DO y = 1, LOOPCOUNT
temp = temp * (a(x * LOOPCOUNT + y) + b(x * LOOPCOUNT + y))
END DO
IF (abs(temp - c(x + 1)) .gt. ((temp / 2) + (c(x + 1) / 2)) * PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/acc_get_device_num.c | #include "acc_testsuite.h"
#ifndef T1
//T1:runtime,devonly,internal-control-values,syntactic,V:1.0-2.7
int test1(){
int err = 0;
if (acc_get_device_type() != acc_device_none){
for (int x = 0; x < acc_get_num_devices(acc_get_device_type()); ++x){
acc_set_device_num(x, acc_get_device_type());
if (acc_get_device_num(acc_get_device_type()) != x){
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/data_create.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:data,data-region,construct-independent,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
c[x] = 0.0;
}
#pragma acc data create(b[0:n])
{
#pragma acc data copyin(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x];
}
}
}
#pragma acc data copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = b[x];
}
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(c[x] - a[x]) > PRECISION) {
err += 1;
break;
}
}
return err;
}
#endif
#ifndef T2
//T2:data,data-region,construct-independent,compatibility-features,V:1.0-2.7
int test2(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
c[x] = 0.0;
}
#pragma acc data present_or_create(b[0:n])
{
#pragma acc data copyin(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x];
}
}
}
#pragma acc data copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = b[x];
}
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(c[x] - a[x]) > PRECISION) {
err += 2;
break;
}
}
return err;
}
#endif
#ifndef T3
//T3:data,data-region,construct-independent,compatibility-features,V:1.0-2.7
int test3(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
c[x] = 0.0;
}
#pragma acc data pcreate(b[0:n])
{
#pragma acc data copyin(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x];
}
}
}
#pragma acc data copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = b[x];
}
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(c[x] - a[x]) > PRECISION){
err += 4;
break;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
#ifndef T3
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test3();
}
if (failed != 0){
failcode = failcode + (1 << 2);
}
#endif
return failcode;
}
|
./SPEChpc/benchspec/HPC/628.pot3d_s/src/hdf5/H5HFdtable.c | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by The HDF Group. *
* Copyright by the Board of Trustees of the University of Illinois. *
* All rights reserved. *
* *
* This file is part of HDF5. The full HDF5 copyright notice, including *
* terms governing use, modification, and redistribution, is contained in *
* the COPYING file, which can be found at the root of the source code *
* distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. *
* If you do not have access to either file, you may request a copy from *
* help@hdfgroup.org. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*-------------------------------------------------------------------------
*
* Created: H5HFdtable.c
* Apr 10 2006
* Quincey Koziol <koziol@ncsa.uiuc.edu>
*
* Purpose: "Doubling table" routines for fractal heaps.
*
*-------------------------------------------------------------------------
*/
/****************/
/* Module Setup */
/****************/
#include "H5HFmodule.h" /* This source code file is part of the H5HF module */
/***********/
/* Headers */
/***********/
#include "H5private.h" /* Generic Functions */
#include "H5Eprivate.h" /* Error handling */
#include "H5HFpkg.h" /* Fractal heaps */
#include "H5MMprivate.h" /* Memory management */
#include "H5VMprivate.h" /* Vectors and arrays */
/****************/
/* Local Macros */
/****************/
/******************/
/* Local Typedefs */
/******************/
/********************/
/* Package Typedefs */
/********************/
/********************/
/* Local Prototypes */
/********************/
/*********************/
/* Package Variables */
/*********************/
/*****************************/
/* Library Private Variables */
/*****************************/
/*******************/
/* Local Variables */
/*******************/
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_init
*
* Purpose: Initialize values for doubling table
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 6 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_dtable_init(H5HF_dtable_t *dtable)
{
hsize_t tmp_block_size; /* Temporary block size */
hsize_t acc_block_off; /* Accumulated block offset */
size_t u; /* Local index variable */
herr_t ret_value = SUCCEED; /* Return value */
FUNC_ENTER_NOAPI_NOINIT
/*
* Check arguments.
*/
HDassert(dtable);
/* Compute/cache some values */
dtable->start_bits = H5VM_log2_of2((uint32_t)dtable->cparam.start_block_size);
dtable->first_row_bits = dtable->start_bits + H5VM_log2_of2(dtable->cparam.width);
dtable->max_root_rows = (dtable->cparam.max_index - dtable->first_row_bits) + 1;
dtable->max_direct_bits = H5VM_log2_of2((uint32_t)dtable->cparam.max_direct_size);
dtable->max_direct_rows = (dtable->max_direct_bits - dtable->start_bits) + 2;
dtable->num_id_first_row = dtable->cparam.start_block_size * dtable->cparam.width;
dtable->max_dir_blk_off_size = H5HF_SIZEOF_OFFSET_LEN(dtable->cparam.max_direct_size);
/* Build table of block sizes for each row */
if(NULL == (dtable->row_block_size = (hsize_t *)H5MM_malloc(dtable->max_root_rows * sizeof(hsize_t))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't create doubling table block size table")
if(NULL == (dtable->row_block_off = (hsize_t *)H5MM_malloc(dtable->max_root_rows * sizeof(hsize_t))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't create doubling table block offset table")
if(NULL == (dtable->row_tot_dblock_free = (hsize_t *)H5MM_malloc(dtable->max_root_rows * sizeof(hsize_t))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't create doubling table total direct block free space table")
if(NULL == (dtable->row_max_dblock_free = (size_t *)H5MM_malloc(dtable->max_root_rows * sizeof(size_t))))
HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, FAIL, "can't create doubling table max. direct block free space table")
tmp_block_size = dtable->cparam.start_block_size;
acc_block_off = dtable->cparam.start_block_size * dtable->cparam.width;
dtable->row_block_size[0] = dtable->cparam.start_block_size;
dtable->row_block_off[0] = 0;
for(u = 1; u < dtable->max_root_rows; u++) {
dtable->row_block_size[u] = tmp_block_size;
dtable->row_block_off[u] = acc_block_off;
tmp_block_size *= 2;
acc_block_off *= 2;
} /* end for */
done:
FUNC_LEAVE_NOAPI(ret_value)
} /* end H5HF_dtable_init() */
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_lookup
*
* Purpose: Compute the row & col of an offset in a doubling-table
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 6 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_dtable_lookup(const H5HF_dtable_t *dtable, hsize_t off, unsigned *row, unsigned *col)
{
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(dtable);
HDassert(row);
HDassert(col);
#ifdef QAK
HDfprintf(stderr, "%s: off = %Hu\n", "H5HF_dtable_lookup", off);
#endif /* QAK */
/* Check for offset in first row */
if(off < dtable->num_id_first_row) {
*row = 0;
H5_CHECKED_ASSIGN(*col, unsigned, (off / dtable->cparam.start_block_size), hsize_t);
} /* end if */
else {
unsigned high_bit = H5VM_log2_gen(off); /* Determine the high bit in the offset */
hsize_t off_mask = ((hsize_t)1) << high_bit; /* Compute mask for determining column */
#ifdef QAK
HDfprintf(stderr, "%s: high_bit = %u, off_mask = %Hu\n", "H5HF_dtable_lookup", high_bit, off_mask);
#endif /* QAK */
*row = (high_bit - dtable->first_row_bits) + 1;
H5_CHECKED_ASSIGN(*col, unsigned, ((off - off_mask) / dtable->row_block_size[*row]), hsize_t);
} /* end else */
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5HF_dtable_lookup() */
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_dest
*
* Purpose: Release information for doubling table
*
* Return: Non-negative on success/Negative on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Mar 27 2006
*
*-------------------------------------------------------------------------
*/
herr_t
H5HF_dtable_dest(H5HF_dtable_t *dtable)
{
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(dtable);
/* Free the block size lookup table for the doubling table */
H5MM_xfree(dtable->row_block_size);
/* Free the block offset lookup table for the doubling table */
H5MM_xfree(dtable->row_block_off);
/* Free the total direct block free space lookup table for the doubling table */
H5MM_xfree(dtable->row_tot_dblock_free);
/* Free the max. direct block free space lookup table for the doubling table */
H5MM_xfree(dtable->row_max_dblock_free);
FUNC_LEAVE_NOAPI(SUCCEED)
} /* end H5HF_dtable_dest() */
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_size_to_row
*
* Purpose: Compute row that can hold block of a certain size
*
* Return: Non-negative on success (can't fail)
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* Apr 25 2006
*
*-------------------------------------------------------------------------
*/
unsigned
H5HF_dtable_size_to_row(const H5HF_dtable_t *dtable, size_t block_size)
{
unsigned row = 0; /* Row where block will fit */
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(dtable);
if(block_size == dtable->cparam.start_block_size)
row = 0;
else
row = (H5VM_log2_of2((uint32_t)block_size) - H5VM_log2_of2((uint32_t)dtable->cparam.start_block_size)) + 1;
FUNC_LEAVE_NOAPI(row)
} /* end H5HF_dtable_size_to_row() */
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_size_to_rows
*
* Purpose: Compute # of rows of indirect block of a given size
*
* Return: Non-negative on success (can't fail)
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* May 31 2006
*
*-------------------------------------------------------------------------
*/
unsigned
H5HF_dtable_size_to_rows(const H5HF_dtable_t *dtable, hsize_t size)
{
unsigned rows = 0; /* # of rows required for indirect block */
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(dtable);
rows = (H5VM_log2_gen(size) - dtable->first_row_bits) + 1;
FUNC_LEAVE_NOAPI(rows)
} /* end H5HF_dtable_size_to_rows() */
/*-------------------------------------------------------------------------
* Function: H5HF_dtable_span_size
*
* Purpose: Compute the size covered by a span of entries
*
* Return: Non-zero span size on success/zero on failure
*
* Programmer: Quincey Koziol
* koziol@ncsa.uiuc.edu
* July 25 2006
*
*-------------------------------------------------------------------------
*/
hsize_t
H5HF_dtable_span_size(const H5HF_dtable_t *dtable, unsigned start_row,
unsigned start_col, unsigned num_entries)
{
unsigned start_entry; /* Entry for first block covered */
unsigned end_row; /* Row for last block covered */
unsigned end_col; /* Column for last block covered */
unsigned end_entry; /* Entry for last block covered */
hsize_t acc_span_size = 0; /* Accumulated span size */
FUNC_ENTER_NOAPI_NOINIT_NOERR
/*
* Check arguments.
*/
HDassert(dtable);
HDassert(num_entries > 0);
/* Compute starting entry */
start_entry = (start_row * dtable->cparam.width) + start_col;
/* Compute ending entry, column & row */
end_entry = (start_entry + num_entries) - 1;
end_row = end_entry / dtable->cparam.width;
end_col = end_entry % dtable->cparam.width;
#ifdef QAK
HDfprintf(stderr, "%s: start_row = %u, start_col = %u, start_entry = %u\n", "H5HF_sect_indirect_span_size", start_row, start_col, start_entry);
HDfprintf(stderr, "%s: end_row = %u, end_col = %u, end_entry = %u\n", "H5HF_sect_indirect_span_size", end_row, end_col, end_entry);
#endif /* QAK */
/* Initialize accumulated span size */
acc_span_size = 0;
/* Compute span size covered */
/* Check for multi-row span */
if(start_row != end_row) {
/* Accommodate partial starting row */
if(start_col > 0) {
acc_span_size = dtable->row_block_size[start_row] *
(dtable->cparam.width - start_col);
start_row++;
} /* end if */
/* Accumulate full rows */
while(start_row < end_row) {
acc_span_size += dtable->row_block_size[start_row] *
dtable->cparam.width;
start_row++;
} /* end while */
/* Accommodate partial ending row */
acc_span_size += dtable->row_block_size[start_row] *
(end_col + 1);
} /* end if */
else {
/* Span is in same row */
acc_span_size = dtable->row_block_size[start_row] *
((end_col - start_col) + 1);
} /* end else */
#ifdef QAK
HDfprintf(stderr, "%s: acc_span_size = %Hu\n", "H5HF_dtable_span_size", acc_span_size);
#endif /* QAK */
FUNC_LEAVE_NOAPI(acc_span_size)
} /* end H5HF_sect_indirect_span_size() */
|
./openacc-vv/kernels_loop_reduction_bitxor_general.c | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(n * sizeof(unsigned int));
unsigned int b = 0;
for (int x = 0; x < n; ++x){
a[x] = (unsigned int) rand() / (real_t) (RAND_MAX / 2);
}
unsigned int host_b = a[0];
#pragma acc data copyin(a[0:n])
{
#pragma acc kernels loop reduction(^:b)
for (int x = 0; x < n; ++x){
b = b ^ a[x];
}
}
for (int x = 1; x < n; ++x){
host_b = host_b ^ a[x];
}
if (b != host_b){
err = 1;
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_reduction_and_loop.c | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
char * a = (char *)malloc(10 * n * sizeof(char));
char * a_copy = (char *)malloc(10 * n * sizeof(char));
char * has_false = (char *)malloc(10 * sizeof(char));
real_t false_margin = pow(exp(1), log(.5)/n);
for (int x = 0; x < 10; ++x){
has_false[x] = 0;
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (rand() / (real_t)(RAND_MAX) < false_margin){
a[x * n + y] = 1;
a_copy[x * n + y] = 1;
}
else {
a[x * n + y] = 0;
a_copy[x * n + y] = 0;
has_false[x] = 1;
}
}
}
char temp = 1;
#pragma acc data copy(a[0:10*n])
{
#pragma acc kernels loop gang private(temp)
for (int x = 0; x < 10; ++x){
temp = 1;
#pragma acc loop worker reduction(&&:temp)
for (int y = 0; y < n; ++y){
temp = temp && a[x * n + y];
}
#pragma acc loop worker
for (int y = 0; y < n; ++y){
if(temp == 1){
if (a[x * n + y] == 1){
a[x * n + y] = 0;
}
else {
a[x * n + y] = 1;
}
}
}
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (has_false[x] == 1 && a[x * n + y] != a_copy[x * n + y]){
err = 1;
}
else if (has_false[x] == 0 && a[x * n + y] == a_copy[x * n + y]){
err = 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/serial_loop_worker_blocking.F90 | #ifndef T1
!T1:loop,V:2.6-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c
INTEGER:: multiplier
INTEGER:: x
INTEGER:: errors
errors = 0
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT)) copyout(c(1:LOOPCOUNT))
!$acc serial
!$acc loop worker
DO x = 1, LOOPCOUNT
c(x) = (a(x) + b(x)) * multiplier
END DO
multiplier = multiplier + 1
!$acc loop worker
DO x = 1, LOOPCOUNT
c(x) = c(x) + ((a(x) + b(x)) * multiplier)
END DO
!$acc end serial
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (3 * (a(x) + b(x)))) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/parallel_create_zero.c | #include "acc_testsuite.h"
#ifndef T1
//#T1:parallel,data,data_region,V:3.0-3.2
int Test1(){
int err=0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * b = (real_t *)malloc(n * sizeof(real_t));
for( int x = 0; x < n; x++){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n]
{
#pragma acc parallel create(zero: b[0:n])
{
#pragma acc loop
{
for(int x = 0; x < n; x++){
b[x] += a[x];
}
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - b[x]) > PRECISION){
err = 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
} |
./PhysiCell_GPU/main.cpp | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "./core/PhysiCell.h"
#include "./modules/PhysiCell_standard_modules.h"
// custom user modules
#include "./custom_modules/cancer_immune_3D.h"
using namespace BioFVM;
using namespace PhysiCell;
int main( int argc, char* argv[] )
{
// load and parse settings file(s)
bool XML_status = false;
if( argc > 1 )
{ XML_status = load_PhysiCell_config_file( argv[1] ); }
else
{ XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); }
if( !XML_status )
{ exit(-1); }
// OpenMP setup
omp_set_num_threads(PhysiCell_settings.omp_num_threads);
// PNRG setup
SeedRandom();
// time setup
std::string time_units = "min";
/* Microenvironment setup */
setup_microenvironment();
/* PhysiCell setup */
// set mechanics voxel size, and match the data structure to BioFVM
double mechanics_voxel_size = 30;
Cell_Container* cell_container = create_cell_container_for_microenvironment( microenvironment, mechanics_voxel_size );
create_cell_types();
setup_tissue();
/* Users typically start modifying here. START USERMODS */
double immune_activation_time =
parameters.doubles("immune_activation_time"); // 60 * 24 * 14; // activate immune response at 14 days
/* Users typically stop modifying here. END USERMODS */
// set MultiCellDS save options
set_save_biofvm_mesh_as_matlab( true );
set_save_biofvm_data_as_matlab( true );
set_save_biofvm_cell_data( true );
set_save_biofvm_cell_data_as_custom_matlab( true );
// save a simulation snapshot
char filename[1024];
sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
// save a quick SVG cross section through z = 0, after setting its
// length bar to 200 microns
PhysiCell_SVG_options.length_bar = 200;
// for simplicity, set a pathology coloring function
std::vector<std::string> (*cell_coloring_function)(Cell*) = cancer_immune_coloring_function;
sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
display_citations();
// set the performance timers
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
std::ofstream report_file;
if( PhysiCell_settings.enable_legacy_saves == true )
{
sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() );
report_file.open(filename); // create the data log file
report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl;
}
//set the diffusion solver to GPU
microenvironment.diffusion_decay_solver = diffusion_decay_solver__constant_coefficients_LOD_3D_GPU;
bool first = true;
int outs = 0;
// main loop
try
{
while( PhysiCell_globals.current_time < PhysiCell_settings.max_time + 0.1*diffusion_dt )
{
if (outs == 1){
microenvironment.translate_array_to_vector();
sprintf( filename , "%s/first_out" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
static bool immune_cells_introduced = false;
if( PhysiCell_globals.current_time > immune_activation_time - 0.01*diffusion_dt && immune_cells_introduced == false )
{
std::cout << "Therapy activated!" << std::endl << std::endl;
immune_cells_introduced = true;
PhysiCell_settings.full_save_interval =
parameters.doubles("save_interval_after_therapy_start"); // 3.0;
PhysiCell_settings.SVG_save_interval =
parameters.doubles("save_interval_after_therapy_start"); // 3.0;
PhysiCell_globals.next_full_save_time = PhysiCell_globals.current_time;
PhysiCell_globals.next_SVG_save_time = PhysiCell_globals.current_time;
introduce_immune_cells();
}
// save data if it's time.
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt )
{
// translate data back to vector and update host
if (first == false){
std::cout << "updating host" << std::endl;
microenvironment.translate_array_to_vector();
std::cout << "-------continuing-------" << std::endl;
}
first = false;
display_simulation_status( std::cout );
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file);
}
if( PhysiCell_settings.enable_full_saves == true )
{
sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
}
PhysiCell_globals.full_output_index++;
PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval;
}
// save SVG plot if it's time
if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt )
{
std::cout << "2" << std::endl;
if( PhysiCell_settings.enable_SVG_saves == true )
{
sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
PhysiCell_globals.SVG_output_index++;
PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval;
}
}
// update the microenvironment
microenvironment.simulate_diffusion_decay( diffusion_dt );
// if( default_microenvironment_options.calculate_gradients )
// { microenvironment.compute_all_gradient_vectors(); }
// run PhysiCell
// ((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time );
// manually call the code for cell sources and sinks,
// since these are ordinarily automatically done as part of phenotype.secretion in the
// PhysiCell update that we commented out above. Remove this when we go
// back to main code
/*
#pragma omp parallel for
for( int i=0; i < (*all_cells).size(); i++ )
{
(*all_cells)[i]->phenotype.secretion.advance( (*all_cells)[i], (*all_cells)[i]->phenotype , diffusion_dt );
}
*/
PhysiCell_globals.current_time += diffusion_dt;
outs++;
}
if( PhysiCell_settings.enable_legacy_saves == true )
{
log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file);
report_file.close();
}
}
catch( const std::exception& e )
{ // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
// save a final simulation snapshot
microenvironment.translate_array_to_vector();
std::cout << "NUM_DIRICHLET " << microenvironment.num_dirichlet << std::endl;
sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() );
save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time );
sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() );
SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function );
return 0;
}
|
./openacc-vv/parallel_copyin.F90 | #ifndef T1
!T1:parallel,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, a_copy, b !Data
INTEGER :: errors = 0
INTEGER,DIMENSION(1):: hasDevice
hasDevice(1) = 1
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
a_copy = a
b = 0
!$acc enter data copyin(hasDevice(1:1))
!$acc parallel present(hasDevice(1:1))
hasDevice(1) = 0
!$acc end parallel
!$acc parallel copyin(a(1:LOOPCOUNT))
!$acc loop
DO x = 1, LOOPCOUNT
a(x) = 0.0
END DO
!$acc end parallel
DO x = 1, LOOPCOUNT
IF ((abs(a(x) - a_copy(x)) > PRECISION .AND. hasDevice(1) .eq. 1) .OR. (hasDevice(1) .eq. 0 .AND. abs(a(x)) > PRECISION)) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/parallel_loop_reduction_bitand_loop.c | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(10 * sizeof(unsigned int));
unsigned int * host_c = (unsigned int *)malloc(10 * sizeof(unsigned int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
for (int x = 0; x < 10 * n; ++x){
a[x] = 0;
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX < false_margin){
a[x] += 1 << y;
}
}
}
#pragma acc data copyin(a[0:10 * n]) copy(b[0:10 * n], c[0:10])
{
#pragma acc parallel loop gang private(temp)
for (int y = 0; y < 10; ++y){
temp = a[y * n];
#pragma acc loop worker reduction(&:temp)
for (int x = 1; x < n; ++x){
temp = temp & a[y * n + x];
}
c[y] = temp;
#pragma acc loop worker
for (int x = 0; x < n; ++x){
b[y * n + x] = b[y * n + x] + c[y];
}
}
}
for (int x = 0; x < 10; ++x){
host_c[x] = a[x * n];
for (int y = 1; y < n; ++y){
host_c[x] = host_c[x] & a[x * n + y];
}
if (host_c[x] != c[x]){
err += 1;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (b[x * n + y] != b_copy[x * n + y] + c[x]){
err += 1;
}
}
}
return err;
}
#endif
#ifndef T2
//T2:parallel,private,reduction,combined-constructs,loop,V:2.7-2.7
int test2(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(25 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(25 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(25 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(25 * sizeof(unsigned int));
unsigned int device[5];
unsigned int host[5];
real_t false_margin = pow(exp(1), log(.5)/n);
for (int x = 0; x < 25 * n; ++x){
a[x] = 0;
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
for (int y = 0; y < 16; ++y) {
if (rand() / (real_t)RAND_MAX < false_margin) {
a[x] += 1 << y;
}
}
}
#pragma acc data copyin(a[0:25*n]) copy(b[0:25*n], c[0:25])
{
#pragma acc parallel loop gang private(device)
for (int x = 0; x < 5; ++x) {
for (int y = 0; y < 5; ++y) {
device[y] = a[x * 5 * n + y];
}
#pragma acc loop worker reduction(&:device)
for (int y = 0; y < 5 * n; ++y) {
device[y%5] = device[y%5] & a[x * 5 * n + y];
}
for (int y = 0; y < 5; ++y) {
c[x * 5 + y] = device[y];
}
#pragma acc loop worker
for (int y = 0; y < 5 * n; ++y) {
b[x * 5 * n + y] = b[x * 5 * n + y] + c[x * 5 + (y % 5)];
}
}
}
for (int x = 0; x < 5; ++x) {
for (int y = 0; y < 5; ++y) {
host[y] = a[x * 5 * n + y];
}
for (int y = 0; y < 5 * n; ++y) {
host[y%5] = host[y%5] & a[x * 5 * n + y];
}
for (int y = 0; y < 5; ++y) {
if (host[y] != c[x * 5 + y]) {
err += 1;
}
}
for (int y = 0; y < 5 * n; ++y) {
if (b[x * 5 * n + y] != (host[y%5] + b_copy[x * 5 * n + y])) {
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
return failcode;
}
|
./openacc-vv/acc_on_device.F90 | #ifndef T1
!T1:runtime,construct-independent,internal-control-values,present,V:1.0-2.7
LOGICAL FUNCTION test1()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: errors
INTEGER :: device_type
errors = 0
device_type = acc_get_device_type()
IF (device_type .ne. acc_device_none) THEN
!$acc parallel
IF (acc_on_device(device_type) .eqv. .FALSE.) THEN
errors = errors + 1
END IF
!$acc end parallel
ELSE
!$acc parallel
IF (acc_on_device(acc_device_host) .eqv. .FALSE.) THEN
errors = errors + 1
END IF
!$acc end parallel
END IF
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
!Conditionally define test functions
#ifndef T1
LOGICAL :: test1
#endif
failcode = 0
failed = .FALSE.
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/init.c | #include "acc_testsuite.h"
#ifndef T1
//T1:init,V:2.5-2.7
int test1(){
int err = 0;
srand(SEED);
#pragma acc init
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./PhysiCell_GPU/examples/PhysiCell_test_mechanics_2.cpp | /*
###############################################################################
# If you use PhysiCell in your project, please cite PhysiCell and the version #
# number, such as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1]. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# See VERSION.txt or call get_PhysiCell_version() to get the current version #
# x.y.z. Call display_citations() to get detailed information on all cite-#
# able software used in your PhysiCell application. #
# #
# Because PhysiCell extensively uses BioFVM, we suggest you also cite BioFVM #
# as below: #
# #
# We implemented and solved the model using PhysiCell (Version x.y.z) [1], #
# with BioFVM [2] to solve the transport equations. #
# #
# [1] A Ghaffarizadeh, R Heiland, SH Friedman, SM Mumenthaler, and P Macklin, #
# PhysiCell: an Open Source Physics-Based Cell Simulator for Multicellu- #
# lar Systems, PLoS Comput. Biol. 14(2): e1005991, 2018 #
# DOI: 10.1371/journal.pcbi.1005991 #
# #
# [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient para- #
# llelized diffusive transport solver for 3-D biological simulations, #
# Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 #
# #
###############################################################################
# #
# BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) #
# #
# Copyright (c) 2015-2018, Paul Macklin and the PhysiCell Project #
# All rights reserved. #
# #
# Redistribution and use in source and binary forms, with or without #
# modification, are permitted provided that the following conditions are met: #
# #
# 1. Redistributions of source code must retain the above copyright notice, #
# this list of conditions and the following disclaimer. #
# #
# 2. Redistributions in binary form must reproduce the above copyright #
# notice, this list of conditions and the following disclaimer in the #
# documentation and/or other materials provided with the distribution. #
# #
# 3. Neither the name of the copyright holder nor the names of its #
# contributors may be used to endorse or promote products derived from this #
# software without specific prior written permission. #
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" #
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE #
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE #
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE #
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR #
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF #
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS #
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN #
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) #
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #
###############################################################################
*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <ctime>
#include <cmath>
#include <omp.h>
#include <fstream>
#include "../core/PhysiCell.h"
#include "../modules/PhysiCell_standard_modules.h"
using namespace BioFVM;
using namespace PhysiCell;
int omp_num_threads = 8; // set number of threads for parallel computing
// set this to # of CPU cores x 2 (for hyperthreading)
double pi=3.1415926535897932384626433832795;
double min_voxel_size=30;
void do_nothing(Cell* pCell, Phenotype& phenotype, double dt){}
std::vector<std::vector<double>> create_sphere(double cell_radius, double sphere_radius)
{
std::vector<std::vector<double>> cells;
int xc=0,yc=0,zc=0;
double x_spacing= cell_radius*sqrt(3);
double y_spacing= cell_radius*2;
double z_spacing= cell_radius*sqrt(3);
std::vector<double> tempPoint(3,0.0);
// std::vector<double> cylinder_center(3,0.0);
for(double z=-sphere_radius;z<sphere_radius;z+=z_spacing, zc++)
for(double x=-sphere_radius;x<sphere_radius;x+=x_spacing, xc++)
for(double y=-sphere_radius;y<sphere_radius;y+=y_spacing, yc++)
{
tempPoint[0]=x + (zc%2) * 0.5 * cell_radius;
tempPoint[1]=y + (xc%2) * cell_radius;
tempPoint[2]=z;
if(sqrt(norm_squared(tempPoint))< sphere_radius)
{
cells.push_back(tempPoint);
}
}
return cells;
}
int main( int argc, char* argv[] )
{
if(argc<=1)
{
std::cout<<"you need to provide dt as an argument"<<std::endl;
return 0;
}
double t = 0.0;
double dt = strtod(argv[1],NULL);
double t_output_interval = 5.0; // 1.0;
double t_max = 60;
double t_next_output_time = 0;
int next_output_index = 0;
double dx;
double dy;
double dz;
// openmp setup
omp_set_num_threads(omp_num_threads);
// PNRG setup
SeedRandom(3);
// figure out the bounding box
std::vector<double> bounding_box( 6, 0.0 );
bounding_box[PhysiCell_constants::mesh_min_x_index] = 0; bounding_box[PhysiCell_constants::mesh_max_x_index] = 2000;
bounding_box[PhysiCell_constants::mesh_min_y_index] = 0; bounding_box[PhysiCell_constants::mesh_max_y_index] = 2000;
bounding_box[PhysiCell_constants::mesh_min_z_index] = 0; bounding_box[PhysiCell_constants::mesh_max_z_index] = 2000;
dx=20; dy=20; dz=20;
// create a microenvironment
BioFVM::Microenvironment microenvironment;
microenvironment.name="substrate scale";
// add a microenvironment for simulating substrates
microenvironment.set_density(0, "oxygen" , "mmHg" );
std::cout << bounding_box << std::endl;
microenvironment.resize_space( bounding_box[0] , bounding_box[3] , bounding_box[1], bounding_box[4] , bounding_box[2] , bounding_box[5] ,dx,dy,dz );
microenvironment.spatial_units = "microns";
microenvironment.time_units = "minutes";
microenvironment.mesh.units = "microns";
// Cell_Container *
double mechanics_voxel_size = 30;
Cell_Container* cell_container = create_cell_container_for_microenvironment( microenvironment, mechanics_voxel_size );
microenvironment.display_information( std::cout );
initialize_default_cell_definition();
cell_defaults.type = 0;
cell_defaults.name = "tumor cell";
cell_defaults.functions.cycle_model = Ki67_advanced;
cell_defaults.functions.update_phenotype = empty_function;
cell_defaults.functions.volume_update_function = empty_function;
int Q_index = Ki67_advanced.find_phase_index( PhysiCell_constants::Ki67_negative );
double sample_cell_radius=10;
double volume=2.4943e+03;
double sphere_radius = 80;
// std::cout << __FILE__ << " custom " << __LINE__ << std::endl;
std::vector<std::vector<double>> cell_positions;
cell_positions= create_sphere(sample_cell_radius/5, sphere_radius);
std::vector<double> tumor_center(3);
tumor_center[0]=1000;
tumor_center[1]=1000;
tumor_center[2]=1000;
for(int i=0;i<cell_positions.size();i++)
{
Cell* pCell = create_cell();
pCell->register_microenvironment(µenvironment);
pCell->assign_position(tumor_center+ cell_positions[i]);
// pCell->functions.volume_update_function=empty_function;
// pCell->functions.update_phenotype=do_nothing;
pCell->phenotype.cycle.data.current_phase_index = Q_index;
pCell->set_total_volume(volume);
}
std::cout << (*all_cells)[0]->phenotype.geometry.radius<<std::endl;
std::cout << (*all_cells).size() <<" agents created successfully." <<std::endl;
BioFVM::RUNTIME_TIC();
BioFVM::TIC();
try
{
while( t < t_max )
{
// std::cout<<"time: "<<t<<" diff:"<<fabs( t - t_next_output_time )<<" next output time:"<<t_next_output_time<<std::endl;
if( fabs( t - t_next_output_time ) < 0.001 )
{
std::cout<<"time: "<<t<<std::endl;
writeCellReport(*all_cells, t);
t_next_output_time += t_output_interval;
}
((Cell_Container *)microenvironment.agent_container)->update_all_cells(t, dt, dt, dt);
t += dt;
}
double scale=1000;
writeCellReport(*all_cells, t_max);
std::cout << "total number of agents: " << (*all_cells).size()<<std::endl << std::endl;
BioFVM::RUNTIME_TOC();
BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() );
}
catch( const std::exception& e ) { // reference to the base of a polymorphic object
std::cout << e.what(); // information from length_error printed
}
return 0;
}
|
./openacc-vv/atomic_update_x_plus_expr_end.F90 | #ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: a !Data
REAL(8),DIMENSION(LOOPCOUNT):: totals, totals_comparison
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
totals = 0
totals_comparison = 0
!$acc data copyin(a(1:LOOPCOUNT, 1:10)) copy(totals(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic update
totals(x) = totals(x) + a(x, y)
!$acc end atomic
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
totals_comparison(x) = totals_comparison(x) + a(x, y)
END DO
END DO
DO x = 1, LOOPCOUNT
IF (totals_comparison(x) .NE. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./SPECaccel/tools/src/tar-1.25/gnu/regexec.c | /* -*- buffer-read-only: t -*- vi: set ro: */
/* DO NOT EDIT! GENERATED AUTOMATICALLY! */
/* Extended regular expression matching and search library.
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free
Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Isamu Hasegawa <isamu@yamato.ibm.com>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
static reg_errcode_t match_ctx_init (re_match_context_t *cache, int eflags,
Idx n) internal_function;
static void match_ctx_clean (re_match_context_t *mctx) internal_function;
static void match_ctx_free (re_match_context_t *cache) internal_function;
static reg_errcode_t match_ctx_add_entry (re_match_context_t *cache, Idx node,
Idx str_idx, Idx from, Idx to)
internal_function;
static Idx search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
internal_function;
static reg_errcode_t match_ctx_add_subtop (re_match_context_t *mctx, Idx node,
Idx str_idx) internal_function;
static re_sub_match_last_t * match_ctx_add_sublast (re_sub_match_top_t *subtop,
Idx node, Idx str_idx)
internal_function;
static void sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
re_dfastate_t **limited_sts, Idx last_node,
Idx last_str_idx)
internal_function;
static reg_errcode_t re_search_internal (const regex_t *preg,
const char *string, Idx length,
Idx start, Idx last_start, Idx stop,
size_t nmatch, regmatch_t pmatch[],
int eflags) internal_function;
static regoff_t re_search_2_stub (struct re_pattern_buffer *bufp,
const char *string1, Idx length1,
const char *string2, Idx length2,
Idx start, regoff_t range,
struct re_registers *regs,
Idx stop, bool ret_len) internal_function;
static regoff_t re_search_stub (struct re_pattern_buffer *bufp,
const char *string, Idx length, Idx start,
regoff_t range, Idx stop,
struct re_registers *regs,
bool ret_len) internal_function;
static unsigned int re_copy_regs (struct re_registers *regs, regmatch_t *pmatch,
Idx nregs, int regs_allocated)
internal_function;
static reg_errcode_t prune_impossible_nodes (re_match_context_t *mctx)
internal_function;
static Idx check_matching (re_match_context_t *mctx, bool fl_longest_match,
Idx *p_match_first) internal_function;
static Idx check_halt_state_context (const re_match_context_t *mctx,
const re_dfastate_t *state, Idx idx)
internal_function;
static void update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
regmatch_t *prev_idx_match, Idx cur_node,
Idx cur_idx, Idx nmatch) internal_function;
static reg_errcode_t push_fail_stack (struct re_fail_stack_t *fs,
Idx str_idx, Idx dest_node, Idx nregs,
regmatch_t *regs,
re_node_set *eps_via_nodes)
internal_function;
static reg_errcode_t set_regs (const regex_t *preg,
const re_match_context_t *mctx,
size_t nmatch, regmatch_t *pmatch,
bool fl_backtrack) internal_function;
static reg_errcode_t free_fail_stack_return (struct re_fail_stack_t *fs)
internal_function;
#ifdef RE_ENABLE_I18N
static int sift_states_iter_mb (const re_match_context_t *mctx,
re_sift_context_t *sctx,
Idx node_idx, Idx str_idx, Idx max_str_idx)
internal_function;
#endif /* RE_ENABLE_I18N */
static reg_errcode_t sift_states_backward (const re_match_context_t *mctx,
re_sift_context_t *sctx)
internal_function;
static reg_errcode_t build_sifted_states (const re_match_context_t *mctx,
re_sift_context_t *sctx, Idx str_idx,
re_node_set *cur_dest)
internal_function;
static reg_errcode_t update_cur_sifted_state (const re_match_context_t *mctx,
re_sift_context_t *sctx,
Idx str_idx,
re_node_set *dest_nodes)
internal_function;
static reg_errcode_t add_epsilon_src_nodes (const re_dfa_t *dfa,
re_node_set *dest_nodes,
const re_node_set *candidates)
internal_function;
static bool check_dst_limits (const re_match_context_t *mctx,
const re_node_set *limits,
Idx dst_node, Idx dst_idx, Idx src_node,
Idx src_idx) internal_function;
static int check_dst_limits_calc_pos_1 (const re_match_context_t *mctx,
int boundaries, Idx subexp_idx,
Idx from_node, Idx bkref_idx)
internal_function;
static int check_dst_limits_calc_pos (const re_match_context_t *mctx,
Idx limit, Idx subexp_idx,
Idx node, Idx str_idx,
Idx bkref_idx) internal_function;
static reg_errcode_t check_subexp_limits (const re_dfa_t *dfa,
re_node_set *dest_nodes,
const re_node_set *candidates,
re_node_set *limits,
struct re_backref_cache_entry *bkref_ents,
Idx str_idx) internal_function;
static reg_errcode_t sift_states_bkref (const re_match_context_t *mctx,
re_sift_context_t *sctx,
Idx str_idx, const re_node_set *candidates)
internal_function;
static reg_errcode_t merge_state_array (const re_dfa_t *dfa,
re_dfastate_t **dst,
re_dfastate_t **src, Idx num)
internal_function;
static re_dfastate_t *find_recover_state (reg_errcode_t *err,
re_match_context_t *mctx) internal_function;
static re_dfastate_t *transit_state (reg_errcode_t *err,
re_match_context_t *mctx,
re_dfastate_t *state) internal_function;
static re_dfastate_t *merge_state_with_log (reg_errcode_t *err,
re_match_context_t *mctx,
re_dfastate_t *next_state)
internal_function;
static reg_errcode_t check_subexp_matching_top (re_match_context_t *mctx,
re_node_set *cur_nodes,
Idx str_idx) internal_function;
#if 0
static re_dfastate_t *transit_state_sb (reg_errcode_t *err,
re_match_context_t *mctx,
re_dfastate_t *pstate)
internal_function;
#endif
#ifdef RE_ENABLE_I18N
static reg_errcode_t transit_state_mb (re_match_context_t *mctx,
re_dfastate_t *pstate)
internal_function;
#endif /* RE_ENABLE_I18N */
static reg_errcode_t transit_state_bkref (re_match_context_t *mctx,
const re_node_set *nodes)
internal_function;
static reg_errcode_t get_subexp (re_match_context_t *mctx,
Idx bkref_node, Idx bkref_str_idx)
internal_function;
static reg_errcode_t get_subexp_sub (re_match_context_t *mctx,
const re_sub_match_top_t *sub_top,
re_sub_match_last_t *sub_last,
Idx bkref_node, Idx bkref_str)
internal_function;
static Idx find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
Idx subexp_idx, int type) internal_function;
static reg_errcode_t check_arrival (re_match_context_t *mctx,
state_array_t *path, Idx top_node,
Idx top_str, Idx last_node, Idx last_str,
int type) internal_function;
static reg_errcode_t check_arrival_add_next_nodes (re_match_context_t *mctx,
Idx str_idx,
re_node_set *cur_nodes,
re_node_set *next_nodes)
internal_function;
static reg_errcode_t check_arrival_expand_ecl (const re_dfa_t *dfa,
re_node_set *cur_nodes,
Idx ex_subexp, int type)
internal_function;
static reg_errcode_t check_arrival_expand_ecl_sub (const re_dfa_t *dfa,
re_node_set *dst_nodes,
Idx target, Idx ex_subexp,
int type) internal_function;
static reg_errcode_t expand_bkref_cache (re_match_context_t *mctx,
re_node_set *cur_nodes, Idx cur_str,
Idx subexp_num, int type)
internal_function;
static bool build_trtable (const re_dfa_t *dfa,
re_dfastate_t *state) internal_function;
#ifdef RE_ENABLE_I18N
static int check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
const re_string_t *input, Idx idx)
internal_function;
# ifdef _LIBC
static unsigned int find_collation_sequence_value (const unsigned char *mbs,
size_t name_len)
internal_function;
# endif /* _LIBC */
#endif /* RE_ENABLE_I18N */
static Idx group_nodes_into_DFAstates (const re_dfa_t *dfa,
const re_dfastate_t *state,
re_node_set *states_node,
bitset_t *states_ch) internal_function;
static bool check_node_accept (const re_match_context_t *mctx,
const re_token_t *node, Idx idx)
internal_function;
static reg_errcode_t extend_buffers (re_match_context_t *mctx)
internal_function;
/* Entry point for POSIX code. */
/* regexec searches for a given pattern, specified by PREG, in the
string STRING.
If NMATCH is zero or REG_NOSUB was set in the cflags argument to
`regcomp', we ignore PMATCH. Otherwise, we assume PMATCH has at
least NMATCH elements, and we set them to the offsets of the
corresponding matched substrings.
EFLAGS specifies `execution flags' which affect matching: if
REG_NOTBOL is set, then ^ does not match at the beginning of the
string; if REG_NOTEOL is set, then $ does not match at the end.
We return 0 if we find a match and REG_NOMATCH if not. */
int
regexec (preg, string, nmatch, pmatch, eflags)
const regex_t *_Restrict_ preg;
const char *_Restrict_ string;
size_t nmatch;
regmatch_t pmatch[_Restrict_arr_];
int eflags;
{
reg_errcode_t err;
Idx start, length;
#ifdef _LIBC
re_dfa_t *dfa = (re_dfa_t *) preg->buffer;
#endif
if (eflags & ~(REG_NOTBOL | REG_NOTEOL | REG_STARTEND))
return REG_BADPAT;
if (eflags & REG_STARTEND)
{
start = pmatch[0].rm_so;
length = pmatch[0].rm_eo;
}
else
{
start = 0;
length = strlen (string);
}
__libc_lock_lock (dfa->lock);
if (preg->no_sub)
err = re_search_internal (preg, string, length, start, length,
length, 0, NULL, eflags);
else
err = re_search_internal (preg, string, length, start, length,
length, nmatch, pmatch, eflags);
__libc_lock_unlock (dfa->lock);
return err != REG_NOERROR;
}
#ifdef _LIBC
# include <shlib-compat.h>
versioned_symbol (libc, __regexec, regexec, GLIBC_2_3_4);
# if SHLIB_COMPAT (libc, GLIBC_2_0, GLIBC_2_3_4)
__typeof__ (__regexec) __compat_regexec;
int
attribute_compat_text_section
__compat_regexec (const regex_t *_Restrict_ preg,
const char *_Restrict_ string, size_t nmatch,
regmatch_t pmatch[], int eflags)
{
return regexec (preg, string, nmatch, pmatch,
eflags & (REG_NOTBOL | REG_NOTEOL));
}
compat_symbol (libc, __compat_regexec, regexec, GLIBC_2_0);
# endif
#endif
/* Entry points for GNU code. */
/* re_match, re_search, re_match_2, re_search_2
The former two functions operate on STRING with length LENGTH,
while the later two operate on concatenation of STRING1 and STRING2
with lengths LENGTH1 and LENGTH2, respectively.
re_match() matches the compiled pattern in BUFP against the string,
starting at index START.
re_search() first tries matching at index START, then it tries to match
starting from index START + 1, and so on. The last start position tried
is START + RANGE. (Thus RANGE = 0 forces re_search to operate the same
way as re_match().)
The parameter STOP of re_{match,search}_2 specifies that no match exceeding
the first STOP characters of the concatenation of the strings should be
concerned.
If REGS is not NULL, and BUFP->no_sub is not set, the offsets of the match
and all groups is stored in REGS. (For the "_2" variants, the offsets are
computed relative to the concatenation, not relative to the individual
strings.)
On success, re_match* functions return the length of the match, re_search*
return the position of the start of the match. Return value -1 means no
match was found and -2 indicates an internal error. */
regoff_t
re_match (bufp, string, length, start, regs)
struct re_pattern_buffer *bufp;
const char *string;
Idx length, start;
struct re_registers *regs;
{
return re_search_stub (bufp, string, length, start, 0, length, regs, true);
}
#ifdef _LIBC
weak_alias (__re_match, re_match)
#endif
regoff_t
re_search (bufp, string, length, start, range, regs)
struct re_pattern_buffer *bufp;
const char *string;
Idx length, start;
regoff_t range;
struct re_registers *regs;
{
return re_search_stub (bufp, string, length, start, range, length, regs,
false);
}
#ifdef _LIBC
weak_alias (__re_search, re_search)
#endif
regoff_t
re_match_2 (bufp, string1, length1, string2, length2, start, regs, stop)
struct re_pattern_buffer *bufp;
const char *string1, *string2;
Idx length1, length2, start, stop;
struct re_registers *regs;
{
return re_search_2_stub (bufp, string1, length1, string2, length2,
start, 0, regs, stop, true);
}
#ifdef _LIBC
weak_alias (__re_match_2, re_match_2)
#endif
regoff_t
re_search_2 (bufp, string1, length1, string2, length2, start, range, regs, stop)
struct re_pattern_buffer *bufp;
const char *string1, *string2;
Idx length1, length2, start, stop;
regoff_t range;
struct re_registers *regs;
{
return re_search_2_stub (bufp, string1, length1, string2, length2,
start, range, regs, stop, false);
}
#ifdef _LIBC
weak_alias (__re_search_2, re_search_2)
#endif
static regoff_t
internal_function
re_search_2_stub (struct re_pattern_buffer *bufp,
const char *string1, Idx length1,
const char *string2, Idx length2,
Idx start, regoff_t range, struct re_registers *regs,
Idx stop, bool ret_len)
{
const char *str;
regoff_t rval;
Idx len = length1 + length2;
char *s = NULL;
if (BE (length1 < 0 || length2 < 0 || stop < 0 || len < length1, 0))
return -2;
/* Concatenate the strings. */
if (length2 > 0)
if (length1 > 0)
{
s = re_malloc (char, len);
if (BE (s == NULL, 0))
return -2;
#ifdef _LIBC
memcpy (__mempcpy (s, string1, length1), string2, length2);
#else
memcpy (s, string1, length1);
memcpy (s + length1, string2, length2);
#endif
str = s;
}
else
str = string2;
else
str = string1;
rval = re_search_stub (bufp, str, len, start, range, stop, regs,
ret_len);
re_free (s);
return rval;
}
/* The parameters have the same meaning as those of re_search.
Additional parameters:
If RET_LEN is true the length of the match is returned (re_match style);
otherwise the position of the match is returned. */
static regoff_t
internal_function
re_search_stub (struct re_pattern_buffer *bufp,
const char *string, Idx length,
Idx start, regoff_t range, Idx stop, struct re_registers *regs,
bool ret_len)
{
reg_errcode_t result;
regmatch_t *pmatch;
Idx nregs;
regoff_t rval;
int eflags = 0;
#ifdef _LIBC
re_dfa_t *dfa = (re_dfa_t *) bufp->buffer;
#endif
Idx last_start = start + range;
/* Check for out-of-range. */
if (BE (start < 0 || start > length, 0))
return -1;
if (BE (length < last_start || (0 <= range && last_start < start), 0))
last_start = length;
else if (BE (last_start < 0 || (range < 0 && start <= last_start), 0))
last_start = 0;
__libc_lock_lock (dfa->lock);
eflags |= (bufp->not_bol) ? REG_NOTBOL : 0;
eflags |= (bufp->not_eol) ? REG_NOTEOL : 0;
/* Compile fastmap if we haven't yet. */
if (start < last_start && bufp->fastmap != NULL && !bufp->fastmap_accurate)
re_compile_fastmap (bufp);
if (BE (bufp->no_sub, 0))
regs = NULL;
/* We need at least 1 register. */
if (regs == NULL)
nregs = 1;
else if (BE (bufp->regs_allocated == REGS_FIXED
&& regs->num_regs <= bufp->re_nsub, 0))
{
nregs = regs->num_regs;
if (BE (nregs < 1, 0))
{
/* Nothing can be copied to regs. */
regs = NULL;
nregs = 1;
}
}
else
nregs = bufp->re_nsub + 1;
pmatch = re_malloc (regmatch_t, nregs);
if (BE (pmatch == NULL, 0))
{
rval = -2;
goto out;
}
result = re_search_internal (bufp, string, length, start, last_start, stop,
nregs, pmatch, eflags);
rval = 0;
/* I hope we needn't fill ther regs with -1's when no match was found. */
if (result != REG_NOERROR)
rval = -1;
else if (regs != NULL)
{
/* If caller wants register contents data back, copy them. */
bufp->regs_allocated = re_copy_regs (regs, pmatch, nregs,
bufp->regs_allocated);
if (BE (bufp->regs_allocated == REGS_UNALLOCATED, 0))
rval = -2;
}
if (BE (rval == 0, 1))
{
if (ret_len)
{
assert (pmatch[0].rm_so == start);
rval = pmatch[0].rm_eo - start;
}
else
rval = pmatch[0].rm_so;
}
re_free (pmatch);
out:
__libc_lock_unlock (dfa->lock);
return rval;
}
static unsigned int
internal_function
re_copy_regs (struct re_registers *regs, regmatch_t *pmatch, Idx nregs,
int regs_allocated)
{
int rval = REGS_REALLOCATE;
Idx i;
Idx need_regs = nregs + 1;
/* We need one extra element beyond `num_regs' for the `-1' marker GNU code
uses. */
/* Have the register data arrays been allocated? */
if (regs_allocated == REGS_UNALLOCATED)
{ /* No. So allocate them with malloc. */
regs->start = re_malloc (regoff_t, need_regs);
if (BE (regs->start == NULL, 0))
return REGS_UNALLOCATED;
regs->end = re_malloc (regoff_t, need_regs);
if (BE (regs->end == NULL, 0))
{
re_free (regs->start);
return REGS_UNALLOCATED;
}
regs->num_regs = need_regs;
}
else if (regs_allocated == REGS_REALLOCATE)
{ /* Yes. If we need more elements than were already
allocated, reallocate them. If we need fewer, just
leave it alone. */
if (BE (need_regs > regs->num_regs, 0))
{
regoff_t *new_start = re_realloc (regs->start, regoff_t, need_regs);
regoff_t *new_end;
if (BE (new_start == NULL, 0))
return REGS_UNALLOCATED;
new_end = re_realloc (regs->end, regoff_t, need_regs);
if (BE (new_end == NULL, 0))
{
re_free (new_start);
return REGS_UNALLOCATED;
}
regs->start = new_start;
regs->end = new_end;
regs->num_regs = need_regs;
}
}
else
{
assert (regs_allocated == REGS_FIXED);
/* This function may not be called with REGS_FIXED and nregs too big. */
assert (regs->num_regs >= nregs);
rval = REGS_FIXED;
}
/* Copy the regs. */
for (i = 0; i < nregs; ++i)
{
regs->start[i] = pmatch[i].rm_so;
regs->end[i] = pmatch[i].rm_eo;
}
for ( ; i < regs->num_regs; ++i)
regs->start[i] = regs->end[i] = -1;
return rval;
}
/* Set REGS to hold NUM_REGS registers, storing them in STARTS and
ENDS. Subsequent matches using PATTERN_BUFFER and REGS will use
this memory for recording register information. STARTS and ENDS
must be allocated using the malloc library routine, and must each
be at least NUM_REGS * sizeof (regoff_t) bytes long.
If NUM_REGS == 0, then subsequent matches should allocate their own
register data.
Unless this function is called, the first search or match using
PATTERN_BUFFER will allocate its own register data, without
freeing the old data. */
void
re_set_registers (bufp, regs, num_regs, starts, ends)
struct re_pattern_buffer *bufp;
struct re_registers *regs;
__re_size_t num_regs;
regoff_t *starts, *ends;
{
if (num_regs)
{
bufp->regs_allocated = REGS_REALLOCATE;
regs->num_regs = num_regs;
regs->start = starts;
regs->end = ends;
}
else
{
bufp->regs_allocated = REGS_UNALLOCATED;
regs->num_regs = 0;
regs->start = regs->end = NULL;
}
}
#ifdef _LIBC
weak_alias (__re_set_registers, re_set_registers)
#endif
/* Entry points compatible with 4.2 BSD regex library. We don't define
them unless specifically requested. */
#if defined _REGEX_RE_COMP || defined _LIBC
int
# ifdef _LIBC
weak_function
# endif
re_exec (s)
const char *s;
{
return 0 == regexec (&re_comp_buf, s, 0, NULL, 0);
}
#endif /* _REGEX_RE_COMP */
/* Internal entry point. */
/* Searches for a compiled pattern PREG in the string STRING, whose
length is LENGTH. NMATCH, PMATCH, and EFLAGS have the same
meaning as with regexec. LAST_START is START + RANGE, where
START and RANGE have the same meaning as with re_search.
Return REG_NOERROR if we find a match, and REG_NOMATCH if not,
otherwise return the error code.
Note: We assume front end functions already check ranges.
(0 <= LAST_START && LAST_START <= LENGTH) */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
re_search_internal (const regex_t *preg,
const char *string, Idx length,
Idx start, Idx last_start, Idx stop,
size_t nmatch, regmatch_t pmatch[],
int eflags)
{
reg_errcode_t err;
const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
Idx left_lim, right_lim;
int incr;
bool fl_longest_match;
int match_kind;
Idx match_first;
Idx match_last = REG_MISSING;
Idx extra_nmatch;
bool sb;
int ch;
#if defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L)
re_match_context_t mctx = { .dfa = dfa };
#else
re_match_context_t mctx;
#endif
char *fastmap = ((preg->fastmap != NULL && preg->fastmap_accurate
&& start != last_start && !preg->can_be_null)
? preg->fastmap : NULL);
RE_TRANSLATE_TYPE t = preg->translate;
#if !(defined _LIBC || (defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L))
memset (&mctx, '\0', sizeof (re_match_context_t));
mctx.dfa = dfa;
#endif
extra_nmatch = (nmatch > preg->re_nsub) ? nmatch - (preg->re_nsub + 1) : 0;
nmatch -= extra_nmatch;
/* Check if the DFA haven't been compiled. */
if (BE (preg->used == 0 || dfa->init_state == NULL
|| dfa->init_state_word == NULL || dfa->init_state_nl == NULL
|| dfa->init_state_begbuf == NULL, 0))
return REG_NOMATCH;
#ifdef DEBUG
/* We assume front-end functions already check them. */
assert (0 <= last_start && last_start <= length);
#endif
/* If initial states with non-begbuf contexts have no elements,
the regex must be anchored. If preg->newline_anchor is set,
we'll never use init_state_nl, so do not check it. */
if (dfa->init_state->nodes.nelem == 0
&& dfa->init_state_word->nodes.nelem == 0
&& (dfa->init_state_nl->nodes.nelem == 0
|| !preg->newline_anchor))
{
if (start != 0 && last_start != 0)
return REG_NOMATCH;
start = last_start = 0;
}
/* We must check the longest matching, if nmatch > 0. */
fl_longest_match = (nmatch != 0 || dfa->nbackref);
err = re_string_allocate (&mctx.input, string, length, dfa->nodes_len + 1,
preg->translate, (preg->syntax & RE_ICASE) != 0,
dfa);
if (BE (err != REG_NOERROR, 0))
goto free_return;
mctx.input.stop = stop;
mctx.input.raw_stop = stop;
mctx.input.newline_anchor = preg->newline_anchor;
err = match_ctx_init (&mctx, eflags, dfa->nbackref * 2);
if (BE (err != REG_NOERROR, 0))
goto free_return;
/* We will log all the DFA states through which the dfa pass,
if nmatch > 1, or this dfa has "multibyte node", which is a
back-reference or a node which can accept multibyte character or
multi character collating element. */
if (nmatch > 1 || dfa->has_mb_node)
{
/* Avoid overflow. */
if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= mctx.input.bufs_len, 0))
{
err = REG_ESPACE;
goto free_return;
}
mctx.state_log = re_malloc (re_dfastate_t *, mctx.input.bufs_len + 1);
if (BE (mctx.state_log == NULL, 0))
{
err = REG_ESPACE;
goto free_return;
}
}
else
mctx.state_log = NULL;
match_first = start;
mctx.input.tip_context = (eflags & REG_NOTBOL) ? CONTEXT_BEGBUF
: CONTEXT_NEWLINE | CONTEXT_BEGBUF;
/* Check incrementally whether of not the input string match. */
incr = (last_start < start) ? -1 : 1;
left_lim = (last_start < start) ? last_start : start;
right_lim = (last_start < start) ? start : last_start;
sb = dfa->mb_cur_max == 1;
match_kind =
(fastmap
? ((sb || !(preg->syntax & RE_ICASE || t) ? 4 : 0)
| (start <= last_start ? 2 : 0)
| (t != NULL ? 1 : 0))
: 8);
for (;; match_first += incr)
{
err = REG_NOMATCH;
if (match_first < left_lim || right_lim < match_first)
goto free_return;
/* Advance as rapidly as possible through the string, until we
find a plausible place to start matching. This may be done
with varying efficiency, so there are various possibilities:
only the most common of them are specialized, in order to
save on code size. We use a switch statement for speed. */
switch (match_kind)
{
case 8:
/* No fastmap. */
break;
case 7:
/* Fastmap with single-byte translation, match forward. */
while (BE (match_first < right_lim, 1)
&& !fastmap[t[(unsigned char) string[match_first]]])
++match_first;
goto forward_match_found_start_or_reached_end;
case 6:
/* Fastmap without translation, match forward. */
while (BE (match_first < right_lim, 1)
&& !fastmap[(unsigned char) string[match_first]])
++match_first;
forward_match_found_start_or_reached_end:
if (BE (match_first == right_lim, 0))
{
ch = match_first >= length
? 0 : (unsigned char) string[match_first];
if (!fastmap[t ? t[ch] : ch])
goto free_return;
}
break;
case 4:
case 5:
/* Fastmap without multi-byte translation, match backwards. */
while (match_first >= left_lim)
{
ch = match_first >= length
? 0 : (unsigned char) string[match_first];
if (fastmap[t ? t[ch] : ch])
break;
--match_first;
}
if (match_first < left_lim)
goto free_return;
break;
default:
/* In this case, we can't determine easily the current byte,
since it might be a component byte of a multibyte
character. Then we use the constructed buffer instead. */
for (;;)
{
/* If MATCH_FIRST is out of the valid range, reconstruct the
buffers. */
__re_size_t offset = match_first - mctx.input.raw_mbs_idx;
if (BE (offset >= (__re_size_t) mctx.input.valid_raw_len, 0))
{
err = re_string_reconstruct (&mctx.input, match_first,
eflags);
if (BE (err != REG_NOERROR, 0))
goto free_return;
offset = match_first - mctx.input.raw_mbs_idx;
}
/* If MATCH_FIRST is out of the buffer, leave it as '\0'.
Note that MATCH_FIRST must not be smaller than 0. */
ch = (match_first >= length
? 0 : re_string_byte_at (&mctx.input, offset));
if (fastmap[ch])
break;
match_first += incr;
if (match_first < left_lim || match_first > right_lim)
{
err = REG_NOMATCH;
goto free_return;
}
}
break;
}
/* Reconstruct the buffers so that the matcher can assume that
the matching starts from the beginning of the buffer. */
err = re_string_reconstruct (&mctx.input, match_first, eflags);
if (BE (err != REG_NOERROR, 0))
goto free_return;
#ifdef RE_ENABLE_I18N
/* Don't consider this char as a possible match start if it part,
yet isn't the head, of a multibyte character. */
if (!sb && !re_string_first_byte (&mctx.input, 0))
continue;
#endif
/* It seems to be appropriate one, then use the matcher. */
/* We assume that the matching starts from 0. */
mctx.state_log_top = mctx.nbkref_ents = mctx.max_mb_elem_len = 0;
match_last = check_matching (&mctx, fl_longest_match,
start <= last_start ? &match_first : NULL);
if (match_last != REG_MISSING)
{
if (BE (match_last == REG_ERROR, 0))
{
err = REG_ESPACE;
goto free_return;
}
else
{
mctx.match_last = match_last;
if ((!preg->no_sub && nmatch > 1) || dfa->nbackref)
{
re_dfastate_t *pstate = mctx.state_log[match_last];
mctx.last_node = check_halt_state_context (&mctx, pstate,
match_last);
}
if ((!preg->no_sub && nmatch > 1 && dfa->has_plural_match)
|| dfa->nbackref)
{
err = prune_impossible_nodes (&mctx);
if (err == REG_NOERROR)
break;
if (BE (err != REG_NOMATCH, 0))
goto free_return;
match_last = REG_MISSING;
}
else
break; /* We found a match. */
}
}
match_ctx_clean (&mctx);
}
#ifdef DEBUG
assert (match_last != REG_MISSING);
assert (err == REG_NOERROR);
#endif
/* Set pmatch[] if we need. */
if (nmatch > 0)
{
Idx reg_idx;
/* Initialize registers. */
for (reg_idx = 1; reg_idx < nmatch; ++reg_idx)
pmatch[reg_idx].rm_so = pmatch[reg_idx].rm_eo = -1;
/* Set the points where matching start/end. */
pmatch[0].rm_so = 0;
pmatch[0].rm_eo = mctx.match_last;
/* FIXME: This function should fail if mctx.match_last exceeds
the maximum possible regoff_t value. We need a new error
code REG_OVERFLOW. */
if (!preg->no_sub && nmatch > 1)
{
err = set_regs (preg, &mctx, nmatch, pmatch,
dfa->has_plural_match && dfa->nbackref > 0);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
/* At last, add the offset to the each registers, since we slided
the buffers so that we could assume that the matching starts
from 0. */
for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
if (pmatch[reg_idx].rm_so != -1)
{
#ifdef RE_ENABLE_I18N
if (BE (mctx.input.offsets_needed != 0, 0))
{
pmatch[reg_idx].rm_so =
(pmatch[reg_idx].rm_so == mctx.input.valid_len
? mctx.input.valid_raw_len
: mctx.input.offsets[pmatch[reg_idx].rm_so]);
pmatch[reg_idx].rm_eo =
(pmatch[reg_idx].rm_eo == mctx.input.valid_len
? mctx.input.valid_raw_len
: mctx.input.offsets[pmatch[reg_idx].rm_eo]);
}
#else
assert (mctx.input.offsets_needed == 0);
#endif
pmatch[reg_idx].rm_so += match_first;
pmatch[reg_idx].rm_eo += match_first;
}
for (reg_idx = 0; reg_idx < extra_nmatch; ++reg_idx)
{
pmatch[nmatch + reg_idx].rm_so = -1;
pmatch[nmatch + reg_idx].rm_eo = -1;
}
if (dfa->subexp_map)
for (reg_idx = 0; reg_idx + 1 < nmatch; reg_idx++)
if (dfa->subexp_map[reg_idx] != reg_idx)
{
pmatch[reg_idx + 1].rm_so
= pmatch[dfa->subexp_map[reg_idx] + 1].rm_so;
pmatch[reg_idx + 1].rm_eo
= pmatch[dfa->subexp_map[reg_idx] + 1].rm_eo;
}
}
free_return:
re_free (mctx.state_log);
if (dfa->nbackref)
match_ctx_free (&mctx);
re_string_destruct (&mctx.input);
return err;
}
static reg_errcode_t
internal_function __attribute_warn_unused_result__
prune_impossible_nodes (re_match_context_t *mctx)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx halt_node, match_last;
reg_errcode_t ret;
re_dfastate_t **sifted_states;
re_dfastate_t **lim_states = NULL;
re_sift_context_t sctx;
#ifdef DEBUG
assert (mctx->state_log != NULL);
#endif
match_last = mctx->match_last;
halt_node = mctx->last_node;
/* Avoid overflow. */
if (BE (SIZE_MAX / sizeof (re_dfastate_t *) <= match_last, 0))
return REG_ESPACE;
sifted_states = re_malloc (re_dfastate_t *, match_last + 1);
if (BE (sifted_states == NULL, 0))
{
ret = REG_ESPACE;
goto free_return;
}
if (dfa->nbackref)
{
lim_states = re_malloc (re_dfastate_t *, match_last + 1);
if (BE (lim_states == NULL, 0))
{
ret = REG_ESPACE;
goto free_return;
}
while (1)
{
memset (lim_states, '\0',
sizeof (re_dfastate_t *) * (match_last + 1));
sift_ctx_init (&sctx, sifted_states, lim_states, halt_node,
match_last);
ret = sift_states_backward (mctx, &sctx);
re_node_set_free (&sctx.limits);
if (BE (ret != REG_NOERROR, 0))
goto free_return;
if (sifted_states[0] != NULL || lim_states[0] != NULL)
break;
do
{
--match_last;
if (! REG_VALID_INDEX (match_last))
{
ret = REG_NOMATCH;
goto free_return;
}
} while (mctx->state_log[match_last] == NULL
|| !mctx->state_log[match_last]->halt);
halt_node = check_halt_state_context (mctx,
mctx->state_log[match_last],
match_last);
}
ret = merge_state_array (dfa, sifted_states, lim_states,
match_last + 1);
re_free (lim_states);
lim_states = NULL;
if (BE (ret != REG_NOERROR, 0))
goto free_return;
}
else
{
sift_ctx_init (&sctx, sifted_states, lim_states, halt_node, match_last);
ret = sift_states_backward (mctx, &sctx);
re_node_set_free (&sctx.limits);
if (BE (ret != REG_NOERROR, 0))
goto free_return;
if (sifted_states[0] == NULL)
{
ret = REG_NOMATCH;
goto free_return;
}
}
re_free (mctx->state_log);
mctx->state_log = sifted_states;
sifted_states = NULL;
mctx->last_node = halt_node;
mctx->match_last = match_last;
ret = REG_NOERROR;
free_return:
re_free (sifted_states);
re_free (lim_states);
return ret;
}
/* Acquire an initial state and return it.
We must select appropriate initial state depending on the context,
since initial states may have constraints like "\<", "^", etc.. */
static inline re_dfastate_t *
__attribute ((always_inline)) internal_function
acquire_init_state_context (reg_errcode_t *err, const re_match_context_t *mctx,
Idx idx)
{
const re_dfa_t *const dfa = mctx->dfa;
if (dfa->init_state->has_constraint)
{
unsigned int context;
context = re_string_context_at (&mctx->input, idx - 1, mctx->eflags);
if (IS_WORD_CONTEXT (context))
return dfa->init_state_word;
else if (IS_ORDINARY_CONTEXT (context))
return dfa->init_state;
else if (IS_BEGBUF_CONTEXT (context) && IS_NEWLINE_CONTEXT (context))
return dfa->init_state_begbuf;
else if (IS_NEWLINE_CONTEXT (context))
return dfa->init_state_nl;
else if (IS_BEGBUF_CONTEXT (context))
{
/* It is relatively rare case, then calculate on demand. */
return re_acquire_state_context (err, dfa,
dfa->init_state->entrance_nodes,
context);
}
else
/* Must not happen? */
return dfa->init_state;
}
else
return dfa->init_state;
}
/* Check whether the regular expression match input string INPUT or not,
and return the index where the matching end. Return REG_MISSING if
there is no match, and return REG_ERROR in case of an error.
FL_LONGEST_MATCH means we want the POSIX longest matching.
If P_MATCH_FIRST is not NULL, and the match fails, it is set to the
next place where we may want to try matching.
Note that the matcher assume that the maching starts from the current
index of the buffer. */
static Idx
internal_function __attribute_warn_unused_result__
check_matching (re_match_context_t *mctx, bool fl_longest_match,
Idx *p_match_first)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err;
Idx match = 0;
Idx match_last = REG_MISSING;
Idx cur_str_idx = re_string_cur_idx (&mctx->input);
re_dfastate_t *cur_state;
bool at_init_state = p_match_first != NULL;
Idx next_start_idx = cur_str_idx;
err = REG_NOERROR;
cur_state = acquire_init_state_context (&err, mctx, cur_str_idx);
/* An initial state must not be NULL (invalid). */
if (BE (cur_state == NULL, 0))
{
assert (err == REG_ESPACE);
return REG_ERROR;
}
if (mctx->state_log != NULL)
{
mctx->state_log[cur_str_idx] = cur_state;
/* Check OP_OPEN_SUBEXP in the initial state in case that we use them
later. E.g. Processing back references. */
if (BE (dfa->nbackref, 0))
{
at_init_state = false;
err = check_subexp_matching_top (mctx, &cur_state->nodes, 0);
if (BE (err != REG_NOERROR, 0))
return err;
if (cur_state->has_backref)
{
err = transit_state_bkref (mctx, &cur_state->nodes);
if (BE (err != REG_NOERROR, 0))
return err;
}
}
}
/* If the RE accepts NULL string. */
if (BE (cur_state->halt, 0))
{
if (!cur_state->has_constraint
|| check_halt_state_context (mctx, cur_state, cur_str_idx))
{
if (!fl_longest_match)
return cur_str_idx;
else
{
match_last = cur_str_idx;
match = 1;
}
}
}
while (!re_string_eoi (&mctx->input))
{
re_dfastate_t *old_state = cur_state;
Idx next_char_idx = re_string_cur_idx (&mctx->input) + 1;
if (BE (next_char_idx >= mctx->input.bufs_len, 0)
|| (BE (next_char_idx >= mctx->input.valid_len, 0)
&& mctx->input.valid_len < mctx->input.len))
{
err = extend_buffers (mctx);
if (BE (err != REG_NOERROR, 0))
{
assert (err == REG_ESPACE);
return REG_ERROR;
}
}
cur_state = transit_state (&err, mctx, cur_state);
if (mctx->state_log != NULL)
cur_state = merge_state_with_log (&err, mctx, cur_state);
if (cur_state == NULL)
{
/* Reached the invalid state or an error. Try to recover a valid
state using the state log, if available and if we have not
already found a valid (even if not the longest) match. */
if (BE (err != REG_NOERROR, 0))
return REG_ERROR;
if (mctx->state_log == NULL
|| (match && !fl_longest_match)
|| (cur_state = find_recover_state (&err, mctx)) == NULL)
break;
}
if (BE (at_init_state, 0))
{
if (old_state == cur_state)
next_start_idx = next_char_idx;
else
at_init_state = false;
}
if (cur_state->halt)
{
/* Reached a halt state.
Check the halt state can satisfy the current context. */
if (!cur_state->has_constraint
|| check_halt_state_context (mctx, cur_state,
re_string_cur_idx (&mctx->input)))
{
/* We found an appropriate halt state. */
match_last = re_string_cur_idx (&mctx->input);
match = 1;
/* We found a match, do not modify match_first below. */
p_match_first = NULL;
if (!fl_longest_match)
break;
}
}
}
if (p_match_first)
*p_match_first += next_start_idx;
return match_last;
}
/* Check NODE match the current context. */
static bool
internal_function
check_halt_node_context (const re_dfa_t *dfa, Idx node, unsigned int context)
{
re_token_type_t type = dfa->nodes[node].type;
unsigned int constraint = dfa->nodes[node].constraint;
if (type != END_OF_RE)
return false;
if (!constraint)
return true;
if (NOT_SATISFY_NEXT_CONSTRAINT (constraint, context))
return false;
return true;
}
/* Check the halt state STATE match the current context.
Return 0 if not match, if the node, STATE has, is a halt node and
match the context, return the node. */
static Idx
internal_function
check_halt_state_context (const re_match_context_t *mctx,
const re_dfastate_t *state, Idx idx)
{
Idx i;
unsigned int context;
#ifdef DEBUG
assert (state->halt);
#endif
context = re_string_context_at (&mctx->input, idx, mctx->eflags);
for (i = 0; i < state->nodes.nelem; ++i)
if (check_halt_node_context (mctx->dfa, state->nodes.elems[i], context))
return state->nodes.elems[i];
return 0;
}
/* Compute the next node to which "NFA" transit from NODE("NFA" is a NFA
corresponding to the DFA).
Return the destination node, and update EPS_VIA_NODES;
return REG_MISSING in case of errors. */
static Idx
internal_function
proceed_next_node (const re_match_context_t *mctx, Idx nregs, regmatch_t *regs,
Idx *pidx, Idx node, re_node_set *eps_via_nodes,
struct re_fail_stack_t *fs)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx i;
bool ok;
if (IS_EPSILON_NODE (dfa->nodes[node].type))
{
re_node_set *cur_nodes = &mctx->state_log[*pidx]->nodes;
re_node_set *edests = &dfa->edests[node];
Idx dest_node;
ok = re_node_set_insert (eps_via_nodes, node);
if (BE (! ok, 0))
return REG_ERROR;
/* Pick up a valid destination, or return REG_MISSING if none
is found. */
for (dest_node = REG_MISSING, i = 0; i < edests->nelem; ++i)
{
Idx candidate = edests->elems[i];
if (!re_node_set_contains (cur_nodes, candidate))
continue;
if (dest_node == REG_MISSING)
dest_node = candidate;
else
{
/* In order to avoid infinite loop like "(a*)*", return the second
epsilon-transition if the first was already considered. */
if (re_node_set_contains (eps_via_nodes, dest_node))
return candidate;
/* Otherwise, push the second epsilon-transition on the fail stack. */
else if (fs != NULL
&& push_fail_stack (fs, *pidx, candidate, nregs, regs,
eps_via_nodes))
return REG_ERROR;
/* We know we are going to exit. */
break;
}
}
return dest_node;
}
else
{
Idx naccepted = 0;
re_token_type_t type = dfa->nodes[node].type;
#ifdef RE_ENABLE_I18N
if (dfa->nodes[node].accept_mb)
naccepted = check_node_accept_bytes (dfa, node, &mctx->input, *pidx);
else
#endif /* RE_ENABLE_I18N */
if (type == OP_BACK_REF)
{
Idx subexp_idx = dfa->nodes[node].opr.idx + 1;
naccepted = regs[subexp_idx].rm_eo - regs[subexp_idx].rm_so;
if (fs != NULL)
{
if (regs[subexp_idx].rm_so == -1 || regs[subexp_idx].rm_eo == -1)
return REG_MISSING;
else if (naccepted)
{
char *buf = (char *) re_string_get_buffer (&mctx->input);
if (memcmp (buf + regs[subexp_idx].rm_so, buf + *pidx,
naccepted) != 0)
return REG_MISSING;
}
}
if (naccepted == 0)
{
Idx dest_node;
ok = re_node_set_insert (eps_via_nodes, node);
if (BE (! ok, 0))
return REG_ERROR;
dest_node = dfa->edests[node].elems[0];
if (re_node_set_contains (&mctx->state_log[*pidx]->nodes,
dest_node))
return dest_node;
}
}
if (naccepted != 0
|| check_node_accept (mctx, dfa->nodes + node, *pidx))
{
Idx dest_node = dfa->nexts[node];
*pidx = (naccepted == 0) ? *pidx + 1 : *pidx + naccepted;
if (fs && (*pidx > mctx->match_last || mctx->state_log[*pidx] == NULL
|| !re_node_set_contains (&mctx->state_log[*pidx]->nodes,
dest_node)))
return REG_MISSING;
re_node_set_empty (eps_via_nodes);
return dest_node;
}
}
return REG_MISSING;
}
static reg_errcode_t
internal_function __attribute_warn_unused_result__
push_fail_stack (struct re_fail_stack_t *fs, Idx str_idx, Idx dest_node,
Idx nregs, regmatch_t *regs, re_node_set *eps_via_nodes)
{
reg_errcode_t err;
Idx num = fs->num++;
if (fs->num == fs->alloc)
{
struct re_fail_stack_ent_t *new_array;
new_array = realloc (fs->stack, (sizeof (struct re_fail_stack_ent_t)
* fs->alloc * 2));
if (new_array == NULL)
return REG_ESPACE;
fs->alloc *= 2;
fs->stack = new_array;
}
fs->stack[num].idx = str_idx;
fs->stack[num].node = dest_node;
fs->stack[num].regs = re_malloc (regmatch_t, nregs);
if (fs->stack[num].regs == NULL)
return REG_ESPACE;
memcpy (fs->stack[num].regs, regs, sizeof (regmatch_t) * nregs);
err = re_node_set_init_copy (&fs->stack[num].eps_via_nodes, eps_via_nodes);
return err;
}
static Idx
internal_function
pop_fail_stack (struct re_fail_stack_t *fs, Idx *pidx, Idx nregs,
regmatch_t *regs, re_node_set *eps_via_nodes)
{
Idx num = --fs->num;
assert (REG_VALID_INDEX (num));
*pidx = fs->stack[num].idx;
memcpy (regs, fs->stack[num].regs, sizeof (regmatch_t) * nregs);
re_node_set_free (eps_via_nodes);
re_free (fs->stack[num].regs);
*eps_via_nodes = fs->stack[num].eps_via_nodes;
return fs->stack[num].node;
}
/* Set the positions where the subexpressions are starts/ends to registers
PMATCH.
Note: We assume that pmatch[0] is already set, and
pmatch[i].rm_so == pmatch[i].rm_eo == -1 for 0 < i < nmatch. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
set_regs (const regex_t *preg, const re_match_context_t *mctx, size_t nmatch,
regmatch_t *pmatch, bool fl_backtrack)
{
const re_dfa_t *dfa = (const re_dfa_t *) preg->buffer;
Idx idx, cur_node;
re_node_set eps_via_nodes;
struct re_fail_stack_t *fs;
struct re_fail_stack_t fs_body = { 0, 2, NULL };
regmatch_t *prev_idx_match;
bool prev_idx_match_malloced = false;
#ifdef DEBUG
assert (nmatch > 1);
assert (mctx->state_log != NULL);
#endif
if (fl_backtrack)
{
fs = &fs_body;
fs->stack = re_malloc (struct re_fail_stack_ent_t, fs->alloc);
if (fs->stack == NULL)
return REG_ESPACE;
}
else
fs = NULL;
cur_node = dfa->init_node;
re_node_set_init_empty (&eps_via_nodes);
if (__libc_use_alloca (nmatch * sizeof (regmatch_t)))
prev_idx_match = (regmatch_t *) alloca (nmatch * sizeof (regmatch_t));
else
{
prev_idx_match = re_malloc (regmatch_t, nmatch);
if (prev_idx_match == NULL)
{
free_fail_stack_return (fs);
return REG_ESPACE;
}
prev_idx_match_malloced = true;
}
memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
for (idx = pmatch[0].rm_so; idx <= pmatch[0].rm_eo ;)
{
update_regs (dfa, pmatch, prev_idx_match, cur_node, idx, nmatch);
if (idx == pmatch[0].rm_eo && cur_node == mctx->last_node)
{
Idx reg_idx;
if (fs)
{
for (reg_idx = 0; reg_idx < nmatch; ++reg_idx)
if (pmatch[reg_idx].rm_so > -1 && pmatch[reg_idx].rm_eo == -1)
break;
if (reg_idx == nmatch)
{
re_node_set_free (&eps_via_nodes);
if (prev_idx_match_malloced)
re_free (prev_idx_match);
return free_fail_stack_return (fs);
}
cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
&eps_via_nodes);
}
else
{
re_node_set_free (&eps_via_nodes);
if (prev_idx_match_malloced)
re_free (prev_idx_match);
return REG_NOERROR;
}
}
/* Proceed to next node. */
cur_node = proceed_next_node (mctx, nmatch, pmatch, &idx, cur_node,
&eps_via_nodes, fs);
if (BE (! REG_VALID_INDEX (cur_node), 0))
{
if (BE (cur_node == REG_ERROR, 0))
{
re_node_set_free (&eps_via_nodes);
if (prev_idx_match_malloced)
re_free (prev_idx_match);
free_fail_stack_return (fs);
return REG_ESPACE;
}
if (fs)
cur_node = pop_fail_stack (fs, &idx, nmatch, pmatch,
&eps_via_nodes);
else
{
re_node_set_free (&eps_via_nodes);
if (prev_idx_match_malloced)
re_free (prev_idx_match);
return REG_NOMATCH;
}
}
}
re_node_set_free (&eps_via_nodes);
if (prev_idx_match_malloced)
re_free (prev_idx_match);
return free_fail_stack_return (fs);
}
static reg_errcode_t
internal_function
free_fail_stack_return (struct re_fail_stack_t *fs)
{
if (fs)
{
Idx fs_idx;
for (fs_idx = 0; fs_idx < fs->num; ++fs_idx)
{
re_node_set_free (&fs->stack[fs_idx].eps_via_nodes);
re_free (fs->stack[fs_idx].regs);
}
re_free (fs->stack);
}
return REG_NOERROR;
}
static void
internal_function
update_regs (const re_dfa_t *dfa, regmatch_t *pmatch,
regmatch_t *prev_idx_match, Idx cur_node, Idx cur_idx, Idx nmatch)
{
int type = dfa->nodes[cur_node].type;
if (type == OP_OPEN_SUBEXP)
{
Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
/* We are at the first node of this sub expression. */
if (reg_num < nmatch)
{
pmatch[reg_num].rm_so = cur_idx;
pmatch[reg_num].rm_eo = -1;
}
}
else if (type == OP_CLOSE_SUBEXP)
{
Idx reg_num = dfa->nodes[cur_node].opr.idx + 1;
if (reg_num < nmatch)
{
/* We are at the last node of this sub expression. */
if (pmatch[reg_num].rm_so < cur_idx)
{
pmatch[reg_num].rm_eo = cur_idx;
/* This is a non-empty match or we are not inside an optional
subexpression. Accept this right away. */
memcpy (prev_idx_match, pmatch, sizeof (regmatch_t) * nmatch);
}
else
{
if (dfa->nodes[cur_node].opt_subexp
&& prev_idx_match[reg_num].rm_so != -1)
/* We transited through an empty match for an optional
subexpression, like (a?)*, and this is not the subexp's
first match. Copy back the old content of the registers
so that matches of an inner subexpression are undone as
well, like in ((a?))*. */
memcpy (pmatch, prev_idx_match, sizeof (regmatch_t) * nmatch);
else
/* We completed a subexpression, but it may be part of
an optional one, so do not update PREV_IDX_MATCH. */
pmatch[reg_num].rm_eo = cur_idx;
}
}
}
}
/* This function checks the STATE_LOG from the SCTX->last_str_idx to 0
and sift the nodes in each states according to the following rules.
Updated state_log will be wrote to STATE_LOG.
Rules: We throw away the Node `a' in the STATE_LOG[STR_IDX] if...
1. When STR_IDX == MATCH_LAST(the last index in the state_log):
If `a' isn't the LAST_NODE and `a' can't epsilon transit to
the LAST_NODE, we throw away the node `a'.
2. When 0 <= STR_IDX < MATCH_LAST and `a' accepts
string `s' and transit to `b':
i. If 'b' isn't in the STATE_LOG[STR_IDX+strlen('s')], we throw
away the node `a'.
ii. If 'b' is in the STATE_LOG[STR_IDX+strlen('s')] but 'b' is
thrown away, we throw away the node `a'.
3. When 0 <= STR_IDX < MATCH_LAST and 'a' epsilon transit to 'b':
i. If 'b' isn't in the STATE_LOG[STR_IDX], we throw away the
node `a'.
ii. If 'b' is in the STATE_LOG[STR_IDX] but 'b' is thrown away,
we throw away the node `a'. */
#define STATE_NODE_CONTAINS(state,node) \
((state) != NULL && re_node_set_contains (&(state)->nodes, node))
static reg_errcode_t
internal_function
sift_states_backward (const re_match_context_t *mctx, re_sift_context_t *sctx)
{
reg_errcode_t err;
int null_cnt = 0;
Idx str_idx = sctx->last_str_idx;
re_node_set cur_dest;
#ifdef DEBUG
assert (mctx->state_log != NULL && mctx->state_log[str_idx] != NULL);
#endif
/* Build sifted state_log[str_idx]. It has the nodes which can epsilon
transit to the last_node and the last_node itself. */
err = re_node_set_init_1 (&cur_dest, sctx->last_node);
if (BE (err != REG_NOERROR, 0))
return err;
err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
if (BE (err != REG_NOERROR, 0))
goto free_return;
/* Then check each states in the state_log. */
while (str_idx > 0)
{
/* Update counters. */
null_cnt = (sctx->sifted_states[str_idx] == NULL) ? null_cnt + 1 : 0;
if (null_cnt > mctx->max_mb_elem_len)
{
memset (sctx->sifted_states, '\0',
sizeof (re_dfastate_t *) * str_idx);
re_node_set_free (&cur_dest);
return REG_NOERROR;
}
re_node_set_empty (&cur_dest);
--str_idx;
if (mctx->state_log[str_idx])
{
err = build_sifted_states (mctx, sctx, str_idx, &cur_dest);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
/* Add all the nodes which satisfy the following conditions:
- It can epsilon transit to a node in CUR_DEST.
- It is in CUR_SRC.
And update state_log. */
err = update_cur_sifted_state (mctx, sctx, str_idx, &cur_dest);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
err = REG_NOERROR;
free_return:
re_node_set_free (&cur_dest);
return err;
}
static reg_errcode_t
internal_function __attribute_warn_unused_result__
build_sifted_states (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx str_idx, re_node_set *cur_dest)
{
const re_dfa_t *const dfa = mctx->dfa;
const re_node_set *cur_src = &mctx->state_log[str_idx]->non_eps_nodes;
Idx i;
/* Then build the next sifted state.
We build the next sifted state on `cur_dest', and update
`sifted_states[str_idx]' with `cur_dest'.
Note:
`cur_dest' is the sifted state from `state_log[str_idx + 1]'.
`cur_src' points the node_set of the old `state_log[str_idx]'
(with the epsilon nodes pre-filtered out). */
for (i = 0; i < cur_src->nelem; i++)
{
Idx prev_node = cur_src->elems[i];
int naccepted = 0;
bool ok;
#ifdef DEBUG
re_token_type_t type = dfa->nodes[prev_node].type;
assert (!IS_EPSILON_NODE (type));
#endif
#ifdef RE_ENABLE_I18N
/* If the node may accept `multi byte'. */
if (dfa->nodes[prev_node].accept_mb)
naccepted = sift_states_iter_mb (mctx, sctx, prev_node,
str_idx, sctx->last_str_idx);
#endif /* RE_ENABLE_I18N */
/* We don't check backreferences here.
See update_cur_sifted_state(). */
if (!naccepted
&& check_node_accept (mctx, dfa->nodes + prev_node, str_idx)
&& STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + 1],
dfa->nexts[prev_node]))
naccepted = 1;
if (naccepted == 0)
continue;
if (sctx->limits.nelem)
{
Idx to_idx = str_idx + naccepted;
if (check_dst_limits (mctx, &sctx->limits,
dfa->nexts[prev_node], to_idx,
prev_node, str_idx))
continue;
}
ok = re_node_set_insert (cur_dest, prev_node);
if (BE (! ok, 0))
return REG_ESPACE;
}
return REG_NOERROR;
}
/* Helper functions. */
static reg_errcode_t
internal_function
clean_state_log_if_needed (re_match_context_t *mctx, Idx next_state_log_idx)
{
Idx top = mctx->state_log_top;
if (next_state_log_idx >= mctx->input.bufs_len
|| (next_state_log_idx >= mctx->input.valid_len
&& mctx->input.valid_len < mctx->input.len))
{
reg_errcode_t err;
err = extend_buffers (mctx);
if (BE (err != REG_NOERROR, 0))
return err;
}
if (top < next_state_log_idx)
{
memset (mctx->state_log + top + 1, '\0',
sizeof (re_dfastate_t *) * (next_state_log_idx - top));
mctx->state_log_top = next_state_log_idx;
}
return REG_NOERROR;
}
static reg_errcode_t
internal_function
merge_state_array (const re_dfa_t *dfa, re_dfastate_t **dst,
re_dfastate_t **src, Idx num)
{
Idx st_idx;
reg_errcode_t err;
for (st_idx = 0; st_idx < num; ++st_idx)
{
if (dst[st_idx] == NULL)
dst[st_idx] = src[st_idx];
else if (src[st_idx] != NULL)
{
re_node_set merged_set;
err = re_node_set_init_union (&merged_set, &dst[st_idx]->nodes,
&src[st_idx]->nodes);
if (BE (err != REG_NOERROR, 0))
return err;
dst[st_idx] = re_acquire_state (&err, dfa, &merged_set);
re_node_set_free (&merged_set);
if (BE (err != REG_NOERROR, 0))
return err;
}
}
return REG_NOERROR;
}
static reg_errcode_t
internal_function
update_cur_sifted_state (const re_match_context_t *mctx,
re_sift_context_t *sctx, Idx str_idx,
re_node_set *dest_nodes)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err = REG_NOERROR;
const re_node_set *candidates;
candidates = ((mctx->state_log[str_idx] == NULL) ? NULL
: &mctx->state_log[str_idx]->nodes);
if (dest_nodes->nelem == 0)
sctx->sifted_states[str_idx] = NULL;
else
{
if (candidates)
{
/* At first, add the nodes which can epsilon transit to a node in
DEST_NODE. */
err = add_epsilon_src_nodes (dfa, dest_nodes, candidates);
if (BE (err != REG_NOERROR, 0))
return err;
/* Then, check the limitations in the current sift_context. */
if (sctx->limits.nelem)
{
err = check_subexp_limits (dfa, dest_nodes, candidates, &sctx->limits,
mctx->bkref_ents, str_idx);
if (BE (err != REG_NOERROR, 0))
return err;
}
}
sctx->sifted_states[str_idx] = re_acquire_state (&err, dfa, dest_nodes);
if (BE (err != REG_NOERROR, 0))
return err;
}
if (candidates && mctx->state_log[str_idx]->has_backref)
{
err = sift_states_bkref (mctx, sctx, str_idx, candidates);
if (BE (err != REG_NOERROR, 0))
return err;
}
return REG_NOERROR;
}
static reg_errcode_t
internal_function __attribute_warn_unused_result__
add_epsilon_src_nodes (const re_dfa_t *dfa, re_node_set *dest_nodes,
const re_node_set *candidates)
{
reg_errcode_t err = REG_NOERROR;
Idx i;
re_dfastate_t *state = re_acquire_state (&err, dfa, dest_nodes);
if (BE (err != REG_NOERROR, 0))
return err;
if (!state->inveclosure.alloc)
{
err = re_node_set_alloc (&state->inveclosure, dest_nodes->nelem);
if (BE (err != REG_NOERROR, 0))
return REG_ESPACE;
for (i = 0; i < dest_nodes->nelem; i++)
{
err = re_node_set_merge (&state->inveclosure,
dfa->inveclosures + dest_nodes->elems[i]);
if (BE (err != REG_NOERROR, 0))
return REG_ESPACE;
}
}
return re_node_set_add_intersect (dest_nodes, candidates,
&state->inveclosure);
}
static reg_errcode_t
internal_function
sub_epsilon_src_nodes (const re_dfa_t *dfa, Idx node, re_node_set *dest_nodes,
const re_node_set *candidates)
{
Idx ecl_idx;
reg_errcode_t err;
re_node_set *inv_eclosure = dfa->inveclosures + node;
re_node_set except_nodes;
re_node_set_init_empty (&except_nodes);
for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
{
Idx cur_node = inv_eclosure->elems[ecl_idx];
if (cur_node == node)
continue;
if (IS_EPSILON_NODE (dfa->nodes[cur_node].type))
{
Idx edst1 = dfa->edests[cur_node].elems[0];
Idx edst2 = ((dfa->edests[cur_node].nelem > 1)
? dfa->edests[cur_node].elems[1] : REG_MISSING);
if ((!re_node_set_contains (inv_eclosure, edst1)
&& re_node_set_contains (dest_nodes, edst1))
|| (REG_VALID_NONZERO_INDEX (edst2)
&& !re_node_set_contains (inv_eclosure, edst2)
&& re_node_set_contains (dest_nodes, edst2)))
{
err = re_node_set_add_intersect (&except_nodes, candidates,
dfa->inveclosures + cur_node);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&except_nodes);
return err;
}
}
}
}
for (ecl_idx = 0; ecl_idx < inv_eclosure->nelem; ++ecl_idx)
{
Idx cur_node = inv_eclosure->elems[ecl_idx];
if (!re_node_set_contains (&except_nodes, cur_node))
{
Idx idx = re_node_set_contains (dest_nodes, cur_node) - 1;
re_node_set_remove_at (dest_nodes, idx);
}
}
re_node_set_free (&except_nodes);
return REG_NOERROR;
}
static bool
internal_function
check_dst_limits (const re_match_context_t *mctx, const re_node_set *limits,
Idx dst_node, Idx dst_idx, Idx src_node, Idx src_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx lim_idx, src_pos, dst_pos;
Idx dst_bkref_idx = search_cur_bkref_entry (mctx, dst_idx);
Idx src_bkref_idx = search_cur_bkref_entry (mctx, src_idx);
for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
{
Idx subexp_idx;
struct re_backref_cache_entry *ent;
ent = mctx->bkref_ents + limits->elems[lim_idx];
subexp_idx = dfa->nodes[ent->node].opr.idx;
dst_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
subexp_idx, dst_node, dst_idx,
dst_bkref_idx);
src_pos = check_dst_limits_calc_pos (mctx, limits->elems[lim_idx],
subexp_idx, src_node, src_idx,
src_bkref_idx);
/* In case of:
<src> <dst> ( <subexp> )
( <subexp> ) <src> <dst>
( <subexp1> <src> <subexp2> <dst> <subexp3> ) */
if (src_pos == dst_pos)
continue; /* This is unrelated limitation. */
else
return true;
}
return false;
}
static int
internal_function
check_dst_limits_calc_pos_1 (const re_match_context_t *mctx, int boundaries,
Idx subexp_idx, Idx from_node, Idx bkref_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
const re_node_set *eclosures = dfa->eclosures + from_node;
Idx node_idx;
/* Else, we are on the boundary: examine the nodes on the epsilon
closure. */
for (node_idx = 0; node_idx < eclosures->nelem; ++node_idx)
{
Idx node = eclosures->elems[node_idx];
switch (dfa->nodes[node].type)
{
case OP_BACK_REF:
if (bkref_idx != REG_MISSING)
{
struct re_backref_cache_entry *ent = mctx->bkref_ents + bkref_idx;
do
{
Idx dst;
int cpos;
if (ent->node != node)
continue;
if (subexp_idx < BITSET_WORD_BITS
&& !(ent->eps_reachable_subexps_map
& ((bitset_word_t) 1 << subexp_idx)))
continue;
/* Recurse trying to reach the OP_OPEN_SUBEXP and
OP_CLOSE_SUBEXP cases below. But, if the
destination node is the same node as the source
node, don't recurse because it would cause an
infinite loop: a regex that exhibits this behavior
is ()\1*\1* */
dst = dfa->edests[node].elems[0];
if (dst == from_node)
{
if (boundaries & 1)
return -1;
else /* if (boundaries & 2) */
return 0;
}
cpos =
check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
dst, bkref_idx);
if (cpos == -1 /* && (boundaries & 1) */)
return -1;
if (cpos == 0 && (boundaries & 2))
return 0;
if (subexp_idx < BITSET_WORD_BITS)
ent->eps_reachable_subexps_map
&= ~((bitset_word_t) 1 << subexp_idx);
}
while (ent++->more);
}
break;
case OP_OPEN_SUBEXP:
if ((boundaries & 1) && subexp_idx == dfa->nodes[node].opr.idx)
return -1;
break;
case OP_CLOSE_SUBEXP:
if ((boundaries & 2) && subexp_idx == dfa->nodes[node].opr.idx)
return 0;
break;
default:
break;
}
}
return (boundaries & 2) ? 1 : 0;
}
static int
internal_function
check_dst_limits_calc_pos (const re_match_context_t *mctx, Idx limit,
Idx subexp_idx, Idx from_node, Idx str_idx,
Idx bkref_idx)
{
struct re_backref_cache_entry *lim = mctx->bkref_ents + limit;
int boundaries;
/* If we are outside the range of the subexpression, return -1 or 1. */
if (str_idx < lim->subexp_from)
return -1;
if (lim->subexp_to < str_idx)
return 1;
/* If we are within the subexpression, return 0. */
boundaries = (str_idx == lim->subexp_from);
boundaries |= (str_idx == lim->subexp_to) << 1;
if (boundaries == 0)
return 0;
/* Else, examine epsilon closure. */
return check_dst_limits_calc_pos_1 (mctx, boundaries, subexp_idx,
from_node, bkref_idx);
}
/* Check the limitations of sub expressions LIMITS, and remove the nodes
which are against limitations from DEST_NODES. */
static reg_errcode_t
internal_function
check_subexp_limits (const re_dfa_t *dfa, re_node_set *dest_nodes,
const re_node_set *candidates, re_node_set *limits,
struct re_backref_cache_entry *bkref_ents, Idx str_idx)
{
reg_errcode_t err;
Idx node_idx, lim_idx;
for (lim_idx = 0; lim_idx < limits->nelem; ++lim_idx)
{
Idx subexp_idx;
struct re_backref_cache_entry *ent;
ent = bkref_ents + limits->elems[lim_idx];
if (str_idx <= ent->subexp_from || ent->str_idx < str_idx)
continue; /* This is unrelated limitation. */
subexp_idx = dfa->nodes[ent->node].opr.idx;
if (ent->subexp_to == str_idx)
{
Idx ops_node = REG_MISSING;
Idx cls_node = REG_MISSING;
for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
{
Idx node = dest_nodes->elems[node_idx];
re_token_type_t type = dfa->nodes[node].type;
if (type == OP_OPEN_SUBEXP
&& subexp_idx == dfa->nodes[node].opr.idx)
ops_node = node;
else if (type == OP_CLOSE_SUBEXP
&& subexp_idx == dfa->nodes[node].opr.idx)
cls_node = node;
}
/* Check the limitation of the open subexpression. */
/* Note that (ent->subexp_to = str_idx != ent->subexp_from). */
if (REG_VALID_INDEX (ops_node))
{
err = sub_epsilon_src_nodes (dfa, ops_node, dest_nodes,
candidates);
if (BE (err != REG_NOERROR, 0))
return err;
}
/* Check the limitation of the close subexpression. */
if (REG_VALID_INDEX (cls_node))
for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
{
Idx node = dest_nodes->elems[node_idx];
if (!re_node_set_contains (dfa->inveclosures + node,
cls_node)
&& !re_node_set_contains (dfa->eclosures + node,
cls_node))
{
/* It is against this limitation.
Remove it form the current sifted state. */
err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
candidates);
if (BE (err != REG_NOERROR, 0))
return err;
--node_idx;
}
}
}
else /* (ent->subexp_to != str_idx) */
{
for (node_idx = 0; node_idx < dest_nodes->nelem; ++node_idx)
{
Idx node = dest_nodes->elems[node_idx];
re_token_type_t type = dfa->nodes[node].type;
if (type == OP_CLOSE_SUBEXP || type == OP_OPEN_SUBEXP)
{
if (subexp_idx != dfa->nodes[node].opr.idx)
continue;
/* It is against this limitation.
Remove it form the current sifted state. */
err = sub_epsilon_src_nodes (dfa, node, dest_nodes,
candidates);
if (BE (err != REG_NOERROR, 0))
return err;
}
}
}
}
return REG_NOERROR;
}
static reg_errcode_t
internal_function __attribute_warn_unused_result__
sift_states_bkref (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx str_idx, const re_node_set *candidates)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err;
Idx node_idx, node;
re_sift_context_t local_sctx;
Idx first_idx = search_cur_bkref_entry (mctx, str_idx);
if (first_idx == REG_MISSING)
return REG_NOERROR;
local_sctx.sifted_states = NULL; /* Mark that it hasn't been initialized. */
for (node_idx = 0; node_idx < candidates->nelem; ++node_idx)
{
Idx enabled_idx;
re_token_type_t type;
struct re_backref_cache_entry *entry;
node = candidates->elems[node_idx];
type = dfa->nodes[node].type;
/* Avoid infinite loop for the REs like "()\1+". */
if (node == sctx->last_node && str_idx == sctx->last_str_idx)
continue;
if (type != OP_BACK_REF)
continue;
entry = mctx->bkref_ents + first_idx;
enabled_idx = first_idx;
do
{
Idx subexp_len;
Idx to_idx;
Idx dst_node;
bool ok;
re_dfastate_t *cur_state;
if (entry->node != node)
continue;
subexp_len = entry->subexp_to - entry->subexp_from;
to_idx = str_idx + subexp_len;
dst_node = (subexp_len ? dfa->nexts[node]
: dfa->edests[node].elems[0]);
if (to_idx > sctx->last_str_idx
|| sctx->sifted_states[to_idx] == NULL
|| !STATE_NODE_CONTAINS (sctx->sifted_states[to_idx], dst_node)
|| check_dst_limits (mctx, &sctx->limits, node,
str_idx, dst_node, to_idx))
continue;
if (local_sctx.sifted_states == NULL)
{
local_sctx = *sctx;
err = re_node_set_init_copy (&local_sctx.limits, &sctx->limits);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
local_sctx.last_node = node;
local_sctx.last_str_idx = str_idx;
ok = re_node_set_insert (&local_sctx.limits, enabled_idx);
if (BE (! ok, 0))
{
err = REG_ESPACE;
goto free_return;
}
cur_state = local_sctx.sifted_states[str_idx];
err = sift_states_backward (mctx, &local_sctx);
if (BE (err != REG_NOERROR, 0))
goto free_return;
if (sctx->limited_states != NULL)
{
err = merge_state_array (dfa, sctx->limited_states,
local_sctx.sifted_states,
str_idx + 1);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
local_sctx.sifted_states[str_idx] = cur_state;
re_node_set_remove (&local_sctx.limits, enabled_idx);
/* mctx->bkref_ents may have changed, reload the pointer. */
entry = mctx->bkref_ents + enabled_idx;
}
while (enabled_idx++, entry++->more);
}
err = REG_NOERROR;
free_return:
if (local_sctx.sifted_states != NULL)
{
re_node_set_free (&local_sctx.limits);
}
return err;
}
#ifdef RE_ENABLE_I18N
static int
internal_function
sift_states_iter_mb (const re_match_context_t *mctx, re_sift_context_t *sctx,
Idx node_idx, Idx str_idx, Idx max_str_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
int naccepted;
/* Check the node can accept `multi byte'. */
naccepted = check_node_accept_bytes (dfa, node_idx, &mctx->input, str_idx);
if (naccepted > 0 && str_idx + naccepted <= max_str_idx &&
!STATE_NODE_CONTAINS (sctx->sifted_states[str_idx + naccepted],
dfa->nexts[node_idx]))
/* The node can't accept the `multi byte', or the
destination was already thrown away, then the node
could't accept the current input `multi byte'. */
naccepted = 0;
/* Otherwise, it is sure that the node could accept
`naccepted' bytes input. */
return naccepted;
}
#endif /* RE_ENABLE_I18N */
/* Functions for state transition. */
/* Return the next state to which the current state STATE will transit by
accepting the current input byte, and update STATE_LOG if necessary.
If STATE can accept a multibyte char/collating element/back reference
update the destination of STATE_LOG. */
static re_dfastate_t *
internal_function __attribute_warn_unused_result__
transit_state (reg_errcode_t *err, re_match_context_t *mctx,
re_dfastate_t *state)
{
re_dfastate_t **trtable;
unsigned char ch;
#ifdef RE_ENABLE_I18N
/* If the current state can accept multibyte. */
if (BE (state->accept_mb, 0))
{
*err = transit_state_mb (mctx, state);
if (BE (*err != REG_NOERROR, 0))
return NULL;
}
#endif /* RE_ENABLE_I18N */
/* Then decide the next state with the single byte. */
#if 0
if (0)
/* don't use transition table */
return transit_state_sb (err, mctx, state);
#endif
/* Use transition table */
ch = re_string_fetch_byte (&mctx->input);
for (;;)
{
trtable = state->trtable;
if (BE (trtable != NULL, 1))
return trtable[ch];
trtable = state->word_trtable;
if (BE (trtable != NULL, 1))
{
unsigned int context;
context
= re_string_context_at (&mctx->input,
re_string_cur_idx (&mctx->input) - 1,
mctx->eflags);
if (IS_WORD_CONTEXT (context))
return trtable[ch + SBC_MAX];
else
return trtable[ch];
}
if (!build_trtable (mctx->dfa, state))
{
*err = REG_ESPACE;
return NULL;
}
/* Retry, we now have a transition table. */
}
}
/* Update the state_log if we need */
static re_dfastate_t *
internal_function
merge_state_with_log (reg_errcode_t *err, re_match_context_t *mctx,
re_dfastate_t *next_state)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx cur_idx = re_string_cur_idx (&mctx->input);
if (cur_idx > mctx->state_log_top)
{
mctx->state_log[cur_idx] = next_state;
mctx->state_log_top = cur_idx;
}
else if (mctx->state_log[cur_idx] == 0)
{
mctx->state_log[cur_idx] = next_state;
}
else
{
re_dfastate_t *pstate;
unsigned int context;
re_node_set next_nodes, *log_nodes, *table_nodes = NULL;
/* If (state_log[cur_idx] != 0), it implies that cur_idx is
the destination of a multibyte char/collating element/
back reference. Then the next state is the union set of
these destinations and the results of the transition table. */
pstate = mctx->state_log[cur_idx];
log_nodes = pstate->entrance_nodes;
if (next_state != NULL)
{
table_nodes = next_state->entrance_nodes;
*err = re_node_set_init_union (&next_nodes, table_nodes,
log_nodes);
if (BE (*err != REG_NOERROR, 0))
return NULL;
}
else
next_nodes = *log_nodes;
/* Note: We already add the nodes of the initial state,
then we don't need to add them here. */
context = re_string_context_at (&mctx->input,
re_string_cur_idx (&mctx->input) - 1,
mctx->eflags);
next_state = mctx->state_log[cur_idx]
= re_acquire_state_context (err, dfa, &next_nodes, context);
/* We don't need to check errors here, since the return value of
this function is next_state and ERR is already set. */
if (table_nodes != NULL)
re_node_set_free (&next_nodes);
}
if (BE (dfa->nbackref, 0) && next_state != NULL)
{
/* Check OP_OPEN_SUBEXP in the current state in case that we use them
later. We must check them here, since the back references in the
next state might use them. */
*err = check_subexp_matching_top (mctx, &next_state->nodes,
cur_idx);
if (BE (*err != REG_NOERROR, 0))
return NULL;
/* If the next state has back references. */
if (next_state->has_backref)
{
*err = transit_state_bkref (mctx, &next_state->nodes);
if (BE (*err != REG_NOERROR, 0))
return NULL;
next_state = mctx->state_log[cur_idx];
}
}
return next_state;
}
/* Skip bytes in the input that correspond to part of a
multi-byte match, then look in the log for a state
from which to restart matching. */
static re_dfastate_t *
internal_function
find_recover_state (reg_errcode_t *err, re_match_context_t *mctx)
{
re_dfastate_t *cur_state;
do
{
Idx max = mctx->state_log_top;
Idx cur_str_idx = re_string_cur_idx (&mctx->input);
do
{
if (++cur_str_idx > max)
return NULL;
re_string_skip_bytes (&mctx->input, 1);
}
while (mctx->state_log[cur_str_idx] == NULL);
cur_state = merge_state_with_log (err, mctx, NULL);
}
while (*err == REG_NOERROR && cur_state == NULL);
return cur_state;
}
/* Helper functions for transit_state. */
/* From the node set CUR_NODES, pick up the nodes whose types are
OP_OPEN_SUBEXP and which have corresponding back references in the regular
expression. And register them to use them later for evaluating the
correspoding back references. */
static reg_errcode_t
internal_function
check_subexp_matching_top (re_match_context_t *mctx, re_node_set *cur_nodes,
Idx str_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx node_idx;
reg_errcode_t err;
/* TODO: This isn't efficient.
Because there might be more than one nodes whose types are
OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
nodes.
E.g. RE: (a){2} */
for (node_idx = 0; node_idx < cur_nodes->nelem; ++node_idx)
{
Idx node = cur_nodes->elems[node_idx];
if (dfa->nodes[node].type == OP_OPEN_SUBEXP
&& dfa->nodes[node].opr.idx < BITSET_WORD_BITS
&& (dfa->used_bkref_map
& ((bitset_word_t) 1 << dfa->nodes[node].opr.idx)))
{
err = match_ctx_add_subtop (mctx, node, str_idx);
if (BE (err != REG_NOERROR, 0))
return err;
}
}
return REG_NOERROR;
}
#if 0
/* Return the next state to which the current state STATE will transit by
accepting the current input byte. */
static re_dfastate_t *
transit_state_sb (reg_errcode_t *err, re_match_context_t *mctx,
re_dfastate_t *state)
{
const re_dfa_t *const dfa = mctx->dfa;
re_node_set next_nodes;
re_dfastate_t *next_state;
Idx node_cnt, cur_str_idx = re_string_cur_idx (&mctx->input);
unsigned int context;
*err = re_node_set_alloc (&next_nodes, state->nodes.nelem + 1);
if (BE (*err != REG_NOERROR, 0))
return NULL;
for (node_cnt = 0; node_cnt < state->nodes.nelem; ++node_cnt)
{
Idx cur_node = state->nodes.elems[node_cnt];
if (check_node_accept (mctx, dfa->nodes + cur_node, cur_str_idx))
{
*err = re_node_set_merge (&next_nodes,
dfa->eclosures + dfa->nexts[cur_node]);
if (BE (*err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return NULL;
}
}
}
context = re_string_context_at (&mctx->input, cur_str_idx, mctx->eflags);
next_state = re_acquire_state_context (err, dfa, &next_nodes, context);
/* We don't need to check errors here, since the return value of
this function is next_state and ERR is already set. */
re_node_set_free (&next_nodes);
re_string_skip_bytes (&mctx->input, 1);
return next_state;
}
#endif
#ifdef RE_ENABLE_I18N
static reg_errcode_t
internal_function
transit_state_mb (re_match_context_t *mctx, re_dfastate_t *pstate)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err;
Idx i;
for (i = 0; i < pstate->nodes.nelem; ++i)
{
re_node_set dest_nodes, *new_nodes;
Idx cur_node_idx = pstate->nodes.elems[i];
int naccepted;
Idx dest_idx;
unsigned int context;
re_dfastate_t *dest_state;
if (!dfa->nodes[cur_node_idx].accept_mb)
continue;
if (dfa->nodes[cur_node_idx].constraint)
{
context = re_string_context_at (&mctx->input,
re_string_cur_idx (&mctx->input),
mctx->eflags);
if (NOT_SATISFY_NEXT_CONSTRAINT (dfa->nodes[cur_node_idx].constraint,
context))
continue;
}
/* How many bytes the node can accept? */
naccepted = check_node_accept_bytes (dfa, cur_node_idx, &mctx->input,
re_string_cur_idx (&mctx->input));
if (naccepted == 0)
continue;
/* The node can accepts `naccepted' bytes. */
dest_idx = re_string_cur_idx (&mctx->input) + naccepted;
mctx->max_mb_elem_len = ((mctx->max_mb_elem_len < naccepted) ? naccepted
: mctx->max_mb_elem_len);
err = clean_state_log_if_needed (mctx, dest_idx);
if (BE (err != REG_NOERROR, 0))
return err;
#ifdef DEBUG
assert (dfa->nexts[cur_node_idx] != REG_MISSING);
#endif
new_nodes = dfa->eclosures + dfa->nexts[cur_node_idx];
dest_state = mctx->state_log[dest_idx];
if (dest_state == NULL)
dest_nodes = *new_nodes;
else
{
err = re_node_set_init_union (&dest_nodes,
dest_state->entrance_nodes, new_nodes);
if (BE (err != REG_NOERROR, 0))
return err;
}
context = re_string_context_at (&mctx->input, dest_idx - 1,
mctx->eflags);
mctx->state_log[dest_idx]
= re_acquire_state_context (&err, dfa, &dest_nodes, context);
if (dest_state != NULL)
re_node_set_free (&dest_nodes);
if (BE (mctx->state_log[dest_idx] == NULL && err != REG_NOERROR, 0))
return err;
}
return REG_NOERROR;
}
#endif /* RE_ENABLE_I18N */
static reg_errcode_t
internal_function
transit_state_bkref (re_match_context_t *mctx, const re_node_set *nodes)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err;
Idx i;
Idx cur_str_idx = re_string_cur_idx (&mctx->input);
for (i = 0; i < nodes->nelem; ++i)
{
Idx dest_str_idx, prev_nelem, bkc_idx;
Idx node_idx = nodes->elems[i];
unsigned int context;
const re_token_t *node = dfa->nodes + node_idx;
re_node_set *new_dest_nodes;
/* Check whether `node' is a backreference or not. */
if (node->type != OP_BACK_REF)
continue;
if (node->constraint)
{
context = re_string_context_at (&mctx->input, cur_str_idx,
mctx->eflags);
if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
continue;
}
/* `node' is a backreference.
Check the substring which the substring matched. */
bkc_idx = mctx->nbkref_ents;
err = get_subexp (mctx, node_idx, cur_str_idx);
if (BE (err != REG_NOERROR, 0))
goto free_return;
/* And add the epsilon closures (which is `new_dest_nodes') of
the backreference to appropriate state_log. */
#ifdef DEBUG
assert (dfa->nexts[node_idx] != REG_MISSING);
#endif
for (; bkc_idx < mctx->nbkref_ents; ++bkc_idx)
{
Idx subexp_len;
re_dfastate_t *dest_state;
struct re_backref_cache_entry *bkref_ent;
bkref_ent = mctx->bkref_ents + bkc_idx;
if (bkref_ent->node != node_idx || bkref_ent->str_idx != cur_str_idx)
continue;
subexp_len = bkref_ent->subexp_to - bkref_ent->subexp_from;
new_dest_nodes = (subexp_len == 0
? dfa->eclosures + dfa->edests[node_idx].elems[0]
: dfa->eclosures + dfa->nexts[node_idx]);
dest_str_idx = (cur_str_idx + bkref_ent->subexp_to
- bkref_ent->subexp_from);
context = re_string_context_at (&mctx->input, dest_str_idx - 1,
mctx->eflags);
dest_state = mctx->state_log[dest_str_idx];
prev_nelem = ((mctx->state_log[cur_str_idx] == NULL) ? 0
: mctx->state_log[cur_str_idx]->nodes.nelem);
/* Add `new_dest_node' to state_log. */
if (dest_state == NULL)
{
mctx->state_log[dest_str_idx]
= re_acquire_state_context (&err, dfa, new_dest_nodes,
context);
if (BE (mctx->state_log[dest_str_idx] == NULL
&& err != REG_NOERROR, 0))
goto free_return;
}
else
{
re_node_set dest_nodes;
err = re_node_set_init_union (&dest_nodes,
dest_state->entrance_nodes,
new_dest_nodes);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&dest_nodes);
goto free_return;
}
mctx->state_log[dest_str_idx]
= re_acquire_state_context (&err, dfa, &dest_nodes, context);
re_node_set_free (&dest_nodes);
if (BE (mctx->state_log[dest_str_idx] == NULL
&& err != REG_NOERROR, 0))
goto free_return;
}
/* We need to check recursively if the backreference can epsilon
transit. */
if (subexp_len == 0
&& mctx->state_log[cur_str_idx]->nodes.nelem > prev_nelem)
{
err = check_subexp_matching_top (mctx, new_dest_nodes,
cur_str_idx);
if (BE (err != REG_NOERROR, 0))
goto free_return;
err = transit_state_bkref (mctx, new_dest_nodes);
if (BE (err != REG_NOERROR, 0))
goto free_return;
}
}
}
err = REG_NOERROR;
free_return:
return err;
}
/* Enumerate all the candidates which the backreference BKREF_NODE can match
at BKREF_STR_IDX, and register them by match_ctx_add_entry().
Note that we might collect inappropriate candidates here.
However, the cost of checking them strictly here is too high, then we
delay these checking for prune_impossible_nodes(). */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
{
const re_dfa_t *const dfa = mctx->dfa;
Idx subexp_num, sub_top_idx;
const char *buf = (const char *) re_string_get_buffer (&mctx->input);
/* Return if we have already checked BKREF_NODE at BKREF_STR_IDX. */
Idx cache_idx = search_cur_bkref_entry (mctx, bkref_str_idx);
if (cache_idx != REG_MISSING)
{
const struct re_backref_cache_entry *entry
= mctx->bkref_ents + cache_idx;
do
if (entry->node == bkref_node)
return REG_NOERROR; /* We already checked it. */
while (entry++->more);
}
subexp_num = dfa->nodes[bkref_node].opr.idx;
/* For each sub expression */
for (sub_top_idx = 0; sub_top_idx < mctx->nsub_tops; ++sub_top_idx)
{
reg_errcode_t err;
re_sub_match_top_t *sub_top = mctx->sub_tops[sub_top_idx];
re_sub_match_last_t *sub_last;
Idx sub_last_idx, sl_str, bkref_str_off;
if (dfa->nodes[sub_top->node].opr.idx != subexp_num)
continue; /* It isn't related. */
sl_str = sub_top->str_idx;
bkref_str_off = bkref_str_idx;
/* At first, check the last node of sub expressions we already
evaluated. */
for (sub_last_idx = 0; sub_last_idx < sub_top->nlasts; ++sub_last_idx)
{
regoff_t sl_str_diff;
sub_last = sub_top->lasts[sub_last_idx];
sl_str_diff = sub_last->str_idx - sl_str;
/* The matched string by the sub expression match with the substring
at the back reference? */
if (sl_str_diff > 0)
{
if (BE (bkref_str_off + sl_str_diff > mctx->input.valid_len, 0))
{
/* Not enough chars for a successful match. */
if (bkref_str_off + sl_str_diff > mctx->input.len)
break;
err = clean_state_log_if_needed (mctx,
bkref_str_off
+ sl_str_diff);
if (BE (err != REG_NOERROR, 0))
return err;
buf = (const char *) re_string_get_buffer (&mctx->input);
}
if (memcmp (buf + bkref_str_off, buf + sl_str, sl_str_diff) != 0)
/* We don't need to search this sub expression any more. */
break;
}
bkref_str_off += sl_str_diff;
sl_str += sl_str_diff;
err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
bkref_str_idx);
/* Reload buf, since the preceding call might have reallocated
the buffer. */
buf = (const char *) re_string_get_buffer (&mctx->input);
if (err == REG_NOMATCH)
continue;
if (BE (err != REG_NOERROR, 0))
return err;
}
if (sub_last_idx < sub_top->nlasts)
continue;
if (sub_last_idx > 0)
++sl_str;
/* Then, search for the other last nodes of the sub expression. */
for (; sl_str <= bkref_str_idx; ++sl_str)
{
Idx cls_node;
regoff_t sl_str_off;
const re_node_set *nodes;
sl_str_off = sl_str - sub_top->str_idx;
/* The matched string by the sub expression match with the substring
at the back reference? */
if (sl_str_off > 0)
{
if (BE (bkref_str_off >= mctx->input.valid_len, 0))
{
/* If we are at the end of the input, we cannot match. */
if (bkref_str_off >= mctx->input.len)
break;
err = extend_buffers (mctx);
if (BE (err != REG_NOERROR, 0))
return err;
buf = (const char *) re_string_get_buffer (&mctx->input);
}
if (buf [bkref_str_off++] != buf[sl_str - 1])
break; /* We don't need to search this sub expression
any more. */
}
if (mctx->state_log[sl_str] == NULL)
continue;
/* Does this state have a ')' of the sub expression? */
nodes = &mctx->state_log[sl_str]->nodes;
cls_node = find_subexp_node (dfa, nodes, subexp_num,
OP_CLOSE_SUBEXP);
if (cls_node == REG_MISSING)
continue; /* No. */
if (sub_top->path == NULL)
{
sub_top->path = calloc (sizeof (state_array_t),
sl_str - sub_top->str_idx + 1);
if (sub_top->path == NULL)
return REG_ESPACE;
}
/* Can the OP_OPEN_SUBEXP node arrive the OP_CLOSE_SUBEXP node
in the current context? */
err = check_arrival (mctx, sub_top->path, sub_top->node,
sub_top->str_idx, cls_node, sl_str,
OP_CLOSE_SUBEXP);
if (err == REG_NOMATCH)
continue;
if (BE (err != REG_NOERROR, 0))
return err;
sub_last = match_ctx_add_sublast (sub_top, cls_node, sl_str);
if (BE (sub_last == NULL, 0))
return REG_ESPACE;
err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
bkref_str_idx);
if (err == REG_NOMATCH)
continue;
}
}
return REG_NOERROR;
}
/* Helper functions for get_subexp(). */
/* Check SUB_LAST can arrive to the back reference BKREF_NODE at BKREF_STR.
If it can arrive, register the sub expression expressed with SUB_TOP
and SUB_LAST. */
static reg_errcode_t
internal_function
get_subexp_sub (re_match_context_t *mctx, const re_sub_match_top_t *sub_top,
re_sub_match_last_t *sub_last, Idx bkref_node, Idx bkref_str)
{
reg_errcode_t err;
Idx to_idx;
/* Can the subexpression arrive the back reference? */
err = check_arrival (mctx, &sub_last->path, sub_last->node,
sub_last->str_idx, bkref_node, bkref_str,
OP_OPEN_SUBEXP);
if (err != REG_NOERROR)
return err;
err = match_ctx_add_entry (mctx, bkref_node, bkref_str, sub_top->str_idx,
sub_last->str_idx);
if (BE (err != REG_NOERROR, 0))
return err;
to_idx = bkref_str + sub_last->str_idx - sub_top->str_idx;
return clean_state_log_if_needed (mctx, to_idx);
}
/* Find the first node which is '(' or ')' and whose index is SUBEXP_IDX.
Search '(' if FL_OPEN, or search ')' otherwise.
TODO: This function isn't efficient...
Because there might be more than one nodes whose types are
OP_OPEN_SUBEXP and whose index is SUBEXP_IDX, we must check all
nodes.
E.g. RE: (a){2} */
static Idx
internal_function
find_subexp_node (const re_dfa_t *dfa, const re_node_set *nodes,
Idx subexp_idx, int type)
{
Idx cls_idx;
for (cls_idx = 0; cls_idx < nodes->nelem; ++cls_idx)
{
Idx cls_node = nodes->elems[cls_idx];
const re_token_t *node = dfa->nodes + cls_node;
if (node->type == type
&& node->opr.idx == subexp_idx)
return cls_node;
}
return REG_MISSING;
}
/* Check whether the node TOP_NODE at TOP_STR can arrive to the node
LAST_NODE at LAST_STR. We record the path onto PATH since it will be
heavily reused.
Return REG_NOERROR if it can arrive, or REG_NOMATCH otherwise. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
check_arrival (re_match_context_t *mctx, state_array_t *path, Idx top_node,
Idx top_str, Idx last_node, Idx last_str, int type)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err = REG_NOERROR;
Idx subexp_num, backup_cur_idx, str_idx, null_cnt;
re_dfastate_t *cur_state = NULL;
re_node_set *cur_nodes, next_nodes;
re_dfastate_t **backup_state_log;
unsigned int context;
subexp_num = dfa->nodes[top_node].opr.idx;
/* Extend the buffer if we need. */
if (BE (path->alloc < last_str + mctx->max_mb_elem_len + 1, 0))
{
re_dfastate_t **new_array;
Idx old_alloc = path->alloc;
Idx new_alloc = old_alloc + last_str + mctx->max_mb_elem_len + 1;
if (BE (new_alloc < old_alloc, 0)
|| BE (SIZE_MAX / sizeof (re_dfastate_t *) < new_alloc, 0))
return REG_ESPACE;
new_array = re_realloc (path->array, re_dfastate_t *, new_alloc);
if (BE (new_array == NULL, 0))
return REG_ESPACE;
path->array = new_array;
path->alloc = new_alloc;
memset (new_array + old_alloc, '\0',
sizeof (re_dfastate_t *) * (path->alloc - old_alloc));
}
str_idx = path->next_idx ? path->next_idx : top_str;
/* Temporary modify MCTX. */
backup_state_log = mctx->state_log;
backup_cur_idx = mctx->input.cur_idx;
mctx->state_log = path->array;
mctx->input.cur_idx = str_idx;
/* Setup initial node set. */
context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
if (str_idx == top_str)
{
err = re_node_set_init_1 (&next_nodes, top_node);
if (BE (err != REG_NOERROR, 0))
return err;
err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
}
else
{
cur_state = mctx->state_log[str_idx];
if (cur_state && cur_state->has_backref)
{
err = re_node_set_init_copy (&next_nodes, &cur_state->nodes);
if (BE (err != REG_NOERROR, 0))
return err;
}
else
re_node_set_init_empty (&next_nodes);
}
if (str_idx == top_str || (cur_state && cur_state->has_backref))
{
if (next_nodes.nelem)
{
err = expand_bkref_cache (mctx, &next_nodes, str_idx,
subexp_num, type);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
}
cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
if (BE (cur_state == NULL && err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
mctx->state_log[str_idx] = cur_state;
}
for (null_cnt = 0; str_idx < last_str && null_cnt <= mctx->max_mb_elem_len;)
{
re_node_set_empty (&next_nodes);
if (mctx->state_log[str_idx + 1])
{
err = re_node_set_merge (&next_nodes,
&mctx->state_log[str_idx + 1]->nodes);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
}
if (cur_state)
{
err = check_arrival_add_next_nodes (mctx, str_idx,
&cur_state->non_eps_nodes,
&next_nodes);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
}
++str_idx;
if (next_nodes.nelem)
{
err = check_arrival_expand_ecl (dfa, &next_nodes, subexp_num, type);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
err = expand_bkref_cache (mctx, &next_nodes, str_idx,
subexp_num, type);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
}
context = re_string_context_at (&mctx->input, str_idx - 1, mctx->eflags);
cur_state = re_acquire_state_context (&err, dfa, &next_nodes, context);
if (BE (cur_state == NULL && err != REG_NOERROR, 0))
{
re_node_set_free (&next_nodes);
return err;
}
mctx->state_log[str_idx] = cur_state;
null_cnt = cur_state == NULL ? null_cnt + 1 : 0;
}
re_node_set_free (&next_nodes);
cur_nodes = (mctx->state_log[last_str] == NULL ? NULL
: &mctx->state_log[last_str]->nodes);
path->next_idx = str_idx;
/* Fix MCTX. */
mctx->state_log = backup_state_log;
mctx->input.cur_idx = backup_cur_idx;
/* Then check the current node set has the node LAST_NODE. */
if (cur_nodes != NULL && re_node_set_contains (cur_nodes, last_node))
return REG_NOERROR;
return REG_NOMATCH;
}
/* Helper functions for check_arrival. */
/* Calculate the destination nodes of CUR_NODES at STR_IDX, and append them
to NEXT_NODES.
TODO: This function is similar to the functions transit_state*(),
however this function has many additional works.
Can't we unify them? */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
check_arrival_add_next_nodes (re_match_context_t *mctx, Idx str_idx,
re_node_set *cur_nodes, re_node_set *next_nodes)
{
const re_dfa_t *const dfa = mctx->dfa;
bool ok;
Idx cur_idx;
#ifdef RE_ENABLE_I18N
reg_errcode_t err = REG_NOERROR;
#endif
re_node_set union_set;
re_node_set_init_empty (&union_set);
for (cur_idx = 0; cur_idx < cur_nodes->nelem; ++cur_idx)
{
int naccepted = 0;
Idx cur_node = cur_nodes->elems[cur_idx];
#ifdef DEBUG
re_token_type_t type = dfa->nodes[cur_node].type;
assert (!IS_EPSILON_NODE (type));
#endif
#ifdef RE_ENABLE_I18N
/* If the node may accept `multi byte'. */
if (dfa->nodes[cur_node].accept_mb)
{
naccepted = check_node_accept_bytes (dfa, cur_node, &mctx->input,
str_idx);
if (naccepted > 1)
{
re_dfastate_t *dest_state;
Idx next_node = dfa->nexts[cur_node];
Idx next_idx = str_idx + naccepted;
dest_state = mctx->state_log[next_idx];
re_node_set_empty (&union_set);
if (dest_state)
{
err = re_node_set_merge (&union_set, &dest_state->nodes);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&union_set);
return err;
}
}
ok = re_node_set_insert (&union_set, next_node);
if (BE (! ok, 0))
{
re_node_set_free (&union_set);
return REG_ESPACE;
}
mctx->state_log[next_idx] = re_acquire_state (&err, dfa,
&union_set);
if (BE (mctx->state_log[next_idx] == NULL
&& err != REG_NOERROR, 0))
{
re_node_set_free (&union_set);
return err;
}
}
}
#endif /* RE_ENABLE_I18N */
if (naccepted
|| check_node_accept (mctx, dfa->nodes + cur_node, str_idx))
{
ok = re_node_set_insert (next_nodes, dfa->nexts[cur_node]);
if (BE (! ok, 0))
{
re_node_set_free (&union_set);
return REG_ESPACE;
}
}
}
re_node_set_free (&union_set);
return REG_NOERROR;
}
/* For all the nodes in CUR_NODES, add the epsilon closures of them to
CUR_NODES, however exclude the nodes which are:
- inside the sub expression whose number is EX_SUBEXP, if FL_OPEN.
- out of the sub expression whose number is EX_SUBEXP, if !FL_OPEN.
*/
static reg_errcode_t
internal_function
check_arrival_expand_ecl (const re_dfa_t *dfa, re_node_set *cur_nodes,
Idx ex_subexp, int type)
{
reg_errcode_t err;
Idx idx, outside_node;
re_node_set new_nodes;
#ifdef DEBUG
assert (cur_nodes->nelem);
#endif
err = re_node_set_alloc (&new_nodes, cur_nodes->nelem);
if (BE (err != REG_NOERROR, 0))
return err;
/* Create a new node set NEW_NODES with the nodes which are epsilon
closures of the node in CUR_NODES. */
for (idx = 0; idx < cur_nodes->nelem; ++idx)
{
Idx cur_node = cur_nodes->elems[idx];
const re_node_set *eclosure = dfa->eclosures + cur_node;
outside_node = find_subexp_node (dfa, eclosure, ex_subexp, type);
if (outside_node == REG_MISSING)
{
/* There are no problematic nodes, just merge them. */
err = re_node_set_merge (&new_nodes, eclosure);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&new_nodes);
return err;
}
}
else
{
/* There are problematic nodes, re-calculate incrementally. */
err = check_arrival_expand_ecl_sub (dfa, &new_nodes, cur_node,
ex_subexp, type);
if (BE (err != REG_NOERROR, 0))
{
re_node_set_free (&new_nodes);
return err;
}
}
}
re_node_set_free (cur_nodes);
*cur_nodes = new_nodes;
return REG_NOERROR;
}
/* Helper function for check_arrival_expand_ecl.
Check incrementally the epsilon closure of TARGET, and if it isn't
problematic append it to DST_NODES. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
check_arrival_expand_ecl_sub (const re_dfa_t *dfa, re_node_set *dst_nodes,
Idx target, Idx ex_subexp, int type)
{
Idx cur_node;
for (cur_node = target; !re_node_set_contains (dst_nodes, cur_node);)
{
bool ok;
if (dfa->nodes[cur_node].type == type
&& dfa->nodes[cur_node].opr.idx == ex_subexp)
{
if (type == OP_CLOSE_SUBEXP)
{
ok = re_node_set_insert (dst_nodes, cur_node);
if (BE (! ok, 0))
return REG_ESPACE;
}
break;
}
ok = re_node_set_insert (dst_nodes, cur_node);
if (BE (! ok, 0))
return REG_ESPACE;
if (dfa->edests[cur_node].nelem == 0)
break;
if (dfa->edests[cur_node].nelem == 2)
{
reg_errcode_t err;
err = check_arrival_expand_ecl_sub (dfa, dst_nodes,
dfa->edests[cur_node].elems[1],
ex_subexp, type);
if (BE (err != REG_NOERROR, 0))
return err;
}
cur_node = dfa->edests[cur_node].elems[0];
}
return REG_NOERROR;
}
/* For all the back references in the current state, calculate the
destination of the back references by the appropriate entry
in MCTX->BKREF_ENTS. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
expand_bkref_cache (re_match_context_t *mctx, re_node_set *cur_nodes,
Idx cur_str, Idx subexp_num, int type)
{
const re_dfa_t *const dfa = mctx->dfa;
reg_errcode_t err;
Idx cache_idx_start = search_cur_bkref_entry (mctx, cur_str);
struct re_backref_cache_entry *ent;
if (cache_idx_start == REG_MISSING)
return REG_NOERROR;
restart:
ent = mctx->bkref_ents + cache_idx_start;
do
{
Idx to_idx, next_node;
/* Is this entry ENT is appropriate? */
if (!re_node_set_contains (cur_nodes, ent->node))
continue; /* No. */
to_idx = cur_str + ent->subexp_to - ent->subexp_from;
/* Calculate the destination of the back reference, and append it
to MCTX->STATE_LOG. */
if (to_idx == cur_str)
{
/* The backreference did epsilon transit, we must re-check all the
node in the current state. */
re_node_set new_dests;
reg_errcode_t err2, err3;
next_node = dfa->edests[ent->node].elems[0];
if (re_node_set_contains (cur_nodes, next_node))
continue;
err = re_node_set_init_1 (&new_dests, next_node);
err2 = check_arrival_expand_ecl (dfa, &new_dests, subexp_num, type);
err3 = re_node_set_merge (cur_nodes, &new_dests);
re_node_set_free (&new_dests);
if (BE (err != REG_NOERROR || err2 != REG_NOERROR
|| err3 != REG_NOERROR, 0))
{
err = (err != REG_NOERROR ? err
: (err2 != REG_NOERROR ? err2 : err3));
return err;
}
/* TODO: It is still inefficient... */
goto restart;
}
else
{
re_node_set union_set;
next_node = dfa->nexts[ent->node];
if (mctx->state_log[to_idx])
{
bool ok;
if (re_node_set_contains (&mctx->state_log[to_idx]->nodes,
next_node))
continue;
err = re_node_set_init_copy (&union_set,
&mctx->state_log[to_idx]->nodes);
ok = re_node_set_insert (&union_set, next_node);
if (BE (err != REG_NOERROR || ! ok, 0))
{
re_node_set_free (&union_set);
err = err != REG_NOERROR ? err : REG_ESPACE;
return err;
}
}
else
{
err = re_node_set_init_1 (&union_set, next_node);
if (BE (err != REG_NOERROR, 0))
return err;
}
mctx->state_log[to_idx] = re_acquire_state (&err, dfa, &union_set);
re_node_set_free (&union_set);
if (BE (mctx->state_log[to_idx] == NULL
&& err != REG_NOERROR, 0))
return err;
}
}
while (ent++->more);
return REG_NOERROR;
}
/* Build transition table for the state.
Return true if successful. */
static bool
internal_function
build_trtable (const re_dfa_t *dfa, re_dfastate_t *state)
{
reg_errcode_t err;
Idx i, j;
int ch;
bool need_word_trtable = false;
bitset_word_t elem, mask;
bool dests_node_malloced = false;
bool dest_states_malloced = false;
Idx ndests; /* Number of the destination states from `state'. */
re_dfastate_t **trtable;
re_dfastate_t **dest_states = NULL, **dest_states_word, **dest_states_nl;
re_node_set follows, *dests_node;
bitset_t *dests_ch;
bitset_t acceptable;
struct dests_alloc
{
re_node_set dests_node[SBC_MAX];
bitset_t dests_ch[SBC_MAX];
} *dests_alloc;
/* We build DFA states which corresponds to the destination nodes
from `state'. `dests_node[i]' represents the nodes which i-th
destination state contains, and `dests_ch[i]' represents the
characters which i-th destination state accepts. */
if (__libc_use_alloca (sizeof (struct dests_alloc)))
dests_alloc = (struct dests_alloc *) alloca (sizeof (struct dests_alloc));
else
{
dests_alloc = re_malloc (struct dests_alloc, 1);
if (BE (dests_alloc == NULL, 0))
return false;
dests_node_malloced = true;
}
dests_node = dests_alloc->dests_node;
dests_ch = dests_alloc->dests_ch;
/* Initialize transiton table. */
state->word_trtable = state->trtable = NULL;
/* At first, group all nodes belonging to `state' into several
destinations. */
ndests = group_nodes_into_DFAstates (dfa, state, dests_node, dests_ch);
if (BE (! REG_VALID_NONZERO_INDEX (ndests), 0))
{
if (dests_node_malloced)
free (dests_alloc);
if (ndests == 0)
{
state->trtable = (re_dfastate_t **)
calloc (sizeof (re_dfastate_t *), SBC_MAX);
return true;
}
return false;
}
err = re_node_set_alloc (&follows, ndests + 1);
if (BE (err != REG_NOERROR, 0))
goto out_free;
/* Avoid arithmetic overflow in size calculation. */
if (BE ((((SIZE_MAX - (sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX)
/ (3 * sizeof (re_dfastate_t *)))
< ndests),
0))
goto out_free;
if (__libc_use_alloca ((sizeof (re_node_set) + sizeof (bitset_t)) * SBC_MAX
+ ndests * 3 * sizeof (re_dfastate_t *)))
dest_states = (re_dfastate_t **)
alloca (ndests * 3 * sizeof (re_dfastate_t *));
else
{
dest_states = (re_dfastate_t **)
malloc (ndests * 3 * sizeof (re_dfastate_t *));
if (BE (dest_states == NULL, 0))
{
out_free:
if (dest_states_malloced)
free (dest_states);
re_node_set_free (&follows);
for (i = 0; i < ndests; ++i)
re_node_set_free (dests_node + i);
if (dests_node_malloced)
free (dests_alloc);
return false;
}
dest_states_malloced = true;
}
dest_states_word = dest_states + ndests;
dest_states_nl = dest_states_word + ndests;
bitset_empty (acceptable);
/* Then build the states for all destinations. */
for (i = 0; i < ndests; ++i)
{
Idx next_node;
re_node_set_empty (&follows);
/* Merge the follows of this destination states. */
for (j = 0; j < dests_node[i].nelem; ++j)
{
next_node = dfa->nexts[dests_node[i].elems[j]];
if (next_node != REG_MISSING)
{
err = re_node_set_merge (&follows, dfa->eclosures + next_node);
if (BE (err != REG_NOERROR, 0))
goto out_free;
}
}
dest_states[i] = re_acquire_state_context (&err, dfa, &follows, 0);
if (BE (dest_states[i] == NULL && err != REG_NOERROR, 0))
goto out_free;
/* If the new state has context constraint,
build appropriate states for these contexts. */
if (dest_states[i]->has_constraint)
{
dest_states_word[i] = re_acquire_state_context (&err, dfa, &follows,
CONTEXT_WORD);
if (BE (dest_states_word[i] == NULL && err != REG_NOERROR, 0))
goto out_free;
if (dest_states[i] != dest_states_word[i] && dfa->mb_cur_max > 1)
need_word_trtable = true;
dest_states_nl[i] = re_acquire_state_context (&err, dfa, &follows,
CONTEXT_NEWLINE);
if (BE (dest_states_nl[i] == NULL && err != REG_NOERROR, 0))
goto out_free;
}
else
{
dest_states_word[i] = dest_states[i];
dest_states_nl[i] = dest_states[i];
}
bitset_merge (acceptable, dests_ch[i]);
}
if (!BE (need_word_trtable, 0))
{
/* We don't care about whether the following character is a word
character, or we are in a single-byte character set so we can
discern by looking at the character code: allocate a
256-entry transition table. */
trtable = state->trtable =
(re_dfastate_t **) calloc (sizeof (re_dfastate_t *), SBC_MAX);
if (BE (trtable == NULL, 0))
goto out_free;
/* For all characters ch...: */
for (i = 0; i < BITSET_WORDS; ++i)
for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
elem;
mask <<= 1, elem >>= 1, ++ch)
if (BE (elem & 1, 0))
{
/* There must be exactly one destination which accepts
character ch. See group_nodes_into_DFAstates. */
for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
;
/* j-th destination accepts the word character ch. */
if (dfa->word_char[i] & mask)
trtable[ch] = dest_states_word[j];
else
trtable[ch] = dest_states[j];
}
}
else
{
/* We care about whether the following character is a word
character, and we are in a multi-byte character set: discern
by looking at the character code: build two 256-entry
transition tables, one starting at trtable[0] and one
starting at trtable[SBC_MAX]. */
trtable = state->word_trtable =
(re_dfastate_t **) calloc (sizeof (re_dfastate_t *), 2 * SBC_MAX);
if (BE (trtable == NULL, 0))
goto out_free;
/* For all characters ch...: */
for (i = 0; i < BITSET_WORDS; ++i)
for (ch = i * BITSET_WORD_BITS, elem = acceptable[i], mask = 1;
elem;
mask <<= 1, elem >>= 1, ++ch)
if (BE (elem & 1, 0))
{
/* There must be exactly one destination which accepts
character ch. See group_nodes_into_DFAstates. */
for (j = 0; (dests_ch[j][i] & mask) == 0; ++j)
;
/* j-th destination accepts the word character ch. */
trtable[ch] = dest_states[j];
trtable[ch + SBC_MAX] = dest_states_word[j];
}
}
/* new line */
if (bitset_contain (acceptable, NEWLINE_CHAR))
{
/* The current state accepts newline character. */
for (j = 0; j < ndests; ++j)
if (bitset_contain (dests_ch[j], NEWLINE_CHAR))
{
/* k-th destination accepts newline character. */
trtable[NEWLINE_CHAR] = dest_states_nl[j];
if (need_word_trtable)
trtable[NEWLINE_CHAR + SBC_MAX] = dest_states_nl[j];
/* There must be only one destination which accepts
newline. See group_nodes_into_DFAstates. */
break;
}
}
if (dest_states_malloced)
free (dest_states);
re_node_set_free (&follows);
for (i = 0; i < ndests; ++i)
re_node_set_free (dests_node + i);
if (dests_node_malloced)
free (dests_alloc);
return true;
}
/* Group all nodes belonging to STATE into several destinations.
Then for all destinations, set the nodes belonging to the destination
to DESTS_NODE[i] and set the characters accepted by the destination
to DEST_CH[i]. This function return the number of destinations. */
static Idx
internal_function
group_nodes_into_DFAstates (const re_dfa_t *dfa, const re_dfastate_t *state,
re_node_set *dests_node, bitset_t *dests_ch)
{
reg_errcode_t err;
bool ok;
Idx i, j, k;
Idx ndests; /* Number of the destinations from `state'. */
bitset_t accepts; /* Characters a node can accept. */
const re_node_set *cur_nodes = &state->nodes;
bitset_empty (accepts);
ndests = 0;
/* For all the nodes belonging to `state', */
for (i = 0; i < cur_nodes->nelem; ++i)
{
re_token_t *node = &dfa->nodes[cur_nodes->elems[i]];
re_token_type_t type = node->type;
unsigned int constraint = node->constraint;
/* Enumerate all single byte character this node can accept. */
if (type == CHARACTER)
bitset_set (accepts, node->opr.c);
else if (type == SIMPLE_BRACKET)
{
bitset_merge (accepts, node->opr.sbcset);
}
else if (type == OP_PERIOD)
{
#ifdef RE_ENABLE_I18N
if (dfa->mb_cur_max > 1)
bitset_merge (accepts, dfa->sb_char);
else
#endif
bitset_set_all (accepts);
if (!(dfa->syntax & RE_DOT_NEWLINE))
bitset_clear (accepts, '\n');
if (dfa->syntax & RE_DOT_NOT_NULL)
bitset_clear (accepts, '\0');
}
#ifdef RE_ENABLE_I18N
else if (type == OP_UTF8_PERIOD)
{
if (ASCII_CHARS % BITSET_WORD_BITS == 0)
memset (accepts, -1, ASCII_CHARS / CHAR_BIT);
else
bitset_merge (accepts, utf8_sb_map);
if (!(dfa->syntax & RE_DOT_NEWLINE))
bitset_clear (accepts, '\n');
if (dfa->syntax & RE_DOT_NOT_NULL)
bitset_clear (accepts, '\0');
}
#endif
else
continue;
/* Check the `accepts' and sift the characters which are not
match it the context. */
if (constraint)
{
if (constraint & NEXT_NEWLINE_CONSTRAINT)
{
bool accepts_newline = bitset_contain (accepts, NEWLINE_CHAR);
bitset_empty (accepts);
if (accepts_newline)
bitset_set (accepts, NEWLINE_CHAR);
else
continue;
}
if (constraint & NEXT_ENDBUF_CONSTRAINT)
{
bitset_empty (accepts);
continue;
}
if (constraint & NEXT_WORD_CONSTRAINT)
{
bitset_word_t any_set = 0;
if (type == CHARACTER && !node->word_char)
{
bitset_empty (accepts);
continue;
}
#ifdef RE_ENABLE_I18N
if (dfa->mb_cur_max > 1)
for (j = 0; j < BITSET_WORDS; ++j)
any_set |= (accepts[j] &= (dfa->word_char[j] | ~dfa->sb_char[j]));
else
#endif
for (j = 0; j < BITSET_WORDS; ++j)
any_set |= (accepts[j] &= dfa->word_char[j]);
if (!any_set)
continue;
}
if (constraint & NEXT_NOTWORD_CONSTRAINT)
{
bitset_word_t any_set = 0;
if (type == CHARACTER && node->word_char)
{
bitset_empty (accepts);
continue;
}
#ifdef RE_ENABLE_I18N
if (dfa->mb_cur_max > 1)
for (j = 0; j < BITSET_WORDS; ++j)
any_set |= (accepts[j] &= ~(dfa->word_char[j] & dfa->sb_char[j]));
else
#endif
for (j = 0; j < BITSET_WORDS; ++j)
any_set |= (accepts[j] &= ~dfa->word_char[j]);
if (!any_set)
continue;
}
}
/* Then divide `accepts' into DFA states, or create a new
state. Above, we make sure that accepts is not empty. */
for (j = 0; j < ndests; ++j)
{
bitset_t intersec; /* Intersection sets, see below. */
bitset_t remains;
/* Flags, see below. */
bitset_word_t has_intersec, not_subset, not_consumed;
/* Optimization, skip if this state doesn't accept the character. */
if (type == CHARACTER && !bitset_contain (dests_ch[j], node->opr.c))
continue;
/* Enumerate the intersection set of this state and `accepts'. */
has_intersec = 0;
for (k = 0; k < BITSET_WORDS; ++k)
has_intersec |= intersec[k] = accepts[k] & dests_ch[j][k];
/* And skip if the intersection set is empty. */
if (!has_intersec)
continue;
/* Then check if this state is a subset of `accepts'. */
not_subset = not_consumed = 0;
for (k = 0; k < BITSET_WORDS; ++k)
{
not_subset |= remains[k] = ~accepts[k] & dests_ch[j][k];
not_consumed |= accepts[k] = accepts[k] & ~dests_ch[j][k];
}
/* If this state isn't a subset of `accepts', create a
new group state, which has the `remains'. */
if (not_subset)
{
bitset_copy (dests_ch[ndests], remains);
bitset_copy (dests_ch[j], intersec);
err = re_node_set_init_copy (dests_node + ndests, &dests_node[j]);
if (BE (err != REG_NOERROR, 0))
goto error_return;
++ndests;
}
/* Put the position in the current group. */
ok = re_node_set_insert (&dests_node[j], cur_nodes->elems[i]);
if (BE (! ok, 0))
goto error_return;
/* If all characters are consumed, go to next node. */
if (!not_consumed)
break;
}
/* Some characters remain, create a new group. */
if (j == ndests)
{
bitset_copy (dests_ch[ndests], accepts);
err = re_node_set_init_1 (dests_node + ndests, cur_nodes->elems[i]);
if (BE (err != REG_NOERROR, 0))
goto error_return;
++ndests;
bitset_empty (accepts);
}
}
return ndests;
error_return:
for (j = 0; j < ndests; ++j)
re_node_set_free (dests_node + j);
return REG_MISSING;
}
#ifdef RE_ENABLE_I18N
/* Check how many bytes the node `dfa->nodes[node_idx]' accepts.
Return the number of the bytes the node accepts.
STR_IDX is the current index of the input string.
This function handles the nodes which can accept one character, or
one collating element like '.', '[a-z]', opposite to the other nodes
can only accept one byte. */
static int
internal_function
check_node_accept_bytes (const re_dfa_t *dfa, Idx node_idx,
const re_string_t *input, Idx str_idx)
{
const re_token_t *node = dfa->nodes + node_idx;
int char_len, elem_len;
Idx i;
if (BE (node->type == OP_UTF8_PERIOD, 0))
{
unsigned char c = re_string_byte_at (input, str_idx), d;
if (BE (c < 0xc2, 1))
return 0;
if (str_idx + 2 > input->len)
return 0;
d = re_string_byte_at (input, str_idx + 1);
if (c < 0xe0)
return (d < 0x80 || d > 0xbf) ? 0 : 2;
else if (c < 0xf0)
{
char_len = 3;
if (c == 0xe0 && d < 0xa0)
return 0;
}
else if (c < 0xf8)
{
char_len = 4;
if (c == 0xf0 && d < 0x90)
return 0;
}
else if (c < 0xfc)
{
char_len = 5;
if (c == 0xf8 && d < 0x88)
return 0;
}
else if (c < 0xfe)
{
char_len = 6;
if (c == 0xfc && d < 0x84)
return 0;
}
else
return 0;
if (str_idx + char_len > input->len)
return 0;
for (i = 1; i < char_len; ++i)
{
d = re_string_byte_at (input, str_idx + i);
if (d < 0x80 || d > 0xbf)
return 0;
}
return char_len;
}
char_len = re_string_char_size_at (input, str_idx);
if (node->type == OP_PERIOD)
{
if (char_len <= 1)
return 0;
/* FIXME: I don't think this if is needed, as both '\n'
and '\0' are char_len == 1. */
/* '.' accepts any one character except the following two cases. */
if ((!(dfa->syntax & RE_DOT_NEWLINE) &&
re_string_byte_at (input, str_idx) == '\n') ||
((dfa->syntax & RE_DOT_NOT_NULL) &&
re_string_byte_at (input, str_idx) == '\0'))
return 0;
return char_len;
}
elem_len = re_string_elem_size_at (input, str_idx);
if ((elem_len <= 1 && char_len <= 1) || char_len == 0)
return 0;
if (node->type == COMPLEX_BRACKET)
{
const re_charset_t *cset = node->opr.mbcset;
# ifdef _LIBC
const unsigned char *pin
= ((const unsigned char *) re_string_get_buffer (input) + str_idx);
Idx j;
uint32_t nrules;
# endif /* _LIBC */
int match_len = 0;
wchar_t wc = ((cset->nranges || cset->nchar_classes || cset->nmbchars)
? re_string_wchar_at (input, str_idx) : 0);
/* match with multibyte character? */
for (i = 0; i < cset->nmbchars; ++i)
if (wc == cset->mbchars[i])
{
match_len = char_len;
goto check_node_accept_bytes_match;
}
/* match with character_class? */
for (i = 0; i < cset->nchar_classes; ++i)
{
wctype_t wt = cset->char_classes[i];
if (__iswctype (wc, wt))
{
match_len = char_len;
goto check_node_accept_bytes_match;
}
}
# ifdef _LIBC
nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
if (nrules != 0)
{
unsigned int in_collseq = 0;
const int32_t *table, *indirect;
const unsigned char *weights, *extra;
const char *collseqwc;
int32_t idx;
/* This #include defines a local function! */
# include <locale/weight.h>
/* match with collating_symbol? */
if (cset->ncoll_syms)
extra = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
for (i = 0; i < cset->ncoll_syms; ++i)
{
const unsigned char *coll_sym = extra + cset->coll_syms[i];
/* Compare the length of input collating element and
the length of current collating element. */
if (*coll_sym != elem_len)
continue;
/* Compare each bytes. */
for (j = 0; j < *coll_sym; j++)
if (pin[j] != coll_sym[1 + j])
break;
if (j == *coll_sym)
{
/* Match if every bytes is equal. */
match_len = j;
goto check_node_accept_bytes_match;
}
}
if (cset->nranges)
{
if (elem_len <= char_len)
{
collseqwc = _NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQWC);
in_collseq = __collseq_table_lookup (collseqwc, wc);
}
else
in_collseq = find_collation_sequence_value (pin, elem_len);
}
/* match with range expression? */
for (i = 0; i < cset->nranges; ++i)
if (cset->range_starts[i] <= in_collseq
&& in_collseq <= cset->range_ends[i])
{
match_len = elem_len;
goto check_node_accept_bytes_match;
}
/* match with equivalence_class? */
if (cset->nequiv_classes)
{
const unsigned char *cp = pin;
table = (const int32_t *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_TABLEMB);
weights = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_WEIGHTMB);
extra = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_EXTRAMB);
indirect = (const int32_t *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_INDIRECTMB);
int32_t idx = findidx (&cp);
if (idx > 0)
for (i = 0; i < cset->nequiv_classes; ++i)
{
int32_t equiv_class_idx = cset->equiv_classes[i];
size_t weight_len = weights[idx & 0xffffff];
if (weight_len == weights[equiv_class_idx & 0xffffff]
&& (idx >> 24) == (equiv_class_idx >> 24))
{
Idx cnt = 0;
idx &= 0xffffff;
equiv_class_idx &= 0xffffff;
while (cnt <= weight_len
&& (weights[equiv_class_idx + 1 + cnt]
== weights[idx + 1 + cnt]))
++cnt;
if (cnt > weight_len)
{
match_len = elem_len;
goto check_node_accept_bytes_match;
}
}
}
}
}
else
# endif /* _LIBC */
{
/* match with range expression? */
#if __GNUC__ >= 2 && ! (__STDC_VERSION__ < 199901L && __STRICT_ANSI__)
wchar_t cmp_buf[] = {L'\0', L'\0', wc, L'\0', L'\0', L'\0'};
#else
wchar_t cmp_buf[] = {L'\0', L'\0', L'\0', L'\0', L'\0', L'\0'};
cmp_buf[2] = wc;
#endif
for (i = 0; i < cset->nranges; ++i)
{
cmp_buf[0] = cset->range_starts[i];
cmp_buf[4] = cset->range_ends[i];
if (wcscoll (cmp_buf, cmp_buf + 2) <= 0
&& wcscoll (cmp_buf + 2, cmp_buf + 4) <= 0)
{
match_len = char_len;
goto check_node_accept_bytes_match;
}
}
}
check_node_accept_bytes_match:
if (!cset->non_match)
return match_len;
else
{
if (match_len > 0)
return 0;
else
return (elem_len > char_len) ? elem_len : char_len;
}
}
return 0;
}
# ifdef _LIBC
static unsigned int
internal_function
find_collation_sequence_value (const unsigned char *mbs, size_t mbs_len)
{
uint32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
if (nrules == 0)
{
if (mbs_len == 1)
{
/* No valid character. Match it as a single byte character. */
const unsigned char *collseq = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_COLLSEQMB);
return collseq[mbs[0]];
}
return UINT_MAX;
}
else
{
int32_t idx;
const unsigned char *extra = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB);
int32_t extrasize = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_SYMB_EXTRAMB + 1) - extra;
for (idx = 0; idx < extrasize;)
{
int mbs_cnt;
bool found = false;
int32_t elem_mbs_len;
/* Skip the name of collating element name. */
idx = idx + extra[idx] + 1;
elem_mbs_len = extra[idx++];
if (mbs_len == elem_mbs_len)
{
for (mbs_cnt = 0; mbs_cnt < elem_mbs_len; ++mbs_cnt)
if (extra[idx + mbs_cnt] != mbs[mbs_cnt])
break;
if (mbs_cnt == elem_mbs_len)
/* Found the entry. */
found = true;
}
/* Skip the byte sequence of the collating element. */
idx += elem_mbs_len;
/* Adjust for the alignment. */
idx = (idx + 3) & ~3;
/* Skip the collation sequence value. */
idx += sizeof (uint32_t);
/* Skip the wide char sequence of the collating element. */
idx = idx + sizeof (uint32_t) * (extra[idx] + 1);
/* If we found the entry, return the sequence value. */
if (found)
return *(uint32_t *) (extra + idx);
/* Skip the collation sequence value. */
idx += sizeof (uint32_t);
}
return UINT_MAX;
}
}
# endif /* _LIBC */
#endif /* RE_ENABLE_I18N */
/* Check whether the node accepts the byte which is IDX-th
byte of the INPUT. */
static bool
internal_function
check_node_accept (const re_match_context_t *mctx, const re_token_t *node,
Idx idx)
{
unsigned char ch;
ch = re_string_byte_at (&mctx->input, idx);
switch (node->type)
{
case CHARACTER:
if (node->opr.c != ch)
return false;
break;
case SIMPLE_BRACKET:
if (!bitset_contain (node->opr.sbcset, ch))
return false;
break;
#ifdef RE_ENABLE_I18N
case OP_UTF8_PERIOD:
if (ch >= ASCII_CHARS)
return false;
/* FALLTHROUGH */
#endif
case OP_PERIOD:
if ((ch == '\n' && !(mctx->dfa->syntax & RE_DOT_NEWLINE))
|| (ch == '\0' && (mctx->dfa->syntax & RE_DOT_NOT_NULL)))
return false;
break;
default:
return false;
}
if (node->constraint)
{
/* The node has constraints. Check whether the current context
satisfies the constraints. */
unsigned int context = re_string_context_at (&mctx->input, idx,
mctx->eflags);
if (NOT_SATISFY_NEXT_CONSTRAINT (node->constraint, context))
return false;
}
return true;
}
/* Extend the buffers, if the buffers have run out. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
extend_buffers (re_match_context_t *mctx)
{
reg_errcode_t ret;
re_string_t *pstr = &mctx->input;
/* Avoid overflow. */
if (BE (SIZE_MAX / 2 / sizeof (re_dfastate_t *) <= pstr->bufs_len, 0))
return REG_ESPACE;
/* Double the lengthes of the buffers. */
ret = re_string_realloc_buffers (pstr, pstr->bufs_len * 2);
if (BE (ret != REG_NOERROR, 0))
return ret;
if (mctx->state_log != NULL)
{
/* And double the length of state_log. */
/* XXX We have no indication of the size of this buffer. If this
allocation fail we have no indication that the state_log array
does not have the right size. */
re_dfastate_t **new_array = re_realloc (mctx->state_log, re_dfastate_t *,
pstr->bufs_len + 1);
if (BE (new_array == NULL, 0))
return REG_ESPACE;
mctx->state_log = new_array;
}
/* Then reconstruct the buffers. */
if (pstr->icase)
{
#ifdef RE_ENABLE_I18N
if (pstr->mb_cur_max > 1)
{
ret = build_wcs_upper_buffer (pstr);
if (BE (ret != REG_NOERROR, 0))
return ret;
}
else
#endif /* RE_ENABLE_I18N */
build_upper_buffer (pstr);
}
else
{
#ifdef RE_ENABLE_I18N
if (pstr->mb_cur_max > 1)
build_wcs_buffer (pstr);
else
#endif /* RE_ENABLE_I18N */
{
if (pstr->trans != NULL)
re_string_translate_buffer (pstr);
}
}
return REG_NOERROR;
}
/* Functions for matching context. */
/* Initialize MCTX. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
match_ctx_init (re_match_context_t *mctx, int eflags, Idx n)
{
mctx->eflags = eflags;
mctx->match_last = REG_MISSING;
if (n > 0)
{
/* Avoid overflow. */
size_t max_object_size =
MAX (sizeof (struct re_backref_cache_entry),
sizeof (re_sub_match_top_t *));
if (BE (SIZE_MAX / max_object_size < n, 0))
return REG_ESPACE;
mctx->bkref_ents = re_malloc (struct re_backref_cache_entry, n);
mctx->sub_tops = re_malloc (re_sub_match_top_t *, n);
if (BE (mctx->bkref_ents == NULL || mctx->sub_tops == NULL, 0))
return REG_ESPACE;
}
/* Already zero-ed by the caller.
else
mctx->bkref_ents = NULL;
mctx->nbkref_ents = 0;
mctx->nsub_tops = 0; */
mctx->abkref_ents = n;
mctx->max_mb_elem_len = 1;
mctx->asub_tops = n;
return REG_NOERROR;
}
/* Clean the entries which depend on the current input in MCTX.
This function must be invoked when the matcher changes the start index
of the input, or changes the input string. */
static void
internal_function
match_ctx_clean (re_match_context_t *mctx)
{
Idx st_idx;
for (st_idx = 0; st_idx < mctx->nsub_tops; ++st_idx)
{
Idx sl_idx;
re_sub_match_top_t *top = mctx->sub_tops[st_idx];
for (sl_idx = 0; sl_idx < top->nlasts; ++sl_idx)
{
re_sub_match_last_t *last = top->lasts[sl_idx];
re_free (last->path.array);
re_free (last);
}
re_free (top->lasts);
if (top->path)
{
re_free (top->path->array);
re_free (top->path);
}
free (top);
}
mctx->nsub_tops = 0;
mctx->nbkref_ents = 0;
}
/* Free all the memory associated with MCTX. */
static void
internal_function
match_ctx_free (re_match_context_t *mctx)
{
/* First, free all the memory associated with MCTX->SUB_TOPS. */
match_ctx_clean (mctx);
re_free (mctx->sub_tops);
re_free (mctx->bkref_ents);
}
/* Add a new backreference entry to MCTX.
Note that we assume that caller never call this function with duplicate
entry, and call with STR_IDX which isn't smaller than any existing entry.
*/
static reg_errcode_t
internal_function __attribute_warn_unused_result__
match_ctx_add_entry (re_match_context_t *mctx, Idx node, Idx str_idx, Idx from,
Idx to)
{
if (mctx->nbkref_ents >= mctx->abkref_ents)
{
struct re_backref_cache_entry* new_entry;
new_entry = re_realloc (mctx->bkref_ents, struct re_backref_cache_entry,
mctx->abkref_ents * 2);
if (BE (new_entry == NULL, 0))
{
re_free (mctx->bkref_ents);
return REG_ESPACE;
}
mctx->bkref_ents = new_entry;
memset (mctx->bkref_ents + mctx->nbkref_ents, '\0',
sizeof (struct re_backref_cache_entry) * mctx->abkref_ents);
mctx->abkref_ents *= 2;
}
if (mctx->nbkref_ents > 0
&& mctx->bkref_ents[mctx->nbkref_ents - 1].str_idx == str_idx)
mctx->bkref_ents[mctx->nbkref_ents - 1].more = 1;
mctx->bkref_ents[mctx->nbkref_ents].node = node;
mctx->bkref_ents[mctx->nbkref_ents].str_idx = str_idx;
mctx->bkref_ents[mctx->nbkref_ents].subexp_from = from;
mctx->bkref_ents[mctx->nbkref_ents].subexp_to = to;
/* This is a cache that saves negative results of check_dst_limits_calc_pos.
If bit N is clear, means that this entry won't epsilon-transition to
an OP_OPEN_SUBEXP or OP_CLOSE_SUBEXP for the N+1-th subexpression. If
it is set, check_dst_limits_calc_pos_1 will recurse and try to find one
such node.
A backreference does not epsilon-transition unless it is empty, so set
to all zeros if FROM != TO. */
mctx->bkref_ents[mctx->nbkref_ents].eps_reachable_subexps_map
= (from == to ? -1 : 0);
mctx->bkref_ents[mctx->nbkref_ents++].more = 0;
if (mctx->max_mb_elem_len < to - from)
mctx->max_mb_elem_len = to - from;
return REG_NOERROR;
}
/* Return the first entry with the same str_idx, or REG_MISSING if none is
found. Note that MCTX->BKREF_ENTS is already sorted by MCTX->STR_IDX. */
static Idx
internal_function
search_cur_bkref_entry (const re_match_context_t *mctx, Idx str_idx)
{
Idx left, right, mid, last;
last = right = mctx->nbkref_ents;
for (left = 0; left < right;)
{
mid = (left + right) / 2;
if (mctx->bkref_ents[mid].str_idx < str_idx)
left = mid + 1;
else
right = mid;
}
if (left < last && mctx->bkref_ents[left].str_idx == str_idx)
return left;
else
return REG_MISSING;
}
/* Register the node NODE, whose type is OP_OPEN_SUBEXP, and which matches
at STR_IDX. */
static reg_errcode_t
internal_function __attribute_warn_unused_result__
match_ctx_add_subtop (re_match_context_t *mctx, Idx node, Idx str_idx)
{
#ifdef DEBUG
assert (mctx->sub_tops != NULL);
assert (mctx->asub_tops > 0);
#endif
if (BE (mctx->nsub_tops == mctx->asub_tops, 0))
{
Idx new_asub_tops = mctx->asub_tops * 2;
re_sub_match_top_t **new_array = re_realloc (mctx->sub_tops,
re_sub_match_top_t *,
new_asub_tops);
if (BE (new_array == NULL, 0))
return REG_ESPACE;
mctx->sub_tops = new_array;
mctx->asub_tops = new_asub_tops;
}
mctx->sub_tops[mctx->nsub_tops] = calloc (1, sizeof (re_sub_match_top_t));
if (BE (mctx->sub_tops[mctx->nsub_tops] == NULL, 0))
return REG_ESPACE;
mctx->sub_tops[mctx->nsub_tops]->node = node;
mctx->sub_tops[mctx->nsub_tops++]->str_idx = str_idx;
return REG_NOERROR;
}
/* Register the node NODE, whose type is OP_CLOSE_SUBEXP, and which matches
at STR_IDX, whose corresponding OP_OPEN_SUBEXP is SUB_TOP. */
static re_sub_match_last_t *
internal_function
match_ctx_add_sublast (re_sub_match_top_t *subtop, Idx node, Idx str_idx)
{
re_sub_match_last_t *new_entry;
if (BE (subtop->nlasts == subtop->alasts, 0))
{
Idx new_alasts = 2 * subtop->alasts + 1;
re_sub_match_last_t **new_array = re_realloc (subtop->lasts,
re_sub_match_last_t *,
new_alasts);
if (BE (new_array == NULL, 0))
return NULL;
subtop->lasts = new_array;
subtop->alasts = new_alasts;
}
new_entry = calloc (1, sizeof (re_sub_match_last_t));
if (BE (new_entry != NULL, 1))
{
subtop->lasts[subtop->nlasts] = new_entry;
new_entry->node = node;
new_entry->str_idx = str_idx;
++subtop->nlasts;
}
return new_entry;
}
static void
internal_function
sift_ctx_init (re_sift_context_t *sctx, re_dfastate_t **sifted_sts,
re_dfastate_t **limited_sts, Idx last_node, Idx last_str_idx)
{
sctx->sifted_states = sifted_sts;
sctx->limited_states = limited_sts;
sctx->last_node = last_node;
sctx->last_str_idx = last_str_idx;
re_node_set_init_empty (&sctx->limits);
}
|
./openacc-vv/kernels_loop_reduction_bitand_loop.c | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(10 * sizeof(unsigned int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
for (int x = 0; x < 10 * n; ++x){
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX < false_margin){
for (int z = 0; z < y; ++z){
temp *= 2;
}
a[x] += temp;
temp = 1;
}
}
}
#pragma acc data copyin(a[0:10 * n]) copy(b[0:10 * n], c[0:10])
{
#pragma acc kernels loop gang private(temp)
for (int y = 0; y < 10; ++y){
temp = a[y * n];
#pragma acc loop worker reduction(&:temp)
for (int x = 1; x < n; ++x){
temp = temp & a[y * n + x];
}
c[y] = temp;
#pragma acc loop worker
for (int x = 0; x < n; ++x){
b[y * n + x] = b[y * n + x] + c[y];
}
}
}
unsigned int* host_c = (unsigned int *)malloc(10 * sizeof(unsigned int));
for (int x = 0; x < 10; ++x){
host_c[x] = a[x * n];
for (int y = 1; y < n; ++y){
host_c[x] = host_c[x] & a[x * n + y];
}
if (host_c[x] != c[x]){
err += 1;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (b[x * n + y] != b_copy[x * n + y] + c[x]){
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/serial_loop_reduction_max_vector_loop.F90 | #ifndef T1
!T1:serial,private,reduction,combined-constructs,loop,V:2.6-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
REAL(8),DIMENSION(LOOPCOUNT, 10):: a, b
REAL(8),DIMENSION(10):: maximums, host_maximums
REAL(8):: temp
INTEGER:: errors, x, y
errors = 0
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
host_maximums = 0
DO y = 1, 10
DO x = 1, LOOPCOUNT
host_maximums(y) = max(host_maximums(y), a(x, y) * b(x, y))
END DO
END DO
!$acc data copyin(a(1:LOOPCOUNT, 1:10), b(1:LOOPCOUNT, 1:10)) copy(maximums(1:10))
!$acc serial loop private(temp)
DO y = 1, 10
temp = 0
!$acc loop vector reduction(max:temp)
DO x = 1, LOOPCOUNT
temp = max(temp, a(x, y) * b(x, y))
END DO
maximums(y) = temp
END DO
!$acc end data
DO x = 1, 10
IF (abs(host_maximums(x) - maximums(x)) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/kernels_loop_seq.F90 | #ifndef T1
!T1:kernels,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
b = 0
!$acc data copyin(a(1:LOOPCOUNT)) copy(b(1:LOOPCOUNT))
!$acc kernels loop seq
DO x = 2, LOOPCOUNT
b(x) = b(x - 1) + a(x)
END DO
!$acc end data
DO x = 2, LOOPCOUNT
IF (abs(b(x) - (b(x - 1) + a(x))) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./SPECaccel/tools/src/perl-5.12.3/regcomp.c | /* regcomp.c
*/
/*
* 'A fair jaw-cracker dwarf-language must be.' --Samwise Gamgee
*
* [p.285 of _The Lord of the Rings_, II/iii: "The Ring Goes South"]
*/
/* This file contains functions for compiling a regular expression. See
* also regexec.c which funnily enough, contains functions for executing
* a regular expression.
*
* This file is also copied at build time to ext/re/re_comp.c, where
* it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
* This causes the main functions to be compiled under new names and with
* debugging support added, which makes "use re 'debug'" work.
*/
/* NOTE: this is derived from Henry Spencer's regexp code, and should not
* confused with the original package (see point 3 below). Thanks, Henry!
*/
/* Additional note: this code is very heavily munged from Henry's version
* in places. In some spots I've traded clarity for efficiency, so don't
* blame Henry for some of the lack of readability.
*/
/* The names of the functions have been changed from regcomp and
* regexec to pregcomp and pregexec in order to avoid conflicts
* with the POSIX routines of the same names.
*/
#ifdef PERL_EXT_RE_BUILD
#include "re_top.h"
#endif
/*
* pregcomp and pregexec -- regsub and regerror are not used in perl
*
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
*
**** Alterations to Henry's code are...
****
**** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
**** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
**** by Larry Wall and others
****
**** You may distribute under the terms of either the GNU General Public
**** License or the Artistic License, as specified in the README file.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes in
* regular-expression syntax might require a total rethink.
*/
#include "EXTERN.h"
#define PERL_IN_REGCOMP_C
#include "perl.h"
#ifndef PERL_IN_XSUB_RE
# include "INTERN.h"
#endif
#define REG_COMP_C
#ifdef PERL_IN_XSUB_RE
# include "re_comp.h"
#else
# include "regcomp.h"
#endif
#ifdef op
#undef op
#endif /* op */
#ifdef MSDOS
# if defined(BUGGY_MSC6)
/* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
# pragma optimize("a",off)
/* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
# pragma optimize("w",on )
# endif /* BUGGY_MSC6 */
#endif /* MSDOS */
#ifndef STATIC
#define STATIC static
#endif
typedef struct RExC_state_t {
U32 flags; /* are we folding, multilining? */
char *precomp; /* uncompiled string. */
REGEXP *rx_sv; /* The SV that is the regexp. */
regexp *rx; /* perl core regexp structure */
regexp_internal *rxi; /* internal data for regexp object pprivate field */
char *start; /* Start of input for compile */
char *end; /* End of input for compile */
char *parse; /* Input-scan pointer. */
I32 whilem_seen; /* number of WHILEM in this expr */
regnode *emit_start; /* Start of emitted-code area */
regnode *emit_bound; /* First regnode outside of the allocated space */
regnode *emit; /* Code-emit pointer; ®dummy = don't = compiling */
I32 naughty; /* How bad is this pattern? */
I32 sawback; /* Did we see \1, ...? */
U32 seen;
I32 size; /* Code size. */
I32 npar; /* Capture buffer count, (OPEN). */
I32 cpar; /* Capture buffer count, (CLOSE). */
I32 nestroot; /* root parens we are in - used by accept */
I32 extralen;
I32 seen_zerolen;
I32 seen_evals;
regnode **open_parens; /* pointers to open parens */
regnode **close_parens; /* pointers to close parens */
regnode *opend; /* END node in program */
I32 utf8; /* whether the pattern is utf8 or not */
I32 orig_utf8; /* whether the pattern was originally in utf8 */
/* XXX use this for future optimisation of case
* where pattern must be upgraded to utf8. */
HV *paren_names; /* Paren names */
regnode **recurse; /* Recurse regops */
I32 recurse_count; /* Number of recurse regops */
#if ADD_TO_REGEXEC
char *starttry; /* -Dr: where regtry was called. */
#define RExC_starttry (pRExC_state->starttry)
#endif
#ifdef DEBUGGING
const char *lastparse;
I32 lastnum;
AV *paren_name_list; /* idx -> name */
#define RExC_lastparse (pRExC_state->lastparse)
#define RExC_lastnum (pRExC_state->lastnum)
#define RExC_paren_name_list (pRExC_state->paren_name_list)
#endif
} RExC_state_t;
#define RExC_flags (pRExC_state->flags)
#define RExC_precomp (pRExC_state->precomp)
#define RExC_rx_sv (pRExC_state->rx_sv)
#define RExC_rx (pRExC_state->rx)
#define RExC_rxi (pRExC_state->rxi)
#define RExC_start (pRExC_state->start)
#define RExC_end (pRExC_state->end)
#define RExC_parse (pRExC_state->parse)
#define RExC_whilem_seen (pRExC_state->whilem_seen)
#ifdef RE_TRACK_PATTERN_OFFSETS
#define RExC_offsets (pRExC_state->rxi->u.offsets) /* I am not like the others */
#endif
#define RExC_emit (pRExC_state->emit)
#define RExC_emit_start (pRExC_state->emit_start)
#define RExC_emit_bound (pRExC_state->emit_bound)
#define RExC_naughty (pRExC_state->naughty)
#define RExC_sawback (pRExC_state->sawback)
#define RExC_seen (pRExC_state->seen)
#define RExC_size (pRExC_state->size)
#define RExC_npar (pRExC_state->npar)
#define RExC_nestroot (pRExC_state->nestroot)
#define RExC_extralen (pRExC_state->extralen)
#define RExC_seen_zerolen (pRExC_state->seen_zerolen)
#define RExC_seen_evals (pRExC_state->seen_evals)
#define RExC_utf8 (pRExC_state->utf8)
#define RExC_orig_utf8 (pRExC_state->orig_utf8)
#define RExC_open_parens (pRExC_state->open_parens)
#define RExC_close_parens (pRExC_state->close_parens)
#define RExC_opend (pRExC_state->opend)
#define RExC_paren_names (pRExC_state->paren_names)
#define RExC_recurse (pRExC_state->recurse)
#define RExC_recurse_count (pRExC_state->recurse_count)
#define ISMULT1(c) ((c) == '*' || (c) == '+' || (c) == '?')
#define ISMULT2(s) ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
((*s) == '{' && regcurly(s)))
#ifdef SPSTART
#undef SPSTART /* dratted cpp namespace... */
#endif
/*
* Flags to be passed up and down.
*/
#define WORST 0 /* Worst case. */
#define HASWIDTH 0x01 /* Known to match non-null strings. */
#define SIMPLE 0x02 /* Simple enough to be STAR/PLUS operand. */
#define SPSTART 0x04 /* Starts with * or +. */
#define TRYAGAIN 0x08 /* Weeded out a declaration. */
#define POSTPONED 0x10 /* (?1),(?&name), (??{...}) or similar */
#define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
/* whether trie related optimizations are enabled */
#if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
#define TRIE_STUDY_OPT
#define FULL_TRIE_STUDY
#define TRIE_STCLASS
#endif
#define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
#define PBITVAL(paren) (1 << ((paren) & 7))
#define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
#define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
#define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
/* About scan_data_t.
During optimisation we recurse through the regexp program performing
various inplace (keyhole style) optimisations. In addition study_chunk
and scan_commit populate this data structure with information about
what strings MUST appear in the pattern. We look for the longest
string that must appear for at a fixed location, and we look for the
longest string that may appear at a floating location. So for instance
in the pattern:
/FOO[xX]A.*B[xX]BAR/
Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
strings (because they follow a .* construct). study_chunk will identify
both FOO and BAR as being the longest fixed and floating strings respectively.
The strings can be composites, for instance
/(f)(o)(o)/
will result in a composite fixed substring 'foo'.
For each string some basic information is maintained:
- offset or min_offset
This is the position the string must appear at, or not before.
It also implicitly (when combined with minlenp) tells us how many
character must match before the string we are searching.
Likewise when combined with minlenp and the length of the string
tells us how many characters must appear after the string we have
found.
- max_offset
Only used for floating strings. This is the rightmost point that
the string can appear at. Ifset to I32 max it indicates that the
string can occur infinitely far to the right.
- minlenp
A pointer to the minimum length of the pattern that the string
was found inside. This is important as in the case of positive
lookahead or positive lookbehind we can have multiple patterns
involved. Consider
/(?=FOO).*F/
The minimum length of the pattern overall is 3, the minimum length
of the lookahead part is 3, but the minimum length of the part that
will actually match is 1. So 'FOO's minimum length is 3, but the
minimum length for the F is 1. This is important as the minimum length
is used to determine offsets in front of and behind the string being
looked for. Since strings can be composites this is the length of the
pattern at the time it was commited with a scan_commit. Note that
the length is calculated by study_chunk, so that the minimum lengths
are not known until the full pattern has been compiled, thus the
pointer to the value.
- lookbehind
In the case of lookbehind the string being searched for can be
offset past the start point of the final matching string.
If this value was just blithely removed from the min_offset it would
invalidate some of the calculations for how many chars must match
before or after (as they are derived from min_offset and minlen and
the length of the string being searched for).
When the final pattern is compiled and the data is moved from the
scan_data_t structure into the regexp structure the information
about lookbehind is factored in, with the information that would
have been lost precalculated in the end_shift field for the
associated string.
The fields pos_min and pos_delta are used to store the minimum offset
and the delta to the maximum offset at the current point in the pattern.
*/
typedef struct scan_data_t {
/*I32 len_min; unused */
/*I32 len_delta; unused */
I32 pos_min;
I32 pos_delta;
SV *last_found;
I32 last_end; /* min value, <0 unless valid. */
I32 last_start_min;
I32 last_start_max;
SV **longest; /* Either &l_fixed, or &l_float. */
SV *longest_fixed; /* longest fixed string found in pattern */
I32 offset_fixed; /* offset where it starts */
I32 *minlen_fixed; /* pointer to the minlen relevent to the string */
I32 lookbehind_fixed; /* is the position of the string modfied by LB */
SV *longest_float; /* longest floating string found in pattern */
I32 offset_float_min; /* earliest point in string it can appear */
I32 offset_float_max; /* latest point in string it can appear */
I32 *minlen_float; /* pointer to the minlen relevent to the string */
I32 lookbehind_float; /* is the position of the string modified by LB */
I32 flags;
I32 whilem_c;
I32 *last_closep;
struct regnode_charclass_class *start_class;
} scan_data_t;
/*
* Forward declarations for pregcomp()'s friends.
*/
static const scan_data_t zero_scan_data =
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
#define SF_BEFORE_EOL (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
#define SF_BEFORE_SEOL 0x0001
#define SF_BEFORE_MEOL 0x0002
#define SF_FIX_BEFORE_EOL (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
#define SF_FL_BEFORE_EOL (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
#ifdef NO_UNARY_PLUS
# define SF_FIX_SHIFT_EOL (0+2)
# define SF_FL_SHIFT_EOL (0+4)
#else
# define SF_FIX_SHIFT_EOL (+2)
# define SF_FL_SHIFT_EOL (+4)
#endif
#define SF_FIX_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
#define SF_FIX_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
#define SF_FL_BEFORE_SEOL (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
#define SF_FL_BEFORE_MEOL (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
#define SF_IS_INF 0x0040
#define SF_HAS_PAR 0x0080
#define SF_IN_PAR 0x0100
#define SF_HAS_EVAL 0x0200
#define SCF_DO_SUBSTR 0x0400
#define SCF_DO_STCLASS_AND 0x0800
#define SCF_DO_STCLASS_OR 0x1000
#define SCF_DO_STCLASS (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
#define SCF_WHILEM_VISITED_POS 0x2000
#define SCF_TRIE_RESTUDY 0x4000 /* Do restudy? */
#define SCF_SEEN_ACCEPT 0x8000
#define UTF (RExC_utf8 != 0)
#define LOC ((RExC_flags & RXf_PMf_LOCALE) != 0)
#define FOLD ((RExC_flags & RXf_PMf_FOLD) != 0)
#define OOB_UNICODE 12345678
#define OOB_NAMEDCLASS -1
#define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
#define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
/* length of regex to show in messages that don't mark a position within */
#define RegexLengthToShowInErrorMessages 127
/*
* If MARKER[12] are adjusted, be sure to adjust the constants at the top
* of t/op/regmesg.t, the tests in t/op/re_tests, and those in
* op/pragma/warn/regcomp.
*/
#define MARKER1 "<-- HERE" /* marker as it appears in the description */
#define MARKER2 " <-- HERE " /* marker as it appears within the regex */
#define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
/*
* Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
* arg. Show regex, up to a maximum length. If it's too long, chop and add
* "...".
*/
#define _FAIL(code) STMT_START { \
const char *ellipses = ""; \
IV len = RExC_end - RExC_precomp; \
\
if (!SIZE_ONLY) \
SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
if (len > RegexLengthToShowInErrorMessages) { \
/* chop 10 shorter than the max, to ensure meaning of "..." */ \
len = RegexLengthToShowInErrorMessages - 10; \
ellipses = "..."; \
} \
code; \
} STMT_END
#define FAIL(msg) _FAIL( \
Perl_croak(aTHX_ "%s in regex m/%.*s%s/", \
msg, (int)len, RExC_precomp, ellipses))
#define FAIL2(msg,arg) _FAIL( \
Perl_croak(aTHX_ msg " in regex m/%.*s%s/", \
arg, (int)len, RExC_precomp, ellipses))
/*
* Simple_vFAIL -- like FAIL, but marks the current location in the scan
*/
#define Simple_vFAIL(m) STMT_START { \
const IV offset = RExC_parse - RExC_precomp; \
Perl_croak(aTHX_ "%s" REPORT_LOCATION, \
m, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
*/
#define vFAIL(m) STMT_START { \
if (!SIZE_ONLY) \
SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
Simple_vFAIL(m); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts two arguments.
*/
#define Simple_vFAIL2(m,a1) STMT_START { \
const IV offset = RExC_parse - RExC_precomp; \
S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, \
(int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
*/
#define vFAIL2(m,a1) STMT_START { \
if (!SIZE_ONLY) \
SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
Simple_vFAIL2(m, a1); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts three arguments.
*/
#define Simple_vFAIL3(m, a1, a2) STMT_START { \
const IV offset = RExC_parse - RExC_precomp; \
S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, \
(int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
/*
* Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
*/
#define vFAIL3(m,a1,a2) STMT_START { \
if (!SIZE_ONLY) \
SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv); \
Simple_vFAIL3(m, a1, a2); \
} STMT_END
/*
* Like Simple_vFAIL(), but accepts four arguments.
*/
#define Simple_vFAIL4(m, a1, a2, a3) STMT_START { \
const IV offset = RExC_parse - RExC_precomp; \
S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, \
(int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define ckWARNreg(loc,m) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
(int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define ckWARNregdep(loc,m) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP), \
m REPORT_LOCATION, \
(int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define ckWARN2reg(loc, m, a1) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define vWARN3(loc, m, a1, a2) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define ckWARN3reg(loc, m, a1, a2) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define vWARN4(loc, m, a1, a2, a3) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define ckWARN4reg(loc, m, a1, a2, a3) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
#define vWARN5(loc, m, a1, a2, a3, a4) STMT_START { \
const IV offset = loc - RExC_precomp; \
Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION, \
a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
} STMT_END
/* Allow for side effects in s */
#define REGC(c,s) STMT_START { \
if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
} STMT_END
/* Macros for recording node offsets. 20001227 mjd@plover.com
* Nodes are numbered 1, 2, 3, 4. Node #n's position is recorded in
* element 2*n-1 of the array. Element #2n holds the byte length node #n.
* Element 0 holds the number n.
* Position is 1 indexed.
*/
#ifndef RE_TRACK_PATTERN_OFFSETS
#define Set_Node_Offset_To_R(node,byte)
#define Set_Node_Offset(node,byte)
#define Set_Cur_Node_Offset
#define Set_Node_Length_To_R(node,len)
#define Set_Node_Length(node,len)
#define Set_Node_Cur_Length(node)
#define Node_Offset(n)
#define Node_Length(n)
#define Set_Node_Offset_Length(node,offset,len)
#define ProgLen(ri) ri->u.proglen
#define SetProgLen(ri,x) ri->u.proglen = x
#else
#define ProgLen(ri) ri->u.offsets[0]
#define SetProgLen(ri,x) ri->u.offsets[0] = x
#define Set_Node_Offset_To_R(node,byte) STMT_START { \
if (! SIZE_ONLY) { \
MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n", \
__LINE__, (int)(node), (int)(byte))); \
if((node) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
} else { \
RExC_offsets[2*(node)-1] = (byte); \
} \
} \
} STMT_END
#define Set_Node_Offset(node,byte) \
Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
#define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
#define Set_Node_Length_To_R(node,len) STMT_START { \
if (! SIZE_ONLY) { \
MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n", \
__LINE__, (int)(node), (int)(len))); \
if((node) < 0) { \
Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
} else { \
RExC_offsets[2*(node)] = (len); \
} \
} \
} STMT_END
#define Set_Node_Length(node,len) \
Set_Node_Length_To_R((node)-RExC_emit_start, len)
#define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
#define Set_Node_Cur_Length(node) \
Set_Node_Length(node, RExC_parse - parse_start)
/* Get offsets and lengths */
#define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
#define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
#define Set_Node_Offset_Length(node,offset,len) STMT_START { \
Set_Node_Offset_To_R((node)-RExC_emit_start, (offset)); \
Set_Node_Length_To_R((node)-RExC_emit_start, (len)); \
} STMT_END
#endif
#if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
#define EXPERIMENTAL_INPLACESCAN
#endif /*RE_TRACK_PATTERN_OFFSETS*/
#define DEBUG_STUDYDATA(str,data,depth) \
DEBUG_OPTIMISE_MORE_r(if(data){ \
PerlIO_printf(Perl_debug_log, \
"%*s" str "Pos:%"IVdf"/%"IVdf \
" Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s", \
(int)(depth)*2, "", \
(IV)((data)->pos_min), \
(IV)((data)->pos_delta), \
(UV)((data)->flags), \
(IV)((data)->whilem_c), \
(IV)((data)->last_closep ? *((data)->last_closep) : -1), \
is_inf ? "INF " : "" \
); \
if ((data)->last_found) \
PerlIO_printf(Perl_debug_log, \
"Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
" %sFloat: '%s' @ %"IVdf"/%"IVdf"", \
SvPVX_const((data)->last_found), \
(IV)((data)->last_end), \
(IV)((data)->last_start_min), \
(IV)((data)->last_start_max), \
((data)->longest && \
(data)->longest==&((data)->longest_fixed)) ? "*" : "", \
SvPVX_const((data)->longest_fixed), \
(IV)((data)->offset_fixed), \
((data)->longest && \
(data)->longest==&((data)->longest_float)) ? "*" : "", \
SvPVX_const((data)->longest_float), \
(IV)((data)->offset_float_min), \
(IV)((data)->offset_float_max) \
); \
PerlIO_printf(Perl_debug_log,"\n"); \
});
static void clear_re(pTHX_ void *r);
/* Mark that we cannot extend a found fixed substring at this point.
Update the longest found anchored substring and the longest found
floating substrings if needed. */
STATIC void
S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
{
const STRLEN l = CHR_SVLEN(data->last_found);
const STRLEN old_l = CHR_SVLEN(*data->longest);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_SCAN_COMMIT;
if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
SvSetMagicSV(*data->longest, data->last_found);
if (*data->longest == data->longest_fixed) {
data->offset_fixed = l ? data->last_start_min : data->pos_min;
if (data->flags & SF_BEFORE_EOL)
data->flags
|= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
else
data->flags &= ~SF_FIX_BEFORE_EOL;
data->minlen_fixed=minlenp;
data->lookbehind_fixed=0;
}
else { /* *data->longest == data->longest_float */
data->offset_float_min = l ? data->last_start_min : data->pos_min;
data->offset_float_max = (l
? data->last_start_max
: data->pos_min + data->pos_delta);
if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
data->offset_float_max = I32_MAX;
if (data->flags & SF_BEFORE_EOL)
data->flags
|= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
else
data->flags &= ~SF_FL_BEFORE_EOL;
data->minlen_float=minlenp;
data->lookbehind_float=0;
}
}
SvCUR_set(data->last_found, 0);
{
SV * const sv = data->last_found;
if (SvUTF8(sv) && SvMAGICAL(sv)) {
MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
if (mg)
mg->mg_len = 0;
}
}
data->last_end = -1;
data->flags &= ~SF_BEFORE_EOL;
DEBUG_STUDYDATA("commit: ",data,0);
}
/* Can match anything (initialization) */
STATIC void
S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
{
PERL_ARGS_ASSERT_CL_ANYTHING;
ANYOF_CLASS_ZERO(cl);
ANYOF_BITMAP_SETALL(cl);
cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
if (LOC)
cl->flags |= ANYOF_LOCALE;
}
/* Can match anything (initialization) */
STATIC int
S_cl_is_anything(const struct regnode_charclass_class *cl)
{
int value;
PERL_ARGS_ASSERT_CL_IS_ANYTHING;
for (value = 0; value <= ANYOF_MAX; value += 2)
if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
return 1;
if (!(cl->flags & ANYOF_UNICODE_ALL))
return 0;
if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
return 0;
return 1;
}
/* Can match anything (initialization) */
STATIC void
S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
{
PERL_ARGS_ASSERT_CL_INIT;
Zero(cl, 1, struct regnode_charclass_class);
cl->type = ANYOF;
cl_anything(pRExC_state, cl);
}
STATIC void
S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
{
PERL_ARGS_ASSERT_CL_INIT_ZERO;
Zero(cl, 1, struct regnode_charclass_class);
cl->type = ANYOF;
cl_anything(pRExC_state, cl);
if (LOC)
cl->flags |= ANYOF_LOCALE;
}
/* 'And' a given class with another one. Can create false positives */
/* We assume that cl is not inverted */
STATIC void
S_cl_and(struct regnode_charclass_class *cl,
const struct regnode_charclass_class *and_with)
{
PERL_ARGS_ASSERT_CL_AND;
assert(and_with->type == ANYOF);
if (!(and_with->flags & ANYOF_CLASS)
&& !(cl->flags & ANYOF_CLASS)
&& (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
&& !(and_with->flags & ANYOF_FOLD)
&& !(cl->flags & ANYOF_FOLD)) {
int i;
if (and_with->flags & ANYOF_INVERT)
for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
cl->bitmap[i] &= ~and_with->bitmap[i];
else
for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
cl->bitmap[i] &= and_with->bitmap[i];
} /* XXXX: logic is complicated otherwise, leave it along for a moment. */
if (!(and_with->flags & ANYOF_EOS))
cl->flags &= ~ANYOF_EOS;
if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
!(and_with->flags & ANYOF_INVERT)) {
cl->flags &= ~ANYOF_UNICODE_ALL;
cl->flags |= ANYOF_UNICODE;
ARG_SET(cl, ARG(and_with));
}
if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
!(and_with->flags & ANYOF_INVERT))
cl->flags &= ~ANYOF_UNICODE_ALL;
if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
!(and_with->flags & ANYOF_INVERT))
cl->flags &= ~ANYOF_UNICODE;
}
/* 'OR' a given class with another one. Can create false positives */
/* We assume that cl is not inverted */
STATIC void
S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
{
PERL_ARGS_ASSERT_CL_OR;
if (or_with->flags & ANYOF_INVERT) {
/* We do not use
* (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
* <= (B1 | !B2) | (CL1 | !CL2)
* which is wasteful if CL2 is small, but we ignore CL2:
* (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
* XXXX Can we handle case-fold? Unclear:
* (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
* (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
*/
if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
&& !(or_with->flags & ANYOF_FOLD)
&& !(cl->flags & ANYOF_FOLD) ) {
int i;
for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
cl->bitmap[i] |= ~or_with->bitmap[i];
} /* XXXX: logic is complicated otherwise */
else {
cl_anything(pRExC_state, cl);
}
} else {
/* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
&& (!(or_with->flags & ANYOF_FOLD)
|| (cl->flags & ANYOF_FOLD)) ) {
int i;
/* OR char bitmap and class bitmap separately */
for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
cl->bitmap[i] |= or_with->bitmap[i];
if (or_with->flags & ANYOF_CLASS) {
for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
cl->classflags[i] |= or_with->classflags[i];
cl->flags |= ANYOF_CLASS;
}
}
else { /* XXXX: logic is complicated, leave it along for a moment. */
cl_anything(pRExC_state, cl);
}
}
if (or_with->flags & ANYOF_EOS)
cl->flags |= ANYOF_EOS;
if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
ARG(cl) != ARG(or_with)) {
cl->flags |= ANYOF_UNICODE_ALL;
cl->flags &= ~ANYOF_UNICODE;
}
if (or_with->flags & ANYOF_UNICODE_ALL) {
cl->flags |= ANYOF_UNICODE_ALL;
cl->flags &= ~ANYOF_UNICODE;
}
}
#define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
#define TRIE_LIST_CUR(state) ( TRIE_LIST_ITEM( state, 0 ).forid )
#define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
#define TRIE_LIST_USED(idx) ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
#ifdef DEBUGGING
/*
dump_trie(trie,widecharmap,revcharmap)
dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
These routines dump out a trie in a somewhat readable format.
The _interim_ variants are used for debugging the interim
tables that are used to generate the final compressed
representation which is what dump_trie expects.
Part of the reason for their existance is to provide a form
of documentation as to how the different representations function.
*/
/*
Dumps the final compressed table form of the trie to Perl_debug_log.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
AV *revcharmap, U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE;
PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
(int)depth * 2 + 2,"",
"Match","Base","Ofs" );
for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
SV ** const tmp = av_fetch( revcharmap, state, 0);
if ( tmp ) {
PerlIO_printf( Perl_debug_log, "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
(int)depth * 2 + 2,"");
for( state = 0 ; state < trie->uniquecharcount ; state++ )
PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
PerlIO_printf( Perl_debug_log, "\n");
for( state = 1 ; state < trie->statecount ; state++ ) {
const U32 base = trie->states[ state ].trans.base;
PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
if ( trie->states[ state ].wordnum ) {
PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
} else {
PerlIO_printf( Perl_debug_log, "%6s", "" );
}
PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
if ( base ) {
U32 ofs = 0;
while( ( base + ofs < trie->uniquecharcount ) ||
( base + ofs - trie->uniquecharcount < trie->lasttrans
&& trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
ofs++;
PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount ) &&
( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
{
PerlIO_printf( Perl_debug_log, "%*"UVXf,
colwidth,
(UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
} else {
PerlIO_printf( Perl_debug_log, "%*s",colwidth," ." );
}
}
PerlIO_printf( Perl_debug_log, "]");
}
PerlIO_printf( Perl_debug_log, "\n" );
}
}
/*
Dumps a fully constructed but uncompressed trie in list form.
List tries normally only are used for construction when the number of
possible chars (trie->uniquecharcount) is very high.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
/* print out the table precompression. */
PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
(int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
"------:-----+-----------------\n" );
for( state=1 ; state < next_alloc ; state ++ ) {
U16 charid;
PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
(int)depth * 2 + 2,"", (UV)state );
if ( ! trie->states[ state ].wordnum ) {
PerlIO_printf( Perl_debug_log, "%5s| ","");
} else {
PerlIO_printf( Perl_debug_log, "W%4x| ",
trie->states[ state ].wordnum
);
}
for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
if ( tmp ) {
PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
) ,
TRIE_LIST_ITEM(state,charid).forid,
(UV)TRIE_LIST_ITEM(state,charid).newstate
);
if (!(charid % 10))
PerlIO_printf(Perl_debug_log, "\n%*s| ",
(int)((depth * 2) + 14), "");
}
}
PerlIO_printf( Perl_debug_log, "\n");
}
}
/*
Dumps a fully constructed but uncompressed trie in table form.
This is the normal DFA style state transition table, with a few
twists to facilitate compression later.
Used for debugging make_trie().
*/
STATIC void
S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
HV *widecharmap, AV *revcharmap, U32 next_alloc,
U32 depth)
{
U32 state;
U16 charid;
SV *sv=sv_newmortal();
int colwidth= widecharmap ? 6 : 4;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
/*
print out the table precompression so that we can do a visual check
that they are identical.
*/
PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
SV ** const tmp = av_fetch( revcharmap, charid, 0);
if ( tmp ) {
PerlIO_printf( Perl_debug_log, "%*s",
colwidth,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
}
}
PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
}
PerlIO_printf( Perl_debug_log, "\n" );
for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ",
(int)depth * 2 + 2,"",
(UV)TRIE_NODENUM( state ) );
for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
if (v)
PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
else
PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
}
if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
} else {
PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
trie->states[ TRIE_NODENUM( state ) ].wordnum );
}
}
}
#endif
/* make_trie(startbranch,first,last,tail,word_count,flags,depth)
startbranch: the first branch in the whole branch sequence
first : start branch of sequence of branch-exact nodes.
May be the same as startbranch
last : Thing following the last branch.
May be the same as tail.
tail : item following the branch sequence
count : words in the sequence
flags : currently the OP() type we will be building one of /EXACT(|F|Fl)/
depth : indent depth
Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
A trie is an N'ary tree where the branches are determined by digital
decomposition of the key. IE, at the root node you look up the 1st character and
follow that branch repeat until you find the end of the branches. Nodes can be
marked as "accepting" meaning they represent a complete word. Eg:
/he|she|his|hers/
would convert into the following structure. Numbers represent states, letters
following numbers represent valid transitions on the letter from that state, if
the number is in square brackets it represents an accepting state, otherwise it
will be in parenthesis.
+-h->+-e->[3]-+-r->(8)-+-s->[9]
| |
| (2)
| |
(1) +-i->(6)-+-s->[7]
|
+-s->(3)-+-h->(4)-+-e->[5]
Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
This shows that when matching against the string 'hers' we will begin at state 1
read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
is also accepting. Thus we know that we can match both 'he' and 'hers' with a
single traverse. We store a mapping from accepting to state to which word was
matched, and then when we have multiple possibilities we try to complete the
rest of the regex in the order in which they occured in the alternation.
The only prior NFA like behaviour that would be changed by the TRIE support is
the silent ignoring of duplicate alternations which are of the form:
/ (DUPE|DUPE) X? (?{ ... }) Y /x
Thus EVAL blocks follwing a trie may be called a different number of times with
and without the optimisation. With the optimisations dupes will be silently
ignored. This inconsistant behaviour of EVAL type nodes is well established as
the following demonstrates:
'words'=~/(word|word|word)(?{ print $1 })[xyz]/
which prints out 'word' three times, but
'words'=~/(word|word|word)(?{ print $1 })S/
which doesnt print it out at all. This is due to other optimisations kicking in.
Example of what happens on a structural level:
The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1: CURLYM[1] {1,32767}(18)
5: BRANCH(8)
6: EXACT <ac>(16)
8: BRANCH(11)
9: EXACT <ad>(16)
11: BRANCH(14)
12: EXACT <ab>(16)
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
This would be optimizable with startbranch=5, first=5, last=16, tail=16
and should turn into:
1: CURLYM[1] {1,32767}(18)
5: TRIE(16)
[Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
<ac>
<ad>
<ab>
16: SUCCEED(0)
17: NOTHING(18)
18: END(0)
Cases where tail != last would be like /(?foo|bar)baz/:
1: BRANCH(4)
2: EXACT <foo>(8)
4: BRANCH(7)
5: EXACT <bar>(8)
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
which would be optimizable with startbranch=1, first=1, last=7, tail=8
and would end up looking like:
1: TRIE(8)
[Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
<foo>
<bar>
7: TAIL(8)
8: EXACT <baz>(10)
10: END(0)
d = uvuni_to_utf8_flags(d, uv, 0);
is the recommended Unicode-aware way of saying
*(d++) = uv;
*/
#define TRIE_STORE_REVCHAR \
STMT_START { \
if (UTF) { \
SV *zlopp = newSV(2); \
unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp); \
unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
SvCUR_set(zlopp, kapow - flrbbbbb); \
SvPOK_on(zlopp); \
SvUTF8_on(zlopp); \
av_push(revcharmap, zlopp); \
} else { \
char ooooff = (char)uvc; \
av_push(revcharmap, newSVpvn(&ooooff, 1)); \
} \
} STMT_END
#define TRIE_READ_CHAR STMT_START { \
wordlen++; \
if ( UTF ) { \
if ( folder ) { \
if ( foldlen > 0 ) { \
uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags ); \
foldlen -= len; \
scan += len; \
len = 0; \
} else { \
uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
foldlen -= UNISKIP( uvc ); \
scan = foldbuf + UNISKIP( uvc ); \
} \
} else { \
uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
} \
} else { \
uvc = (U32)*uc; \
len = 1; \
} \
} STMT_END
#define TRIE_LIST_PUSH(state,fid,ns) STMT_START { \
if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) { \
U32 ging = TRIE_LIST_LEN( state ) *= 2; \
Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
} \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid; \
TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns; \
TRIE_LIST_CUR( state )++; \
} STMT_END
#define TRIE_LIST_NEW(state) STMT_START { \
Newxz( trie->states[ state ].trans.list, \
4, reg_trie_trans_le ); \
TRIE_LIST_CUR( state ) = 1; \
TRIE_LIST_LEN( state ) = 4; \
} STMT_END
#define TRIE_HANDLE_WORD(state) STMT_START { \
U16 dupe= trie->states[ state ].wordnum; \
regnode * const noper_next = regnext( noper ); \
\
if (trie->wordlen) \
trie->wordlen[ curword ] = wordlen; \
DEBUG_r({ \
/* store the word for dumping */ \
SV* tmp; \
if (OP(noper) != NOTHING) \
tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF); \
else \
tmp = newSVpvn_utf8( "", 0, UTF ); \
av_push( trie_words, tmp ); \
}); \
\
curword++; \
\
if ( noper_next < tail ) { \
if (!trie->jump) \
trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
trie->jump[curword] = (U16)(noper_next - convert); \
if (!jumper) \
jumper = noper_next; \
if (!nextbranch) \
nextbranch= regnext(cur); \
} \
\
if ( dupe ) { \
/* So it's a dupe. This means we need to maintain a */\
/* linked-list from the first to the next. */\
/* we only allocate the nextword buffer when there */\
/* a dupe, so first time we have to do the allocation */\
if (!trie->nextword) \
trie->nextword = (U16 *) \
PerlMemShared_calloc( word_count + 1, sizeof(U16)); \
while ( trie->nextword[dupe] ) \
dupe= trie->nextword[dupe]; \
trie->nextword[dupe]= curword; \
} else { \
/* we haven't inserted this word yet. */ \
trie->states[ state ].wordnum = curword; \
} \
} STMT_END
#define TRIE_TRANS_STATE(state,base,ucharcount,charid,special) \
( ( base + charid >= ucharcount \
&& base + charid < ubound \
&& state == trie->trans[ base - ucharcount + charid ].check \
&& trie->trans[ base - ucharcount + charid ].next ) \
? trie->trans[ base - ucharcount + charid ].next \
: ( state==1 ? special : 0 ) \
)
#define MADE_TRIE 1
#define MADE_JUMP_TRIE 2
#define MADE_EXACT_TRIE 4
STATIC I32
S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
{
dVAR;
/* first pass, loop through and scan words */
reg_trie_data *trie;
HV *widecharmap = NULL;
AV *revcharmap = newAV();
regnode *cur;
const U32 uniflags = UTF8_ALLOW_DEFAULT;
STRLEN len = 0;
UV uvc = 0;
U16 curword = 0;
U32 next_alloc = 0;
regnode *jumper = NULL;
regnode *nextbranch = NULL;
regnode *convert = NULL;
/* we just use folder as a flag in utf8 */
const U8 * const folder = ( flags == EXACTF
? PL_fold
: ( flags == EXACTFL
? PL_fold_locale
: NULL
)
);
#ifdef DEBUGGING
const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
AV *trie_words = NULL;
/* along with revcharmap, this only used during construction but both are
* useful during debugging so we store them in the struct when debugging.
*/
#else
const U32 data_slot = add_data( pRExC_state, 2, "tu" );
STRLEN trie_charcount=0;
#endif
SV *re_trie_maxbuff;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_MAKE_TRIE;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
trie->refcount = 1;
trie->startstate = 1;
trie->wordcount = word_count;
RExC_rxi->data->data[ data_slot ] = (void*)trie;
trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
if (!(UTF && folder))
trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
DEBUG_r({
trie_words = newAV();
});
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
if (!SvIOK(re_trie_maxbuff)) {
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
DEBUG_OPTIMISE_r({
PerlIO_printf( Perl_debug_log,
"%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
(int)depth * 2 + 2, "",
REG_NODE_NUM(startbranch),REG_NODE_NUM(first),
REG_NODE_NUM(last), REG_NODE_NUM(tail),
(int)depth);
});
/* Find the node we are going to overwrite */
if ( first == startbranch && OP( last ) != BRANCH ) {
/* whole branch chain */
convert = first;
} else {
/* branch sub-chain */
convert = NEXTOPER( first );
}
/* -- First loop and Setup --
We first traverse the branches and scan each word to determine if it
contains widechars, and how many unique chars there are, this is
important as we have to build a table with at least as many columns as we
have unique chars.
We use an array of integers to represent the character codes 0..255
(trie->charmap) and we use a an HV* to store Unicode characters. We use the
native representation of the character value as the key and IV's for the
coded index.
*TODO* If we keep track of how many times each character is used we can
remap the columns so that the table compression later on is more
efficient in terms of memory by ensuring most common value is in the
middle and the least common are on the outside. IMO this would be better
than a most to least common mapping as theres a decent chance the most
common letter will share a node with the least common, meaning the node
will not be compressable. With a middle is most common approach the worst
case is when we have the least common nodes twice.
*/
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
const U8 *uc = (U8*)STRING( noper );
const U8 * const e = uc + STR_LEN( noper );
STRLEN foldlen = 0;
U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
const U8 *scan = (U8*)NULL;
U32 wordlen = 0; /* required init */
STRLEN chars = 0;
bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
if (OP(noper) == NOTHING) {
trie->minlen= 0;
continue;
}
if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
regardless of encoding */
for ( ; uc < e ; uc += len ) {
TRIE_CHARCOUNT(trie)++;
TRIE_READ_CHAR;
chars++;
if ( uvc < 256 ) {
if ( !trie->charmap[ uvc ] ) {
trie->charmap[ uvc ]=( ++trie->uniquecharcount );
if ( folder )
trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
TRIE_STORE_REVCHAR;
}
if ( set_bit ) {
/* store the codepoint in the bitmap, and if its ascii
also store its folded equivelent. */
TRIE_BITMAP_SET(trie,uvc);
/* store the folded codepoint */
if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
if ( !UTF ) {
/* store first byte of utf8 representation of
codepoints in the 127 < uvc < 256 range */
if (127 < uvc && uvc < 192) {
TRIE_BITMAP_SET(trie,194);
} else if (191 < uvc ) {
TRIE_BITMAP_SET(trie,195);
/* && uvc < 256 -- we know uvc is < 256 already */
}
}
set_bit = 0; /* We've done our bit :-) */
}
} else {
SV** svpp;
if ( !widecharmap )
widecharmap = newHV();
svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
if ( !svpp )
Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
if ( !SvTRUE( *svpp ) ) {
sv_setiv( *svpp, ++trie->uniquecharcount );
TRIE_STORE_REVCHAR;
}
}
}
if( cur == first ) {
trie->minlen=chars;
trie->maxlen=chars;
} else if (chars < trie->minlen) {
trie->minlen=chars;
} else if (chars > trie->maxlen) {
trie->maxlen=chars;
}
} /* end first pass */
DEBUG_TRIE_COMPILE_r(
PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
(int)depth * 2 + 2,"",
( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
(int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
(int)trie->minlen, (int)trie->maxlen )
);
trie->wordlen = (U32 *) PerlMemShared_calloc( word_count, sizeof(U32) );
/*
We now know what we are dealing with in terms of unique chars and
string sizes so we can calculate how much memory a naive
representation using a flat table will take. If it's over a reasonable
limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
conservative but potentially much slower representation using an array
of lists.
At the end we convert both representations into the same compressed
form that will be used in regexec.c for matching with. The latter
is a form that cannot be used to construct with but has memory
properties similar to the list form and access properties similar
to the table form making it both suitable for fast searches and
small enough that its feasable to store for the duration of a program.
See the comment in the code where the compressed table is produced
inplace from the flat tabe representation for an explanation of how
the compression works.
*/
if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
/*
Second Pass -- Array Of Lists Representation
Each state will be represented by a list of charid:state records
(reg_trie_trans_le) the first such element holds the CUR and LEN
points of the allocated array. (See defines above).
We build the initial structure using the lists, and then convert
it into the compressed table form which allows faster lookups
(but cant be modified once converted).
*/
STRLEN transcount = 1;
DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
"%*sCompiling trie using list compiler\n",
(int)depth * 2 + 2, ""));
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
TRIE_LIST_NEW(1);
next_alloc = 2;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
U8 *uc = (U8*)STRING( noper );
const U8 * const e = uc + STR_LEN( noper );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U8 *scan = (U8*)NULL; /* sanity init */
STRLEN foldlen = 0; /* required init */
U32 wordlen = 0; /* required init */
U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
if (OP(noper) != NOTHING) {
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
if ( !svpp ) {
charid = 0;
} else {
charid=(U16)SvIV( *svpp );
}
}
/* charid is now 0 if we dont know the char read, or nonzero if we do */
if ( charid ) {
U16 check;
U32 newstate = 0;
charid--;
if ( !trie->states[ state ].trans.list ) {
TRIE_LIST_NEW( state );
}
for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
newstate = TRIE_LIST_ITEM( state, check ).newstate;
break;
}
}
if ( ! newstate ) {
newstate = next_alloc++;
TRIE_LIST_PUSH( state, charid, newstate );
transcount++;
}
state = newstate;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
}
}
}
TRIE_HANDLE_WORD(state);
} /* end second pass */
/* next alloc is the NEXT state to be allocated */
trie->statecount = next_alloc;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states,
next_alloc
* sizeof(reg_trie_state) );
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
revcharmap, next_alloc,
depth+1)
);
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
{
U32 state;
U32 tp = 0;
U32 zp = 0;
for( state=1 ; state < next_alloc ; state ++ ) {
U32 base=0;
/*
DEBUG_TRIE_COMPILE_MORE_r(
PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
);
*/
if (trie->states[state].trans.list) {
U16 minid=TRIE_LIST_ITEM( state, 1).forid;
U16 maxid=minid;
U16 idx;
for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
if ( forid < minid ) {
minid=forid;
} else if ( forid > maxid ) {
maxid=forid;
}
}
if ( transcount < tp + maxid - minid + 1) {
transcount *= 2;
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans,
transcount
* sizeof(reg_trie_trans) );
Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
}
base = trie->uniquecharcount + tp - minid;
if ( maxid == minid ) {
U32 set = 0;
for ( ; zp < tp ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
base = trie->uniquecharcount + zp - minid;
trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
trie->trans[ zp ].check = state;
set = 1;
break;
}
}
if ( !set ) {
trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
trie->trans[ tp ].check = state;
tp++;
zp = tp;
}
} else {
for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
const U32 tid = base - trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
trie->trans[ tid ].check = state;
}
tp += ( maxid - minid + 1 );
}
Safefree(trie->states[ state ].trans.list);
}
/*
DEBUG_TRIE_COMPILE_MORE_r(
PerlIO_printf( Perl_debug_log, " base: %d\n",base);
);
*/
trie->states[ state ].trans.base=base;
}
trie->lasttrans = tp + 1;
}
} else {
/*
Second Pass -- Flat Table Representation.
we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
We know that we will need Charcount+1 trans at most to store the data
(one row per char at worst case) So we preallocate both structures
assuming worst case.
We then construct the trie using only the .next slots of the entry
structs.
We use the .check field of the first entry of the node temporarily to
make compression both faster and easier by keeping track of how many non
zero fields are in the node.
Since trans are numbered from 1 any 0 pointer in the table is a FAIL
transition.
There are two terms at use here: state as a TRIE_NODEIDX() which is a
number representing the first entry of the node, and state as a
TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
are 2 entrys per node. eg:
A B A B
1. 2 4 1. 3 7
2. 0 3 3. 0 5
3. 0 0 5. 0 0
4. 0 0 7. 0 0
The table is internally in the right hand, idx form. However as we also
have to deal with the states array which is indexed by nodenum we have to
use TRIE_NODENUM() to convert.
*/
DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log,
"%*sCompiling trie using table compiler\n",
(int)depth * 2 + 2, ""));
trie->trans = (reg_trie_trans *)
PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
* trie->uniquecharcount + 1,
sizeof(reg_trie_trans) );
trie->states = (reg_trie_state *)
PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
sizeof(reg_trie_state) );
next_alloc = trie->uniquecharcount + 1;
for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
const U8 *uc = (U8*)STRING( noper );
const U8 * const e = uc + STR_LEN( noper );
U32 state = 1; /* required init */
U16 charid = 0; /* sanity init */
U32 accept_state = 0; /* sanity init */
U8 *scan = (U8*)NULL; /* sanity init */
STRLEN foldlen = 0; /* required init */
U32 wordlen = 0; /* required init */
U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
if ( OP(noper) != NOTHING ) {
for ( ; uc < e ; uc += len ) {
TRIE_READ_CHAR;
if ( uvc < 256 ) {
charid = trie->charmap[ uvc ];
} else {
SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
charid = svpp ? (U16)SvIV(*svpp) : 0;
}
if ( charid ) {
charid--;
if ( !trie->trans[ state + charid ].next ) {
trie->trans[ state + charid ].next = next_alloc;
trie->trans[ state ].check++;
next_alloc += trie->uniquecharcount;
}
state = trie->trans[ state + charid ].next;
} else {
Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
}
/* charid is now 0 if we dont know the char read, or nonzero if we do */
}
}
accept_state = TRIE_NODENUM( state );
TRIE_HANDLE_WORD(accept_state);
} /* end second pass */
/* and now dump it out before we compress it */
DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
revcharmap,
next_alloc, depth+1));
{
/*
* Inplace compress the table.*
For sparse data sets the table constructed by the trie algorithm will
be mostly 0/FAIL transitions or to put it another way mostly empty.
(Note that leaf nodes will not contain any transitions.)
This algorithm compresses the tables by eliminating most such
transitions, at the cost of a modest bit of extra work during lookup:
- Each states[] entry contains a .base field which indicates the
index in the state[] array wheres its transition data is stored.
- If .base is 0 there are no valid transitions from that node.
- If .base is nonzero then charid is added to it to find an entry in
the trans array.
-If trans[states[state].base+charid].check!=state then the
transition is taken to be a 0/Fail transition. Thus if there are fail
transitions at the front of the node then the .base offset will point
somewhere inside the previous nodes data (or maybe even into a node
even earlier), but the .check field determines if the transition is
valid.
XXX - wrong maybe?
The following process inplace converts the table to the compressed
table: We first do not compress the root node 1,and mark its all its
.check pointers as 1 and set its .base pointer as 1 as well. This
allows to do a DFA construction from the compressed table later, and
ensures that any .base pointers we calculate later are greater than
0.
- We set 'pos' to indicate the first entry of the second node.
- We then iterate over the columns of the node, finding the first and
last used entry at l and m. We then copy l..m into pos..(pos+m-l),
and set the .check pointers accordingly, and advance pos
appropriately and repreat for the next node. Note that when we copy
the next pointers we have to convert them from the original
NODEIDX form to NODENUM form as the former is not valid post
compression.
- If a node has no transitions used we mark its base as 0 and do not
advance the pos pointer.
- If a node only has one transition we use a second pointer into the
structure to fill in allocated fail transitions from other states.
This pointer is independent of the main pointer and scans forward
looking for null transitions that are allocated to a state. When it
finds one it writes the single transition into the "hole". If the
pointer doesnt find one the single transition is appended as normal.
- Once compressed we can Renew/realloc the structures to release the
excess space.
See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
specifically Fig 3.47 and the associated pseudocode.
demq
*/
const U32 laststate = TRIE_NODENUM( next_alloc );
U32 state, charid;
U32 pos = 0, zp=0;
trie->statecount = laststate;
for ( state = 1 ; state < laststate ; state++ ) {
U8 flag = 0;
const U32 stateidx = TRIE_NODEIDX( state );
const U32 o_used = trie->trans[ stateidx ].check;
U32 used = trie->trans[ stateidx ].check;
trie->trans[ stateidx ].check = 0;
for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
if ( flag || trie->trans[ stateidx + charid ].next ) {
if ( trie->trans[ stateidx + charid ].next ) {
if (o_used == 1) {
for ( ; zp < pos ; zp++ ) {
if ( ! trie->trans[ zp ].next ) {
break;
}
}
trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
trie->trans[ zp ].check = state;
if ( ++zp > pos ) pos = zp;
break;
}
used--;
}
if ( !flag ) {
flag = 1;
trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
}
trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
trie->trans[ pos ].check = state;
pos++;
}
}
}
trie->lasttrans = pos + 1;
trie->states = (reg_trie_state *)
PerlMemShared_realloc( trie->states, laststate
* sizeof(reg_trie_state) );
DEBUG_TRIE_COMPILE_MORE_r(
PerlIO_printf( Perl_debug_log,
"%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
(int)depth * 2 + 2,"",
(int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
(IV)next_alloc,
(IV)pos,
( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
);
} /* end table compress */
}
DEBUG_TRIE_COMPILE_MORE_r(
PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
(int)depth * 2 + 2, "",
(UV)trie->statecount,
(UV)trie->lasttrans)
);
/* resize the trans array to remove unused space */
trie->trans = (reg_trie_trans *)
PerlMemShared_realloc( trie->trans, trie->lasttrans
* sizeof(reg_trie_trans) );
/* and now dump out the compressed format */
DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
{ /* Modify the program and insert the new TRIE node*/
U8 nodetype =(U8)(flags & 0xFF);
char *str=NULL;
#ifdef DEBUGGING
regnode *optimize = NULL;
#ifdef RE_TRACK_PATTERN_OFFSETS
U32 mjd_offset = 0;
U32 mjd_nodelen = 0;
#endif /* RE_TRACK_PATTERN_OFFSETS */
#endif /* DEBUGGING */
/*
This means we convert either the first branch or the first Exact,
depending on whether the thing following (in 'last') is a branch
or not and whther first is the startbranch (ie is it a sub part of
the alternation or is it the whole thing.)
Assuming its a sub part we conver the EXACT otherwise we convert
the whole branch sequence, including the first.
*/
/* Find the node we are going to overwrite */
if ( first != startbranch || OP( last ) == BRANCH ) {
/* branch sub-chain */
NEXT_OFF( first ) = (U16)(last - first);
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_r({
mjd_offset= Node_Offset((convert));
mjd_nodelen= Node_Length((convert));
});
#endif
/* whole branch chain */
}
#ifdef RE_TRACK_PATTERN_OFFSETS
else {
DEBUG_r({
const regnode *nop = NEXTOPER( convert );
mjd_offset= Node_Offset((nop));
mjd_nodelen= Node_Length((nop));
});
}
DEBUG_OPTIMISE_r(
PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
(int)depth * 2 + 2, "",
(UV)mjd_offset, (UV)mjd_nodelen)
);
#endif
/* But first we check to see if there is a common prefix we can
split out as an EXACT and put in front of the TRIE node. */
trie->startstate= 1;
if ( trie->bitmap && !widecharmap && !trie->jump ) {
U32 state;
for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
U32 ofs = 0;
I32 idx = -1;
U32 count = 0;
const U32 base = trie->states[ state ].trans.base;
if ( trie->states[state].wordnum )
count = 1;
for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
if ( ( base + ofs >= trie->uniquecharcount ) &&
( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
{
if ( ++count > 1 ) {
SV **tmp = av_fetch( revcharmap, ofs, 0);
const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
if ( state == 1 ) break;
if ( count == 2 ) {
Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
DEBUG_OPTIMISE_r(
PerlIO_printf(Perl_debug_log,
"%*sNew Start State=%"UVuf" Class: [",
(int)depth * 2 + 2, "",
(UV)state));
if (idx >= 0) {
SV ** const tmp = av_fetch( revcharmap, idx, 0);
const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
TRIE_BITMAP_SET(trie,*ch);
if ( folder )
TRIE_BITMAP_SET(trie, folder[ *ch ]);
DEBUG_OPTIMISE_r(
PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
);
}
}
TRIE_BITMAP_SET(trie,*ch);
if ( folder )
TRIE_BITMAP_SET(trie,folder[ *ch ]);
DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
}
idx = ofs;
}
}
if ( count == 1 ) {
SV **tmp = av_fetch( revcharmap, idx, 0);
STRLEN len;
char *ch = SvPV( *tmp, len );
DEBUG_OPTIMISE_r({
SV *sv=sv_newmortal();
PerlIO_printf( Perl_debug_log,
"%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
(int)depth * 2 + 2, "",
(UV)state, (UV)idx,
pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6,
PL_colors[0], PL_colors[1],
(SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_ESCAPE_FIRSTCHAR
)
);
});
if ( state==1 ) {
OP( convert ) = nodetype;
str=STRING(convert);
STR_LEN(convert)=0;
}
STR_LEN(convert) += len;
while (len--)
*str++ = *ch++;
} else {
#ifdef DEBUGGING
if (state>1)
DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
#endif
break;
}
}
if (str) {
regnode *n = convert+NODE_SZ_STR(convert);
NEXT_OFF(convert) = NODE_SZ_STR(convert);
trie->startstate = state;
trie->minlen -= (state - 1);
trie->maxlen -= (state - 1);
#ifdef DEBUGGING
/* At least the UNICOS C compiler choked on this
* being argument to DEBUG_r(), so let's just have
* it right here. */
if (
#ifdef PERL_EXT_RE_BUILD
1
#else
DEBUG_r_TEST
#endif
) {
regnode *fix = convert;
U32 word = trie->wordcount;
mjd_nodelen++;
Set_Node_Offset_Length(convert, mjd_offset, state - 1);
while( ++fix < n ) {
Set_Node_Offset_Length(fix, 0, 0);
}
while (word--) {
SV ** const tmp = av_fetch( trie_words, word, 0 );
if (tmp) {
if ( STR_LEN(convert) <= SvCUR(*tmp) )
sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
else
sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
}
}
}
#endif
if (trie->maxlen) {
convert = n;
} else {
NEXT_OFF(convert) = (U16)(tail - convert);
DEBUG_r(optimize= n);
}
}
}
if (!jumper)
jumper = last;
if ( trie->maxlen ) {
NEXT_OFF( convert ) = (U16)(tail - convert);
ARG_SET( convert, data_slot );
/* Store the offset to the first unabsorbed branch in
jump[0], which is otherwise unused by the jump logic.
We use this when dumping a trie and during optimisation. */
if (trie->jump)
trie->jump[0] = (U16)(nextbranch - convert);
/* XXXX */
if ( !trie->states[trie->startstate].wordnum && trie->bitmap &&
( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
{
OP( convert ) = TRIEC;
Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
PerlMemShared_free(trie->bitmap);
trie->bitmap= NULL;
} else
OP( convert ) = TRIE;
/* store the type in the flags */
convert->flags = nodetype;
DEBUG_r({
optimize = convert
+ NODE_STEP_REGNODE
+ regarglen[ OP( convert ) ];
});
/* XXX We really should free up the resource in trie now,
as we won't use them - (which resources?) dmq */
}
/* needed for dumping*/
DEBUG_r(if (optimize) {
regnode *opt = convert;
while ( ++opt < optimize) {
Set_Node_Offset_Length(opt,0,0);
}
/*
Try to clean up some of the debris left after the
optimisation.
*/
while( optimize < jumper ) {
mjd_nodelen += Node_Length((optimize));
OP( optimize ) = OPTIMIZED;
Set_Node_Offset_Length(optimize,0,0);
optimize++;
}
Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
});
} /* end node insert */
RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
#ifdef DEBUGGING
RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
#else
SvREFCNT_dec(revcharmap);
#endif
return trie->jump
? MADE_JUMP_TRIE
: trie->startstate>1
? MADE_EXACT_TRIE
: MADE_TRIE;
}
STATIC void
S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source, regnode *stclass, U32 depth)
{
/* The Trie is constructed and compressed now so we can build a fail array now if its needed
This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
"Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
ISBN 0-201-10088-6
We find the fail state for each state in the trie, this state is the longest proper
suffix of the current states 'word' that is also a proper prefix of another word in our
trie. State 1 represents the word '' and is the thus the default fail state. This allows
the DFA not to have to restart after its tried and failed a word at a given point, it
simply continues as though it had been matching the other word in the first place.
Consider
'abcdgu'=~/abcdefg|cdgu/
When we get to 'd' we are still matching the first word, we would encounter 'g' which would
fail, which would bring use to the state representing 'd' in the second word where we would
try 'g' and succeed, prodceding to match 'cdgu'.
*/
/* add a fail transition */
const U32 trie_offset = ARG(source);
reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
U32 *q;
const U32 ucharcount = trie->uniquecharcount;
const U32 numstates = trie->statecount;
const U32 ubound = trie->lasttrans + ucharcount;
U32 q_read = 0;
U32 q_write = 0;
U32 charid;
U32 base = trie->states[ 1 ].trans.base;
U32 *fail;
reg_ac_data *aho;
const U32 data_slot = add_data( pRExC_state, 1, "T" );
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
ARG_SET( stclass, data_slot );
aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
RExC_rxi->data->data[ data_slot ] = (void*)aho;
aho->trie=trie_offset;
aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
Copy( trie->states, aho->states, numstates, reg_trie_state );
Newxz( q, numstates, U32);
aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
aho->refcount = 1;
fail = aho->fail;
/* initialize fail[0..1] to be 1 so that we always have
a valid final fail state */
fail[ 0 ] = fail[ 1 ] = 1;
for ( charid = 0; charid < ucharcount ; charid++ ) {
const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
if ( newstate ) {
q[ q_write ] = newstate;
/* set to point at the root */
fail[ q[ q_write++ ] ]=1;
}
}
while ( q_read < q_write) {
const U32 cur = q[ q_read++ % numstates ];
base = trie->states[ cur ].trans.base;
for ( charid = 0 ; charid < ucharcount ; charid++ ) {
const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
if (ch_state) {
U32 fail_state = cur;
U32 fail_base;
do {
fail_state = fail[ fail_state ];
fail_base = aho->states[ fail_state ].trans.base;
} while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
fail[ ch_state ] = fail_state;
if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
{
aho->states[ ch_state ].wordnum = aho->states[ fail_state ].wordnum;
}
q[ q_write++ % numstates] = ch_state;
}
}
}
/* restore fail[0..1] to 0 so that we "fall out" of the AC loop
when we fail in state 1, this allows us to use the
charclass scan to find a valid start char. This is based on the principle
that theres a good chance the string being searched contains lots of stuff
that cant be a start char.
*/
fail[ 0 ] = fail[ 1 ] = 0;
DEBUG_TRIE_COMPILE_r({
PerlIO_printf(Perl_debug_log,
"%*sStclass Failtable (%"UVuf" states): 0",
(int)(depth * 2), "", (UV)numstates
);
for( q_read=1; q_read<numstates; q_read++ ) {
PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
}
PerlIO_printf(Perl_debug_log, "\n");
});
Safefree(q);
/*RExC_seen |= REG_SEEN_TRIEDFA;*/
}
/*
* There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
* These need to be revisited when a newer toolchain becomes available.
*/
#if defined(__sparc64__) && defined(__GNUC__)
# if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
# undef SPARC64_GCC_WORKAROUND
# define SPARC64_GCC_WORKAROUND 1
# endif
#endif
#define DEBUG_PEEP(str,scan,depth) \
DEBUG_OPTIMISE_r({if (scan){ \
SV * const mysv=sv_newmortal(); \
regnode *Next = regnext(scan); \
regprop(RExC_rx, mysv, scan); \
PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
(int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
Next ? (REG_NODE_NUM(Next)) : 0 ); \
}});
#define JOIN_EXACT(scan,min,flags) \
if (PL_regkind[OP(scan)] == EXACT) \
join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
STATIC U32
S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
/* Merge several consecutive EXACTish nodes into one. */
regnode *n = regnext(scan);
U32 stringok = 1;
regnode *next = scan + NODE_SZ_STR(scan);
U32 merged = 0;
U32 stopnow = 0;
#ifdef DEBUGGING
regnode *stop = scan;
GET_RE_DEBUG_FLAGS_DECL;
#else
PERL_UNUSED_ARG(depth);
#endif
PERL_ARGS_ASSERT_JOIN_EXACT;
#ifndef EXPERIMENTAL_INPLACESCAN
PERL_UNUSED_ARG(flags);
PERL_UNUSED_ARG(val);
#endif
DEBUG_PEEP("join",scan,depth);
/* Skip NOTHING, merge EXACT*. */
while (n &&
( PL_regkind[OP(n)] == NOTHING ||
(stringok && (OP(n) == OP(scan))))
&& NEXT_OFF(n)
&& NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
if (OP(n) == TAIL || n > next)
stringok = 0;
if (PL_regkind[OP(n)] == NOTHING) {
DEBUG_PEEP("skip:",n,depth);
NEXT_OFF(scan) += NEXT_OFF(n);
next = n + NODE_STEP_REGNODE;
#ifdef DEBUGGING
if (stringok)
stop = n;
#endif
n = regnext(n);
}
else if (stringok) {
const unsigned int oldl = STR_LEN(scan);
regnode * const nnext = regnext(n);
DEBUG_PEEP("merg",n,depth);
merged++;
if (oldl + STR_LEN(n) > U8_MAX)
break;
NEXT_OFF(scan) += NEXT_OFF(n);
STR_LEN(scan) += STR_LEN(n);
next = n + NODE_SZ_STR(n);
/* Now we can overwrite *n : */
Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
#ifdef DEBUGGING
stop = next - 1;
#endif
n = nnext;
if (stopnow) break;
}
#ifdef EXPERIMENTAL_INPLACESCAN
if (flags && !NEXT_OFF(n)) {
DEBUG_PEEP("atch", val, depth);
if (reg_off_by_arg[OP(n)]) {
ARG_SET(n, val - n);
}
else {
NEXT_OFF(n) = val - n;
}
stopnow = 1;
}
#endif
}
if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
/*
Two problematic code points in Unicode casefolding of EXACT nodes:
U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
which casefold to
Unicode UTF-8
U+03B9 U+0308 U+0301 0xCE 0xB9 0xCC 0x88 0xCC 0x81
U+03C5 U+0308 U+0301 0xCF 0x85 0xCC 0x88 0xCC 0x81
This means that in case-insensitive matching (or "loose matching",
as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
length of the above casefolded versions) can match a target string
of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
This would rather mess up the minimum length computation.
What we'll do is to look for the tail four bytes, and then peek
at the preceding two bytes to see whether we need to decrease
the minimum length by four (six minus two).
Thanks to the design of UTF-8, there cannot be false matches:
A sequence of valid UTF-8 bytes cannot be a subsequence of
another valid sequence of UTF-8 bytes.
*/
char * const s0 = STRING(scan), *s, *t;
char * const s1 = s0 + STR_LEN(scan) - 1;
char * const s2 = s1 - 4;
#ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
const char t0[] = "\xaf\x49\xaf\x42";
#else
const char t0[] = "\xcc\x88\xcc\x81";
#endif
const char * const t1 = t0 + 3;
for (s = s0 + 2;
s < s2 && (t = ninstr(s, s1, t0, t1));
s = t + 4) {
#ifdef EBCDIC
if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
#else
if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
#endif
*min -= 4;
}
}
#ifdef DEBUGGING
/* Allow dumping */
n = scan + NODE_SZ_STR(scan);
while (n <= stop) {
if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
OP(n) = OPTIMIZED;
NEXT_OFF(n) = 0;
}
n++;
}
#endif
DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
return stopnow;
}
/* REx optimizer. Converts nodes into quickier variants "in place".
Finds fixed substrings. */
/* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
to the position after last scanned or to NULL. */
#define INIT_AND_WITHP \
assert(!and_withp); \
Newx(and_withp,1,struct regnode_charclass_class); \
SAVEFREEPV(and_withp)
/* this is a chain of data about sub patterns we are processing that
need to be handled seperately/specially in study_chunk. Its so
we can simulate recursion without losing state. */
struct scan_frame;
typedef struct scan_frame {
regnode *last; /* last node to process in this frame */
regnode *next; /* next node to process when last is reached */
struct scan_frame *prev; /*previous frame*/
I32 stop; /* what stopparen do we use */
} scan_frame;
#define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
#define CASE_SYNST_FNC(nAmE) \
case nAmE: \
if (flags & SCF_DO_STCLASS_AND) { \
for (value = 0; value < 256; value++) \
if (!is_ ## nAmE ## _cp(value)) \
ANYOF_BITMAP_CLEAR(data->start_class, value); \
} \
else { \
for (value = 0; value < 256; value++) \
if (is_ ## nAmE ## _cp(value)) \
ANYOF_BITMAP_SET(data->start_class, value); \
} \
break; \
case N ## nAmE: \
if (flags & SCF_DO_STCLASS_AND) { \
for (value = 0; value < 256; value++) \
if (is_ ## nAmE ## _cp(value)) \
ANYOF_BITMAP_CLEAR(data->start_class, value); \
} \
else { \
for (value = 0; value < 256; value++) \
if (!is_ ## nAmE ## _cp(value)) \
ANYOF_BITMAP_SET(data->start_class, value); \
} \
break
STATIC I32
S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
I32 *minlenp, I32 *deltap,
regnode *last,
scan_data_t *data,
I32 stopparen,
U8* recursed,
struct regnode_charclass_class *and_withp,
U32 flags, U32 depth)
/* scanp: Start here (read-write). */
/* deltap: Write maxlen-minlen here. */
/* last: Stop before this one. */
/* data: string data about the pattern */
/* stopparen: treat close N as END */
/* recursed: which subroutines have we recursed into */
/* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
{
dVAR;
I32 min = 0, pars = 0, code;
regnode *scan = *scanp, *next;
I32 delta = 0;
int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
int is_inf_internal = 0; /* The studied chunk is infinite */
I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
scan_data_t data_fake;
SV *re_trie_maxbuff = NULL;
regnode *first_non_open = scan;
I32 stopmin = I32_MAX;
scan_frame *frame = NULL;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_STUDY_CHUNK;
#ifdef DEBUGGING
StructCopy(&zero_scan_data, &data_fake, scan_data_t);
#endif
if ( depth == 0 ) {
while (first_non_open && OP(first_non_open) == OPEN)
first_non_open=regnext(first_non_open);
}
fake_study_recurse:
while ( scan && OP(scan) != END && scan < last ){
/* Peephole optimizer: */
DEBUG_STUDYDATA("Peep:", data,depth);
DEBUG_PEEP("Peep",scan,depth);
JOIN_EXACT(scan,&min,0);
/* Follow the next-chain of the current node and optimize
away all the NOTHINGs from it. */
if (OP(scan) != CURLYX) {
const int max = (reg_off_by_arg[OP(scan)]
? I32_MAX
/* I32 may be smaller than U16 on CRAYs! */
: (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
int noff;
regnode *n = scan;
/* Skip NOTHING and LONGJMP. */
while ((n = regnext(n))
&& ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
|| ((OP(n) == LONGJMP) && (noff = ARG(n))))
&& off + noff < max)
off += noff;
if (reg_off_by_arg[OP(scan)])
ARG(scan) = off;
else
NEXT_OFF(scan) = off;
}
/* The principal pseudo-switch. Cannot be a switch, since we
look into several different things. */
if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
|| OP(scan) == IFTHEN) {
next = regnext(scan);
code = OP(scan);
/* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
if (OP(next) == code || code == IFTHEN) {
/* NOTE - There is similar code to this block below for handling
TRIE nodes on a re-study. If you change stuff here check there
too. */
I32 max1 = 0, min1 = I32_MAX, num = 0;
struct regnode_charclass_class accum;
regnode * const startbranch=scan;
if (flags & SCF_DO_SUBSTR)
SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
if (flags & SCF_DO_STCLASS)
cl_init_zero(pRExC_state, &accum);
while (OP(scan) == code) {
I32 deltanext, minnext, f = 0, fake;
struct regnode_charclass_class this_class;
num++;
data_fake.flags = 0;
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
next = regnext(scan);
scan = NEXTOPER(scan);
if (code != BRANCH)
scan = NEXTOPER(scan);
if (flags & SCF_DO_STCLASS) {
cl_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
/* we suppose the run is continuous, last=next...*/
minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
next, &data_fake,
stopparen, recursed, NULL, f,depth+1);
if (min1 > minnext)
min1 = minnext;
if (max1 < minnext + deltanext)
max1 = minnext + deltanext;
if (deltanext == I32_MAX)
is_inf = is_inf_internal = 1;
scan = next;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > minnext)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
cl_or(pRExC_state, &accum, &this_class);
}
if (code == IFTHEN && num < 2) /* Empty ELSE branch */
min1 = 0;
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->longest = &(data->longest_float);
}
min += min1;
delta += max1 - min1;
if (flags & SCF_DO_STCLASS_OR) {
cl_or(pRExC_state, data->start_class, &accum);
if (min1) {
cl_and(data->start_class, and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
cl_and(data->start_class, &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp,
struct regnode_charclass_class);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class,
struct regnode_charclass_class);
flags |= SCF_DO_STCLASS_OR;
data->start_class->flags |= ANYOF_EOS;
}
}
if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
/* demq.
Assuming this was/is a branch we are dealing with: 'scan' now
points at the item that follows the branch sequence, whatever
it is. We now start at the beginning of the sequence and look
for subsequences of
BRANCH->EXACT=>x1
BRANCH->EXACT=>x2
tail
which would be constructed from a pattern like /A|LIST|OF|WORDS/
If we can find such a subseqence we need to turn the first
element into a trie and then add the subsequent branch exact
strings to the trie.
We have two cases
1. patterns where the whole set of branch can be converted.
2. patterns where only a subset can be converted.
In case 1 we can replace the whole set with a single regop
for the trie. In case 2 we need to keep the start and end
branchs so
'BRANCH EXACT; BRANCH EXACT; BRANCH X'
becomes BRANCH TRIE; BRANCH X;
There is an additional case, that being where there is a
common prefix, which gets split out into an EXACT like node
preceding the TRIE node.
If x(1..n)==tail then we can do a simple trie, if not we make
a "jump" trie, such that when we match the appropriate word
we "jump" to the appopriate tail node. Essentailly we turn
a nested if into a case structure of sorts.
*/
int made=0;
if (!re_trie_maxbuff) {
re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
if (!SvIOK(re_trie_maxbuff))
sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
}
if ( SvIV(re_trie_maxbuff)>=0 ) {
regnode *cur;
regnode *first = (regnode *)NULL;
regnode *last = (regnode *)NULL;
regnode *tail = scan;
U8 optype = 0;
U32 count=0;
#ifdef DEBUGGING
SV * const mysv = sv_newmortal(); /* for dumping */
#endif
/* var tail is used because there may be a TAIL
regop in the way. Ie, the exacts will point to the
thing following the TAIL, but the last branch will
point at the TAIL. So we advance tail. If we
have nested (?:) we may have to move through several
tails.
*/
while ( OP( tail ) == TAIL ) {
/* this is the TAIL generated by (?:) */
tail = regnext( tail );
}
DEBUG_OPTIMISE_r({
regprop(RExC_rx, mysv, tail );
PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
(int)depth * 2 + 2, "",
"Looking for TRIE'able sequences. Tail node is: ",
SvPV_nolen_const( mysv )
);
});
/*
step through the branches, cur represents each
branch, noper is the first thing to be matched
as part of that branch and noper_next is the
regnext() of that node. if noper is an EXACT
and noper_next is the same as scan (our current
position in the regex) then the EXACT branch is
a possible optimization target. Once we have
two or more consequetive such branches we can
create a trie of the EXACT's contents and stich
it in place. If the sequence represents all of
the branches we eliminate the whole thing and
replace it with a single TRIE. If it is a
subsequence then we need to stitch it in. This
means the first branch has to remain, and needs
to be repointed at the item on the branch chain
following the last branch optimized. This could
be either a BRANCH, in which case the
subsequence is internal, or it could be the
item following the branch sequence in which
case the subsequence is at the end.
*/
/* dont use tail as the end marker for this traverse */
for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
regnode * const noper = NEXTOPER( cur );
#if defined(DEBUGGING) || defined(NOJUMPTRIE)
regnode * const noper_next = regnext( noper );
#endif
DEBUG_OPTIMISE_r({
regprop(RExC_rx, mysv, cur);
PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
(int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
regprop(RExC_rx, mysv, noper);
PerlIO_printf( Perl_debug_log, " -> %s",
SvPV_nolen_const(mysv));
if ( noper_next ) {
regprop(RExC_rx, mysv, noper_next );
PerlIO_printf( Perl_debug_log,"\t=> %s\t",
SvPV_nolen_const(mysv));
}
PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
});
if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
: PL_regkind[ OP( noper ) ] == EXACT )
|| OP(noper) == NOTHING )
#ifdef NOJUMPTRIE
&& noper_next == tail
#endif
&& count < U16_MAX)
{
count++;
if ( !first || optype == NOTHING ) {
if (!first) first = cur;
optype = OP( noper );
} else {
last = cur;
}
} else {
/*
Currently we do not believe that the trie logic can
handle case insensitive matching properly when the
pattern is not unicode (thus forcing unicode semantics).
If/when this is fixed the following define can be swapped
in below to fully enable trie logic.
#define TRIE_TYPE_IS_SAFE 1
*/
#define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
if ( last && TRIE_TYPE_IS_SAFE ) {
make_trie( pRExC_state,
startbranch, first, cur, tail, count,
optype, depth+1 );
}
if ( PL_regkind[ OP( noper ) ] == EXACT
#ifdef NOJUMPTRIE
&& noper_next == tail
#endif
){
count = 1;
first = cur;
optype = OP( noper );
} else {
count = 0;
first = NULL;
optype = 0;
}
last = NULL;
}
}
DEBUG_OPTIMISE_r({
regprop(RExC_rx, mysv, cur);
PerlIO_printf( Perl_debug_log,
"%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
"", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
});
if ( last && TRIE_TYPE_IS_SAFE ) {
made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
#ifdef TRIE_STUDY_OPT
if ( ((made == MADE_EXACT_TRIE &&
startbranch == first)
|| ( first_non_open == first )) &&
depth==0 ) {
flags |= SCF_TRIE_RESTUDY;
if ( startbranch == first
&& scan == tail )
{
RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
}
}
#endif
}
}
} /* do trie */
}
else if ( code == BRANCHJ ) { /* single branch is optimized. */
scan = NEXTOPER(NEXTOPER(scan));
} else /* single branch is optimized. */
scan = NEXTOPER(scan);
continue;
} else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
scan_frame *newframe = NULL;
I32 paren;
regnode *start;
regnode *end;
if (OP(scan) != SUSPEND) {
/* set the pointer */
if (OP(scan) == GOSUB) {
paren = ARG(scan);
RExC_recurse[ARG2L(scan)] = scan;
start = RExC_open_parens[paren-1];
end = RExC_close_parens[paren-1];
} else {
paren = 0;
start = RExC_rxi->program + 1;
end = RExC_opend;
}
if (!recursed) {
Newxz(recursed, (((RExC_npar)>>3) +1), U8);
SAVEFREEPV(recursed);
}
if (!PAREN_TEST(recursed,paren+1)) {
PAREN_SET(recursed,paren+1);
Newx(newframe,1,scan_frame);
} else {
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp);
data->longest = &(data->longest_float);
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
cl_anything(pRExC_state, data->start_class);
flags &= ~SCF_DO_STCLASS;
}
} else {
Newx(newframe,1,scan_frame);
paren = stopparen;
start = scan+2;
end = regnext(scan);
}
if (newframe) {
assert(start);
assert(end);
SAVEFREEPV(newframe);
newframe->next = regnext(scan);
newframe->last = last;
newframe->stop = stopparen;
newframe->prev = frame;
frame = newframe;
scan = start;
stopparen = paren;
last = end;
continue;
}
}
else if (OP(scan) == EXACT) {
I32 l = STR_LEN(scan);
UV uc;
if (UTF) {
const U8 * const s = (U8*)STRING(scan);
l = utf8_length(s, s + l);
uc = utf8_to_uvchr(s, NULL);
} else {
uc = *((U8*)STRING(scan));
}
min += l;
if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
/* The code below prefers earlier match for fixed
offset, later match for variable offset. */
if (data->last_end == -1) { /* Update the start info. */
data->last_start_min = data->pos_min;
data->last_start_max = is_inf
? I32_MAX : data->pos_min + data->pos_delta;
}
sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
if (UTF)
SvUTF8_on(data->last_found);
{
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += utf8_length((U8*)STRING(scan),
(U8*)STRING(scan)+STR_LEN(scan));
}
data->last_end = data->pos_min + l;
data->pos_min += l; /* As in the first entry. */
data->flags &= ~SF_BEFORE_EOL;
}
if (flags & SCF_DO_STCLASS_AND) {
/* Check whether it is compatible with what we know already! */
int compat = 1;
if (uc >= 0x100 ||
(!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
&& !ANYOF_BITMAP_TEST(data->start_class, uc)
&& (!(data->start_class->flags & ANYOF_FOLD)
|| !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
)
compat = 0;
ANYOF_CLASS_ZERO(data->start_class);
ANYOF_BITMAP_ZERO(data->start_class);
if (compat)
ANYOF_BITMAP_SET(data->start_class, uc);
data->start_class->flags &= ~ANYOF_EOS;
if (uc < 0x100)
data->start_class->flags &= ~ANYOF_UNICODE_ALL;
}
else if (flags & SCF_DO_STCLASS_OR) {
/* false positive possible if the class is case-folded */
if (uc < 0x100)
ANYOF_BITMAP_SET(data->start_class, uc);
else
data->start_class->flags |= ANYOF_UNICODE_ALL;
data->start_class->flags &= ~ANYOF_EOS;
cl_and(data->start_class, and_withp);
}
flags &= ~SCF_DO_STCLASS;
}
else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
I32 l = STR_LEN(scan);
UV uc = *((U8*)STRING(scan));
/* Search for fixed substrings supports EXACT only. */
if (flags & SCF_DO_SUBSTR) {
assert(data);
SCAN_COMMIT(pRExC_state, data, minlenp);
}
if (UTF) {
const U8 * const s = (U8 *)STRING(scan);
l = utf8_length(s, s + l);
uc = utf8_to_uvchr(s, NULL);
}
min += l;
if (flags & SCF_DO_SUBSTR)
data->pos_min += l;
if (flags & SCF_DO_STCLASS_AND) {
/* Check whether it is compatible with what we know already! */
int compat = 1;
if (uc >= 0x100 ||
(!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
&& !ANYOF_BITMAP_TEST(data->start_class, uc)
&& !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
compat = 0;
ANYOF_CLASS_ZERO(data->start_class);
ANYOF_BITMAP_ZERO(data->start_class);
if (compat) {
ANYOF_BITMAP_SET(data->start_class, uc);
data->start_class->flags &= ~ANYOF_EOS;
data->start_class->flags |= ANYOF_FOLD;
if (OP(scan) == EXACTFL)
data->start_class->flags |= ANYOF_LOCALE;
}
}
else if (flags & SCF_DO_STCLASS_OR) {
if (data->start_class->flags & ANYOF_FOLD) {
/* false positive possible if the class is case-folded.
Assume that the locale settings are the same... */
if (uc < 0x100)
ANYOF_BITMAP_SET(data->start_class, uc);
data->start_class->flags &= ~ANYOF_EOS;
}
cl_and(data->start_class, and_withp);
}
flags &= ~SCF_DO_STCLASS;
}
else if (strchr((const char*)PL_varies,OP(scan))) {
I32 mincount, maxcount, minnext, deltanext, fl = 0;
I32 f = flags, pos_before = 0;
regnode * const oscan = scan;
struct regnode_charclass_class this_class;
struct regnode_charclass_class *oclass = NULL;
I32 next_is_eval = 0;
switch (PL_regkind[OP(scan)]) {
case WHILEM: /* End of (?:...)* . */
scan = NEXTOPER(scan);
goto finish;
case PLUS:
if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
next = NEXTOPER(scan);
if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
mincount = 1;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
}
if (flags & SCF_DO_SUBSTR)
data->pos_min++;
min++;
/* Fall through. */
case STAR:
if (flags & SCF_DO_STCLASS) {
mincount = 0;
maxcount = REG_INFTY;
next = regnext(scan);
scan = NEXTOPER(scan);
goto do_curly;
}
is_inf = is_inf_internal = 1;
scan = regnext(scan);
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
data->longest = &(data->longest_float);
}
goto optimize_curly_tail;
case CURLY:
if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
&& (scan->flags == stopparen))
{
mincount = 1;
maxcount = 1;
} else {
mincount = ARG1(scan);
maxcount = ARG2(scan);
}
next = regnext(scan);
if (OP(scan) == CURLYX) {
I32 lp = (data ? *(data->last_closep) : 0);
scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
}
scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
next_is_eval = (OP(scan) == EVAL);
do_curly:
if (flags & SCF_DO_SUBSTR) {
if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
pos_before = data->pos_min;
}
if (data) {
fl = data->flags;
data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
if (is_inf)
data->flags |= SF_IS_INF;
}
if (flags & SCF_DO_STCLASS) {
cl_init(pRExC_state, &this_class);
oclass = data->start_class;
data->start_class = &this_class;
f |= SCF_DO_STCLASS_AND;
f &= ~SCF_DO_STCLASS_OR;
}
/* These are the cases when once a subexpression
fails at a particular position, it cannot succeed
even after backtracking at the enclosing scope.
XXXX what if minimal match and we are at the
initial run of {n,m}? */
if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
f &= ~SCF_WHILEM_VISITED_POS;
/* This will finish on WHILEM, setting scan, or on NULL: */
minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
last, data, stopparen, recursed, NULL,
(mincount == 0
? (f & ~SCF_DO_SUBSTR) : f),depth+1);
if (flags & SCF_DO_STCLASS)
data->start_class = oclass;
if (mincount == 0 || minnext == 0) {
if (flags & SCF_DO_STCLASS_OR) {
cl_or(pRExC_state, data->start_class, &this_class);
}
else if (flags & SCF_DO_STCLASS_AND) {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp,
struct regnode_charclass_class);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&this_class, data->start_class,
struct regnode_charclass_class);
flags |= SCF_DO_STCLASS_OR;
data->start_class->flags |= ANYOF_EOS;
}
} else { /* Non-zero len */
if (flags & SCF_DO_STCLASS_OR) {
cl_or(pRExC_state, data->start_class, &this_class);
cl_and(data->start_class, and_withp);
}
else if (flags & SCF_DO_STCLASS_AND)
cl_and(data->start_class, &this_class);
flags &= ~SCF_DO_STCLASS;
}
if (!scan) /* It was not CURLYX, but CURLY. */
scan = next;
if ( /* ? quantifier ok, except for (?{ ... }) */
(next_is_eval || !(mincount == 0 && maxcount == 1))
&& (minnext == 0) && (deltanext == 0)
&& data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
&& maxcount <= REG_INFTY/3) /* Complement check for big count */
{
ckWARNreg(RExC_parse,
"Quantifier unexpected on zero-length expression");
}
min += minnext * mincount;
is_inf_internal |= ((maxcount == REG_INFTY
&& (minnext + deltanext) > 0)
|| deltanext == I32_MAX);
is_inf |= is_inf_internal;
delta += (minnext + deltanext) * maxcount - minnext * mincount;
/* Try powerful optimization CURLYX => CURLYN. */
if ( OP(oscan) == CURLYX && data
&& data->flags & SF_IN_PAR
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext && minnext == 1 ) {
/* Try to optimize to CURLYN. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
regnode * const nxt1 = nxt;
#ifdef DEBUGGING
regnode *nxt2;
#endif
/* Skip open. */
nxt = regnext(nxt);
if (!strchr((const char*)PL_simple,OP(nxt))
&& !(PL_regkind[OP(nxt)] == EXACT
&& STR_LEN(nxt) == 1))
goto nogo;
#ifdef DEBUGGING
nxt2 = nxt;
#endif
nxt = regnext(nxt);
if (OP(nxt) != CLOSE)
goto nogo;
if (RExC_open_parens) {
RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
}
/* Now we know that nxt2 is the only contents: */
oscan->flags = (U8)ARG(nxt);
OP(oscan) = CURLYN;
OP(nxt1) = NOTHING; /* was OPEN. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
#endif
}
nogo:
/* Try optimization CURLYX => CURLYM. */
if ( OP(oscan) == CURLYX && data
&& !(data->flags & SF_HAS_PAR)
&& !(data->flags & SF_HAS_EVAL)
&& !deltanext /* atom is fixed width */
&& minnext != 0 /* CURLYM can't handle zero width */
) {
/* XXXX How to optimize if data == 0? */
/* Optimize to a simpler form. */
regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
regnode *nxt2;
OP(oscan) = CURLYM;
while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
&& (OP(nxt2) != WHILEM))
nxt = nxt2;
OP(nxt2) = SUCCEED; /* Whas WHILEM */
/* Need to optimize away parenths. */
if (data->flags & SF_IN_PAR) {
/* Set the parenth number. */
regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
if (OP(nxt) != CLOSE)
FAIL("Panic opt close");
oscan->flags = (U8)ARG(nxt);
if (RExC_open_parens) {
RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
}
OP(nxt1) = OPTIMIZED; /* was OPEN. */
OP(nxt) = OPTIMIZED; /* was CLOSE. */
#ifdef DEBUGGING
OP(nxt1 + 1) = OPTIMIZED; /* was count. */
OP(nxt + 1) = OPTIMIZED; /* was count. */
NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
#endif
#if 0
while ( nxt1 && (OP(nxt1) != WHILEM)) {
regnode *nnxt = regnext(nxt1);
if (nnxt == nxt) {
if (reg_off_by_arg[OP(nxt1)])
ARG_SET(nxt1, nxt2 - nxt1);
else if (nxt2 - nxt1 < U16_MAX)
NEXT_OFF(nxt1) = nxt2 - nxt1;
else
OP(nxt) = NOTHING; /* Cannot beautify */
}
nxt1 = nnxt;
}
#endif
/* Optimize again: */
study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
NULL, stopparen, recursed, NULL, 0,depth+1);
}
else
oscan->flags = 0;
}
else if ((OP(oscan) == CURLYX)
&& (flags & SCF_WHILEM_VISITED_POS)
/* See the comment on a similar expression above.
However, this time it not a subexpression
we care about, but the expression itself. */
&& (maxcount == REG_INFTY)
&& data && ++data->whilem_c < 16) {
/* This stays as CURLYX, we can put the count/of pair. */
/* Find WHILEM (as in regexec.c) */
regnode *nxt = oscan + NEXT_OFF(oscan);
if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
nxt += ARG(nxt);
PREVOPER(nxt)->flags = (U8)(data->whilem_c
| (RExC_whilem_seen << 4)); /* On WHILEM */
}
if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (flags & SCF_DO_SUBSTR) {
SV *last_str = NULL;
int counted = mincount != 0;
if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
#if defined(SPARC64_GCC_WORKAROUND)
I32 b = 0;
STRLEN l = 0;
const char *s = NULL;
I32 old = 0;
if (pos_before >= data->last_start_min)
b = pos_before;
else
b = data->last_start_min;
l = 0;
s = SvPV_const(data->last_found, l);
old = b - data->last_start_min;
#else
I32 b = pos_before >= data->last_start_min
? pos_before : data->last_start_min;
STRLEN l;
const char * const s = SvPV_const(data->last_found, l);
I32 old = b - data->last_start_min;
#endif
if (UTF)
old = utf8_hop((U8*)s, old) - (U8*)s;
l -= old;
/* Get the added string: */
last_str = newSVpvn_utf8(s + old, l, UTF);
if (deltanext == 0 && pos_before == b) {
/* What was added is a constant string */
if (mincount > 1) {
SvGROW(last_str, (mincount * l) + 1);
repeatcpy(SvPVX(last_str) + l,
SvPVX_const(last_str), l, mincount - 1);
SvCUR_set(last_str, SvCUR(last_str) * mincount);
/* Add additional parts. */
SvCUR_set(data->last_found,
SvCUR(data->last_found) - l);
sv_catsv(data->last_found, last_str);
{
SV * sv = data->last_found;
MAGIC *mg =
SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg && mg->mg_len >= 0)
mg->mg_len += CHR_SVLEN(last_str) - l;
}
data->last_end += l * (mincount - 1);
}
} else {
/* start offset must point into the last copy */
data->last_start_min += minnext * (mincount - 1);
data->last_start_max += is_inf ? I32_MAX
: (maxcount - 1) * (minnext + data->pos_delta);
}
}
/* It is counted once already... */
data->pos_min += minnext * (mincount - counted);
data->pos_delta += - counted * deltanext +
(minnext + deltanext) * maxcount - minnext * mincount;
if (mincount != maxcount) {
/* Cannot extend fixed substrings found inside
the group. */
SCAN_COMMIT(pRExC_state,data,minlenp);
if (mincount && last_str) {
SV * const sv = data->last_found;
MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
mg_find(sv, PERL_MAGIC_utf8) : NULL;
if (mg)
mg->mg_len = -1;
sv_setsv(sv, last_str);
data->last_end = data->pos_min;
data->last_start_min =
data->pos_min - CHR_SVLEN(last_str);
data->last_start_max = is_inf
? I32_MAX
: data->pos_min + data->pos_delta
- CHR_SVLEN(last_str);
}
data->longest = &(data->longest_float);
}
SvREFCNT_dec(last_str);
}
if (data && (fl & SF_HAS_EVAL))
data->flags |= SF_HAS_EVAL;
optimize_curly_tail:
if (OP(oscan) != CURLYX) {
while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
&& NEXT_OFF(next))
NEXT_OFF(oscan) += NEXT_OFF(next);
}
continue;
default: /* REF and CLUMP only? */
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
data->longest = &(data->longest_float);
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR)
cl_anything(pRExC_state, data->start_class);
flags &= ~SCF_DO_STCLASS;
break;
}
}
else if (OP(scan) == LNBREAK) {
if (flags & SCF_DO_STCLASS) {
int value = 0;
data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
if (flags & SCF_DO_STCLASS_AND) {
for (value = 0; value < 256; value++)
if (!is_VERTWS_cp(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
else {
for (value = 0; value < 256; value++)
if (is_VERTWS_cp(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
if (flags & SCF_DO_STCLASS_OR)
cl_and(data->start_class, and_withp);
flags &= ~SCF_DO_STCLASS;
}
min += 1;
delta += 1;
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
data->pos_min += 1;
data->pos_delta += 1;
data->longest = &(data->longest_float);
}
}
else if (OP(scan) == FOLDCHAR) {
int d = ARG(scan)==0xDF ? 1 : 2;
flags &= ~SCF_DO_STCLASS;
min += 1;
delta += d;
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
data->pos_min += 1;
data->pos_delta += d;
data->longest = &(data->longest_float);
}
}
else if (strchr((const char*)PL_simple,OP(scan))) {
int value = 0;
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp);
data->pos_min++;
}
min++;
if (flags & SCF_DO_STCLASS) {
data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
/* Some of the logic below assumes that switching
locale on will only add false positives. */
switch (PL_regkind[OP(scan)]) {
case SANY:
default:
do_default:
/* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
cl_anything(pRExC_state, data->start_class);
break;
case REG_ANY:
if (OP(scan) == SANY)
goto do_default;
if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
|| (data->start_class->flags & ANYOF_CLASS));
cl_anything(pRExC_state, data->start_class);
}
if (flags & SCF_DO_STCLASS_AND || !value)
ANYOF_BITMAP_CLEAR(data->start_class,'\n');
break;
case ANYOF:
if (flags & SCF_DO_STCLASS_AND)
cl_and(data->start_class,
(struct regnode_charclass_class*)scan);
else
cl_or(pRExC_state, data->start_class,
(struct regnode_charclass_class*)scan);
break;
case ALNUM:
if (flags & SCF_DO_STCLASS_AND) {
if (!(data->start_class->flags & ANYOF_LOCALE)) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
for (value = 0; value < 256; value++)
if (!isALNUM(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
else {
for (value = 0; value < 256; value++)
if (isALNUM(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
case ALNUML:
if (flags & SCF_DO_STCLASS_AND) {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
}
else {
ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
data->start_class->flags |= ANYOF_LOCALE;
}
break;
case NALNUM:
if (flags & SCF_DO_STCLASS_AND) {
if (!(data->start_class->flags & ANYOF_LOCALE)) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
for (value = 0; value < 256; value++)
if (isALNUM(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
else {
for (value = 0; value < 256; value++)
if (!isALNUM(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
case NALNUML:
if (flags & SCF_DO_STCLASS_AND) {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
}
else {
data->start_class->flags |= ANYOF_LOCALE;
ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
}
break;
case SPACE:
if (flags & SCF_DO_STCLASS_AND) {
if (!(data->start_class->flags & ANYOF_LOCALE)) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
for (value = 0; value < 256; value++)
if (!isSPACE(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
else {
for (value = 0; value < 256; value++)
if (isSPACE(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
case SPACEL:
if (flags & SCF_DO_STCLASS_AND) {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
}
else {
data->start_class->flags |= ANYOF_LOCALE;
ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
}
break;
case NSPACE:
if (flags & SCF_DO_STCLASS_AND) {
if (!(data->start_class->flags & ANYOF_LOCALE)) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
for (value = 0; value < 256; value++)
if (isSPACE(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
else {
for (value = 0; value < 256; value++)
if (!isSPACE(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
case NSPACEL:
if (flags & SCF_DO_STCLASS_AND) {
if (data->start_class->flags & ANYOF_LOCALE) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
for (value = 0; value < 256; value++)
if (!isSPACE(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
}
else {
data->start_class->flags |= ANYOF_LOCALE;
ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
}
break;
case DIGIT:
if (flags & SCF_DO_STCLASS_AND) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
for (value = 0; value < 256; value++)
if (!isDIGIT(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
else {
for (value = 0; value < 256; value++)
if (isDIGIT(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
case NDIGIT:
if (flags & SCF_DO_STCLASS_AND) {
ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
for (value = 0; value < 256; value++)
if (isDIGIT(value))
ANYOF_BITMAP_CLEAR(data->start_class, value);
}
else {
if (data->start_class->flags & ANYOF_LOCALE)
ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
else {
for (value = 0; value < 256; value++)
if (!isDIGIT(value))
ANYOF_BITMAP_SET(data->start_class, value);
}
}
break;
CASE_SYNST_FNC(VERTWS);
CASE_SYNST_FNC(HORIZWS);
}
if (flags & SCF_DO_STCLASS_OR)
cl_and(data->start_class, and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
data->flags |= (OP(scan) == MEOL
? SF_BEFORE_MEOL
: SF_BEFORE_SEOL);
}
else if ( PL_regkind[OP(scan)] == BRANCHJ
/* Lookbehind, or need to calculate parens/evals/stclass: */
&& (scan->flags || data || (flags & SCF_DO_STCLASS))
&& (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY
|| OP(scan) == UNLESSM )
{
/* Negative Lookahead/lookbehind
In this case we can't do fixed string optimisation.
*/
I32 deltanext, minnext, fake = 0;
regnode *nscan;
struct regnode_charclass_class intrnl;
int f = 0;
data_fake.flags = 0;
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
cl_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
last, &data_fake, stopparen, recursed, NULL, f, depth+1);
if (scan->flags) {
if (deltanext) {
FAIL("Variable length lookbehind not implemented");
}
else if (minnext > (I32)U8_MAX) {
FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
}
scan->flags = (U8)minnext;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (f & SCF_DO_STCLASS_AND) {
if (flags & SCF_DO_STCLASS_OR) {
/* OR before, AND after: ideally we would recurse with
* data_fake to get the AND applied by study of the
* remainder of the pattern, and then derecurse;
* *** HACK *** for now just treat as "no information".
* See [perl #56690].
*/
cl_init(pRExC_state, data->start_class);
} else {
/* AND before and after: combine and continue */
const int was = (data->start_class->flags & ANYOF_EOS);
cl_and(data->start_class, &intrnl);
if (was)
data->start_class->flags |= ANYOF_EOS;
}
}
}
#if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
else {
/* Positive Lookahead/lookbehind
In this case we can do fixed string optimisation,
but we must be careful about it. Note in the case of
lookbehind the positions will be offset by the minimum
length of the pattern, something we won't know about
until after the recurse.
*/
I32 deltanext, fake = 0;
regnode *nscan;
struct regnode_charclass_class intrnl;
int f = 0;
/* We use SAVEFREEPV so that when the full compile
is finished perl will clean up the allocated
minlens when its all done. This was we don't
have to worry about freeing them when we know
they wont be used, which would be a pain.
*/
I32 *minnextp;
Newx( minnextp, 1, I32 );
SAVEFREEPV(minnextp);
if (data) {
StructCopy(data, &data_fake, scan_data_t);
if ((flags & SCF_DO_SUBSTR) && data->last_found) {
f |= SCF_DO_SUBSTR;
if (scan->flags)
SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
data_fake.last_found=newSVsv(data->last_found);
}
}
else
data_fake.last_closep = &fake;
data_fake.flags = 0;
data_fake.pos_delta = delta;
if (is_inf)
data_fake.flags |= SF_IS_INF;
if ( flags & SCF_DO_STCLASS && !scan->flags
&& OP(scan) == IFMATCH ) { /* Lookahead */
cl_init(pRExC_state, &intrnl);
data_fake.start_class = &intrnl;
f |= SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
next = regnext(scan);
nscan = NEXTOPER(NEXTOPER(scan));
*minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext,
last, &data_fake, stopparen, recursed, NULL, f,depth+1);
if (scan->flags) {
if (deltanext) {
FAIL("Variable length lookbehind not implemented");
}
else if (*minnextp > (I32)U8_MAX) {
FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
}
scan->flags = (U8)*minnextp;
}
*minnextp += min;
if (f & SCF_DO_STCLASS_AND) {
const int was = (data->start_class->flags & ANYOF_EOS);
cl_and(data->start_class, &intrnl);
if (was)
data->start_class->flags |= ANYOF_EOS;
}
if (data) {
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
if (RExC_rx->minlen<*minnextp)
RExC_rx->minlen=*minnextp;
SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
SvREFCNT_dec(data_fake.last_found);
if ( data_fake.minlen_fixed != minlenp )
{
data->offset_fixed= data_fake.offset_fixed;
data->minlen_fixed= data_fake.minlen_fixed;
data->lookbehind_fixed+= scan->flags;
}
if ( data_fake.minlen_float != minlenp )
{
data->minlen_float= data_fake.minlen_float;
data->offset_float_min=data_fake.offset_float_min;
data->offset_float_max=data_fake.offset_float_max;
data->lookbehind_float+= scan->flags;
}
}
}
}
#endif
}
else if (OP(scan) == OPEN) {
if (stopparen != (I32)ARG(scan))
pars++;
}
else if (OP(scan) == CLOSE) {
if (stopparen == (I32)ARG(scan)) {
break;
}
if ((I32)ARG(scan) == is_par) {
next = regnext(scan);
if ( next && (OP(next) != WHILEM) && next < last)
is_par = 0; /* Disable optimization */
}
if (data)
*(data->last_closep) = ARG(scan);
}
else if (OP(scan) == EVAL) {
if (data)
data->flags |= SF_HAS_EVAL;
}
else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp);
flags &= ~SCF_DO_SUBSTR;
}
if (data && OP(scan)==ACCEPT) {
data->flags |= SCF_SEEN_ACCEPT;
if (stopmin > min)
stopmin = min;
}
}
else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
{
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp);
data->longest = &(data->longest_float);
}
is_inf = is_inf_internal = 1;
if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
cl_anything(pRExC_state, data->start_class);
flags &= ~SCF_DO_STCLASS;
}
else if (OP(scan) == GPOS) {
if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
!(delta || is_inf || (data && data->pos_delta)))
{
if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
RExC_rx->extflags |= RXf_ANCH_GPOS;
if (RExC_rx->gofs < (U32)min)
RExC_rx->gofs = min;
} else {
RExC_rx->extflags |= RXf_GPOS_FLOAT;
RExC_rx->gofs = 0;
}
}
#ifdef TRIE_STUDY_OPT
#ifdef FULL_TRIE_STUDY
else if (PL_regkind[OP(scan)] == TRIE) {
/* NOTE - There is similar code to this block above for handling
BRANCH nodes on the initial study. If you change stuff here
check there too. */
regnode *trie_node= scan;
regnode *tail= regnext(scan);
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
I32 max1 = 0, min1 = I32_MAX;
struct regnode_charclass_class accum;
if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
if (flags & SCF_DO_STCLASS)
cl_init_zero(pRExC_state, &accum);
if (!trie->jump) {
min1= trie->minlen;
max1= trie->maxlen;
} else {
const regnode *nextbranch= NULL;
U32 word;
for ( word=1 ; word <= trie->wordcount ; word++)
{
I32 deltanext=0, minnext=0, f = 0, fake;
struct regnode_charclass_class this_class;
data_fake.flags = 0;
if (data) {
data_fake.whilem_c = data->whilem_c;
data_fake.last_closep = data->last_closep;
}
else
data_fake.last_closep = &fake;
data_fake.pos_delta = delta;
if (flags & SCF_DO_STCLASS) {
cl_init(pRExC_state, &this_class);
data_fake.start_class = &this_class;
f = SCF_DO_STCLASS_AND;
}
if (flags & SCF_WHILEM_VISITED_POS)
f |= SCF_WHILEM_VISITED_POS;
if (trie->jump[word]) {
if (!nextbranch)
nextbranch = trie_node + trie->jump[0];
scan= trie_node + trie->jump[word];
/* We go from the jump point to the branch that follows
it. Note this means we need the vestigal unused branches
even though they arent otherwise used.
*/
minnext = study_chunk(pRExC_state, &scan, minlenp,
&deltanext, (regnode *)nextbranch, &data_fake,
stopparen, recursed, NULL, f,depth+1);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode*)nextbranch);
if (min1 > (I32)(minnext + trie->minlen))
min1 = minnext + trie->minlen;
if (max1 < (I32)(minnext + deltanext + trie->maxlen))
max1 = minnext + deltanext + trie->maxlen;
if (deltanext == I32_MAX)
is_inf = is_inf_internal = 1;
if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
pars++;
if (data_fake.flags & SCF_SEEN_ACCEPT) {
if ( stopmin > min + min1)
stopmin = min + min1;
flags &= ~SCF_DO_SUBSTR;
if (data)
data->flags |= SCF_SEEN_ACCEPT;
}
if (data) {
if (data_fake.flags & SF_HAS_EVAL)
data->flags |= SF_HAS_EVAL;
data->whilem_c = data_fake.whilem_c;
}
if (flags & SCF_DO_STCLASS)
cl_or(pRExC_state, &accum, &this_class);
}
}
if (flags & SCF_DO_SUBSTR) {
data->pos_min += min1;
data->pos_delta += max1 - min1;
if (max1 != min1 || is_inf)
data->longest = &(data->longest_float);
}
min += min1;
delta += max1 - min1;
if (flags & SCF_DO_STCLASS_OR) {
cl_or(pRExC_state, data->start_class, &accum);
if (min1) {
cl_and(data->start_class, and_withp);
flags &= ~SCF_DO_STCLASS;
}
}
else if (flags & SCF_DO_STCLASS_AND) {
if (min1) {
cl_and(data->start_class, &accum);
flags &= ~SCF_DO_STCLASS;
}
else {
/* Switch to OR mode: cache the old value of
* data->start_class */
INIT_AND_WITHP;
StructCopy(data->start_class, and_withp,
struct regnode_charclass_class);
flags &= ~SCF_DO_STCLASS_AND;
StructCopy(&accum, data->start_class,
struct regnode_charclass_class);
flags |= SCF_DO_STCLASS_OR;
data->start_class->flags |= ANYOF_EOS;
}
}
scan= tail;
continue;
}
#else
else if (PL_regkind[OP(scan)] == TRIE) {
reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
U8*bang=NULL;
min += trie->minlen;
delta += (trie->maxlen - trie->minlen);
flags &= ~SCF_DO_STCLASS; /* xxx */
if (flags & SCF_DO_SUBSTR) {
SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot expect anything... */
data->pos_min += trie->minlen;
data->pos_delta += (trie->maxlen - trie->minlen);
if (trie->maxlen != trie->minlen)
data->longest = &(data->longest_float);
}
if (trie->jump) /* no more substrings -- for now /grr*/
flags &= ~SCF_DO_SUBSTR;
}
#endif /* old or new */
#endif /* TRIE_STUDY_OPT */
/* Else: zero-length, ignore. */
scan = regnext(scan);
}
if (frame) {
last = frame->last;
scan = frame->next;
stopparen = frame->stop;
frame = frame->prev;
goto fake_study_recurse;
}
finish:
assert(!frame);
DEBUG_STUDYDATA("pre-fin:",data,depth);
*scanp = scan;
*deltap = is_inf_internal ? I32_MAX : delta;
if (flags & SCF_DO_SUBSTR && is_inf)
data->pos_delta = I32_MAX - data->pos_min;
if (is_par > (I32)U8_MAX)
is_par = 0;
if (is_par && pars==1 && data) {
data->flags |= SF_IN_PAR;
data->flags &= ~SF_HAS_PAR;
}
else if (pars && data) {
data->flags |= SF_HAS_PAR;
data->flags &= ~SF_IN_PAR;
}
if (flags & SCF_DO_STCLASS_OR)
cl_and(data->start_class, and_withp);
if (flags & SCF_TRIE_RESTUDY)
data->flags |= SCF_TRIE_RESTUDY;
DEBUG_STUDYDATA("post-fin:",data,depth);
return min < stopmin ? min : stopmin;
}
STATIC U32
S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
{
U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
PERL_ARGS_ASSERT_ADD_DATA;
Renewc(RExC_rxi->data,
sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
char, struct reg_data);
if(count)
Renew(RExC_rxi->data->what, count + n, U8);
else
Newx(RExC_rxi->data->what, n, U8);
RExC_rxi->data->count = count + n;
Copy(s, RExC_rxi->data->what + count, n, U8);
return count;
}
/*XXX: todo make this not included in a non debugging perl */
#ifndef PERL_IN_XSUB_RE
void
Perl_reginitcolors(pTHX)
{
dVAR;
const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
if (s) {
char *t = savepv(s);
int i = 0;
PL_colors[0] = t;
while (++i < 6) {
t = strchr(t, '\t');
if (t) {
*t = '\0';
PL_colors[i] = ++t;
}
else
PL_colors[i] = t = (char *)"";
}
} else {
int i = 0;
while (i < 6)
PL_colors[i++] = (char *)"";
}
PL_colorset = 1;
}
#endif
#ifdef TRIE_STUDY_OPT
#define CHECK_RESTUDY_GOTO \
if ( \
(data.flags & SCF_TRIE_RESTUDY) \
&& ! restudied++ \
) goto reStudy
#else
#define CHECK_RESTUDY_GOTO
#endif
/*
- pregcomp - compile a regular expression into internal code
*
* We can't allocate space until we know how big the compiled form will be,
* but we can't compile it (and thus know how big it is) until we've got a
* place to put the code. So we cheat: we compile it twice, once with code
* generation turned off and size counting turned on, and once "for real".
* This also means that we don't allocate space until we are sure that the
* thing really will compile successfully, and we never have to move the
* code and thus invalidate pointers into it. (Note that it has to be in
* one piece because free() must be able to free it all.) [NB: not true in perl]
*
* Beware that the optimization-preparation code in here knows about some
* of the structure of the compiled regexp. [I'll say.]
*/
#ifndef PERL_IN_XSUB_RE
#define RE_ENGINE_PTR &PL_core_reg_engine
#else
extern const struct regexp_engine my_reg_engine;
#define RE_ENGINE_PTR &my_reg_engine
#endif
#ifndef PERL_IN_XSUB_RE
REGEXP *
Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
{
dVAR;
HV * const table = GvHV(PL_hintgv);
PERL_ARGS_ASSERT_PREGCOMP;
/* Dispatch a request to compile a regexp to correct
regexp engine. */
if (table) {
SV **ptr= hv_fetchs(table, "regcomp", FALSE);
GET_RE_DEBUG_FLAGS_DECL;
if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
DEBUG_COMPILE_r({
PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
SvIV(*ptr));
});
return CALLREGCOMP_ENG(eng, pattern, flags);
}
}
return Perl_re_compile(aTHX_ pattern, flags);
}
#endif
REGEXP *
Perl_re_compile(pTHX_ SV * const pattern, U32 pm_flags)
{
dVAR;
REGEXP *rx;
struct regexp *r;
register regexp_internal *ri;
STRLEN plen;
char *exp = SvPV(pattern, plen);
char* xend = exp + plen;
regnode *scan;
I32 flags;
I32 minlen = 0;
I32 sawplus = 0;
I32 sawopen = 0;
scan_data_t data;
RExC_state_t RExC_state;
RExC_state_t * const pRExC_state = &RExC_state;
#ifdef TRIE_STUDY_OPT
int restudied= 0;
RExC_state_t copyRExC_state;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_COMPILE;
DEBUG_r(if (!PL_colorset) reginitcolors());
RExC_utf8 = RExC_orig_utf8 = SvUTF8(pattern);
DEBUG_COMPILE_r({
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RExC_utf8,
dsv, exp, plen, 60);
PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
PL_colors[4],PL_colors[5],s);
});
redo_first_pass:
RExC_precomp = exp;
RExC_flags = pm_flags;
RExC_sawback = 0;
RExC_seen = 0;
RExC_seen_zerolen = *exp == '^' ? -1 : 0;
RExC_seen_evals = 0;
RExC_extralen = 0;
/* First pass: determine size, legality. */
RExC_parse = exp;
RExC_start = exp;
RExC_end = xend;
RExC_naughty = 0;
RExC_npar = 1;
RExC_nestroot = 0;
RExC_size = 0L;
RExC_emit = &PL_regdummy;
RExC_whilem_seen = 0;
RExC_open_parens = NULL;
RExC_close_parens = NULL;
RExC_opend = NULL;
RExC_paren_names = NULL;
#ifdef DEBUGGING
RExC_paren_name_list = NULL;
#endif
RExC_recurse = NULL;
RExC_recurse_count = 0;
#if 0 /* REGC() is (currently) a NOP at the first pass.
* Clever compilers notice this and complain. --jhi */
REGC((U8)REG_MAGIC, (char*)RExC_emit);
#endif
DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
if (reg(pRExC_state, 0, &flags,1) == NULL) {
RExC_precomp = NULL;
return(NULL);
}
if (RExC_utf8 && !RExC_orig_utf8) {
/* It's possible to write a regexp in ascii that represents Unicode
codepoints outside of the byte range, such as via \x{100}. If we
detect such a sequence we have to convert the entire pattern to utf8
and then recompile, as our sizing calculation will have been based
on 1 byte == 1 character, but we will need to use utf8 to encode
at least some part of the pattern, and therefore must convert the whole
thing.
XXX: somehow figure out how to make this less expensive...
-- dmq */
STRLEN len = plen;
DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
"UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
exp = (char*)Perl_bytes_to_utf8(aTHX_ (U8*)exp, &len);
xend = exp + len;
RExC_orig_utf8 = RExC_utf8;
SAVEFREEPV(exp);
goto redo_first_pass;
}
DEBUG_PARSE_r({
PerlIO_printf(Perl_debug_log,
"Required size %"IVdf" nodes\n"
"Starting second pass (creation)\n",
(IV)RExC_size);
RExC_lastnum=0;
RExC_lastparse=NULL;
});
/* Small enough for pointer-storage convention?
If extralen==0, this means that we will not need long jumps. */
if (RExC_size >= 0x10000L && RExC_extralen)
RExC_size += RExC_extralen;
else
RExC_extralen = 0;
if (RExC_whilem_seen > 15)
RExC_whilem_seen = 15;
/* Allocate space and zero-initialize. Note, the two step process
of zeroing when in debug mode, thus anything assigned has to
happen after that */
rx = (REGEXP*) newSV_type(SVt_REGEXP);
r = (struct regexp*)SvANY(rx);
Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
char, regexp_internal);
if ( r == NULL || ri == NULL )
FAIL("Regexp out of space");
#ifdef DEBUGGING
/* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
#else
/* bulk initialize base fields with 0. */
Zero(ri, sizeof(regexp_internal), char);
#endif
/* non-zero initialization begins here */
RXi_SET( r, ri );
r->engine= RE_ENGINE_PTR;
r->extflags = pm_flags;
{
bool has_p = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
>> RXf_PMf_STD_PMMOD_SHIFT);
const char *fptr = STD_PAT_MODS; /*"msix"*/
char *p;
const STRLEN wraplen = plen + has_minus + has_p + has_runon
+ (sizeof(STD_PAT_MODS) - 1)
+ (sizeof("(?:)") - 1);
p = sv_grow(MUTABLE_SV(rx), wraplen + 1);
SvCUR_set(rx, wraplen);
SvPOK_on(rx);
SvFLAGS(rx) |= SvUTF8(pattern);
*p++='('; *p++='?';
if (has_p)
*p++ = KEEPCOPY_PAT_MOD; /*'p'*/
{
char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
char *colon = r + 1;
char ch;
while((ch = *fptr++)) {
if(reganch & 1)
*p++ = ch;
else
*r-- = ch;
reganch >>= 1;
}
if(has_minus) {
*r = '-';
p = colon;
}
}
*p++ = ':';
Copy(RExC_precomp, p, plen, char);
assert ((RX_WRAPPED(rx) - p) < 16);
r->pre_prefix = p - RX_WRAPPED(rx);
p += plen;
if (has_runon)
*p++ = '\n';
*p++ = ')';
*p = 0;
}
r->intflags = 0;
r->nparens = RExC_npar - 1; /* set early to validate backrefs */
if (RExC_seen & REG_SEEN_RECURSE) {
Newxz(RExC_open_parens, RExC_npar,regnode *);
SAVEFREEPV(RExC_open_parens);
Newxz(RExC_close_parens,RExC_npar,regnode *);
SAVEFREEPV(RExC_close_parens);
}
/* Useful during FAIL. */
#ifdef RE_TRACK_PATTERN_OFFSETS
Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
"%s %"UVuf" bytes for offset annotations.\n",
ri->u.offsets ? "Got" : "Couldn't get",
(UV)((2*RExC_size+1) * sizeof(U32))));
#endif
SetProgLen(ri,RExC_size);
RExC_rx_sv = rx;
RExC_rx = r;
RExC_rxi = ri;
/* Second pass: emit code. */
RExC_flags = pm_flags; /* don't let top level (?i) bleed */
RExC_parse = exp;
RExC_end = xend;
RExC_naughty = 0;
RExC_npar = 1;
RExC_emit_start = ri->program;
RExC_emit = ri->program;
RExC_emit_bound = ri->program + RExC_size + 1;
/* Store the count of eval-groups for security checks: */
RExC_rx->seen_evals = RExC_seen_evals;
REGC((U8)REG_MAGIC, (char*) RExC_emit++);
if (reg(pRExC_state, 0, &flags,1) == NULL) {
ReREFCNT_dec(rx);
return(NULL);
}
/* XXXX To minimize changes to RE engine we always allocate
3-units-long substrs field. */
Newx(r->substrs, 1, struct reg_substr_data);
if (RExC_recurse_count) {
Newxz(RExC_recurse,RExC_recurse_count,regnode *);
SAVEFREEPV(RExC_recurse);
}
reStudy:
r->minlen = minlen = sawplus = sawopen = 0;
Zero(r->substrs, 1, struct reg_substr_data);
#ifdef TRIE_STUDY_OPT
if (!restudied) {
StructCopy(&zero_scan_data, &data, scan_data_t);
copyRExC_state = RExC_state;
} else {
U32 seen=RExC_seen;
DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
RExC_state = copyRExC_state;
if (seen & REG_TOP_LEVEL_BRANCHES)
RExC_seen |= REG_TOP_LEVEL_BRANCHES;
else
RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
if (data.last_found) {
SvREFCNT_dec(data.longest_fixed);
SvREFCNT_dec(data.longest_float);
SvREFCNT_dec(data.last_found);
}
StructCopy(&zero_scan_data, &data, scan_data_t);
}
#else
StructCopy(&zero_scan_data, &data, scan_data_t);
#endif
/* Dig out information for optimizations. */
r->extflags = RExC_flags; /* was pm_op */
/*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
if (UTF)
SvUTF8_on(rx); /* Unicode in it? */
ri->regstclass = NULL;
if (RExC_naughty >= 10) /* Probably an expensive pattern. */
r->intflags |= PREGf_NAUGHTY;
scan = ri->program + 1; /* First BRANCH. */
/* testing for BRANCH here tells us whether there is "must appear"
data in the pattern. If there is then we can use it for optimisations */
if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /* Only one top-level choice. */
I32 fake;
STRLEN longest_float_length, longest_fixed_length;
struct regnode_charclass_class ch_class; /* pointed to by data */
int stclass_flag;
I32 last_close = 0; /* pointed to by data */
regnode *first= scan;
regnode *first_next= regnext(first);
/*
* Skip introductions and multiplicators >= 1
* so that we can extract the 'meat' of the pattern that must
* match in the large if() sequence following.
* NOTE that EXACT is NOT covered here, as it is normally
* picked up by the optimiser separately.
*
* This is unfortunate as the optimiser isnt handling lookahead
* properly currently.
*
*/
while ((OP(first) == OPEN && (sawopen = 1)) ||
/* An OR of *one* alternative - should not happen now. */
(OP(first) == BRANCH && OP(first_next) != BRANCH) ||
/* for now we can't handle lookbehind IFMATCH*/
(OP(first) == IFMATCH && !first->flags) ||
(OP(first) == PLUS) ||
(OP(first) == MINMOD) ||
/* An {n,m} with n>0 */
(PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
(OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
{
/*
* the only op that could be a regnode is PLUS, all the rest
* will be regnode_1 or regnode_2.
*
*/
if (OP(first) == PLUS)
sawplus = 1;
else
first += regarglen[OP(first)];
first = NEXTOPER(first);
first_next= regnext(first);
}
/* Starting-point info. */
again:
DEBUG_PEEP("first:",first,0);
/* Ignore EXACT as we deal with it later. */
if (PL_regkind[OP(first)] == EXACT) {
if (OP(first) == EXACT)
NOOP; /* Empty, get anchored substr later. */
else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
ri->regstclass = first;
}
#ifdef TRIE_STCLASS
else if (PL_regkind[OP(first)] == TRIE &&
((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0)
{
regnode *trie_op;
/* this can happen only on restudy */
if ( OP(first) == TRIE ) {
struct regnode_1 *trieop = (struct regnode_1 *)
PerlMemShared_calloc(1, sizeof(struct regnode_1));
StructCopy(first,trieop,struct regnode_1);
trie_op=(regnode *)trieop;
} else {
struct regnode_charclass *trieop = (struct regnode_charclass *)
PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
StructCopy(first,trieop,struct regnode_charclass);
trie_op=(regnode *)trieop;
}
OP(trie_op)+=2;
make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
ri->regstclass = trie_op;
}
#endif
else if (strchr((const char*)PL_simple,OP(first)))
ri->regstclass = first;
else if (PL_regkind[OP(first)] == BOUND ||
PL_regkind[OP(first)] == NBOUND)
ri->regstclass = first;
else if (PL_regkind[OP(first)] == BOL) {
r->extflags |= (OP(first) == MBOL
? RXf_ANCH_MBOL
: (OP(first) == SBOL
? RXf_ANCH_SBOL
: RXf_ANCH_BOL));
first = NEXTOPER(first);
goto again;
}
else if (OP(first) == GPOS) {
r->extflags |= RXf_ANCH_GPOS;
first = NEXTOPER(first);
goto again;
}
else if ((!sawopen || !RExC_sawback) &&
(OP(first) == STAR &&
PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
!(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
{
/* turn .* into ^.* with an implied $*=1 */
const int type =
(OP(NEXTOPER(first)) == REG_ANY)
? RXf_ANCH_MBOL
: RXf_ANCH_SBOL;
r->extflags |= type;
r->intflags |= PREGf_IMPLICIT;
first = NEXTOPER(first);
goto again;
}
if (sawplus && (!sawopen || !RExC_sawback)
&& !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
/* x+ must match at the 1st pos of run of x's */
r->intflags |= PREGf_SKIP;
/* Scan is after the zeroth branch, first is atomic matcher. */
#ifdef TRIE_STUDY_OPT
DEBUG_PARSE_r(
if (!restudied)
PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
(IV)(first - scan + 1))
);
#else
DEBUG_PARSE_r(
PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
(IV)(first - scan + 1))
);
#endif
/*
* If there's something expensive in the r.e., find the
* longest literal string that must appear and make it the
* regmust. Resolve ties in favor of later strings, since
* the regstart check works with the beginning of the r.e.
* and avoiding duplication strengthens checking. Not a
* strong reason, but sufficient in the absence of others.
* [Now we resolve ties in favor of the earlier string if
* it happens that c_offset_min has been invalidated, since the
* earlier string may buy us something the later one won't.]
*/
data.longest_fixed = newSVpvs("");
data.longest_float = newSVpvs("");
data.last_found = newSVpvs("");
data.longest = &(data.longest_fixed);
first = scan;
if (!ri->regstclass) {
cl_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
stclass_flag = SCF_DO_STCLASS_AND;
} else /* XXXX Check for BOUND? */
stclass_flag = 0;
data.last_closep = &last_close;
minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
&data, -1, NULL, NULL,
SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
CHECK_RESTUDY_GOTO;
if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
&& data.last_start_min == 0 && data.last_end > 0
&& !RExC_seen_zerolen
&& !(RExC_seen & REG_SEEN_VERBARG)
&& (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
r->extflags |= RXf_CHECK_ALL;
scan_commit(pRExC_state, &data,&minlen,0);
SvREFCNT_dec(data.last_found);
/* Note that code very similar to this but for anchored string
follows immediately below, changes may need to be made to both.
Be careful.
*/
longest_float_length = CHR_SVLEN(data.longest_float);
if (longest_float_length
|| (data.flags & SF_FL_BEFORE_EOL
&& (!(data.flags & SF_FL_BEFORE_MEOL)
|| (RExC_flags & RXf_PMf_MULTILINE))))
{
I32 t,ml;
if (SvCUR(data.longest_fixed) /* ok to leave SvCUR */
&& data.offset_fixed == data.offset_float_min
&& SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
goto remove_float; /* As in (a)+. */
/* copy the information about the longest float from the reg_scan_data
over to the program. */
if (SvUTF8(data.longest_float)) {
r->float_utf8 = data.longest_float;
r->float_substr = NULL;
} else {
r->float_substr = data.longest_float;
r->float_utf8 = NULL;
}
/* float_end_shift is how many chars that must be matched that
follow this item. We calculate it ahead of time as once the
lookbehind offset is added in we lose the ability to correctly
calculate it.*/
ml = data.minlen_float ? *(data.minlen_float)
: (I32)longest_float_length;
r->float_end_shift = ml - data.offset_float_min
- longest_float_length + (SvTAIL(data.longest_float) != 0)
+ data.lookbehind_float;
r->float_min_offset = data.offset_float_min - data.lookbehind_float;
r->float_max_offset = data.offset_float_max;
if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
r->float_max_offset -= data.lookbehind_float;
t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
&& (!(data.flags & SF_FL_BEFORE_MEOL)
|| (RExC_flags & RXf_PMf_MULTILINE)));
fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
}
else {
remove_float:
r->float_substr = r->float_utf8 = NULL;
SvREFCNT_dec(data.longest_float);
longest_float_length = 0;
}
/* Note that code very similar to this but for floating string
is immediately above, changes may need to be made to both.
Be careful.
*/
longest_fixed_length = CHR_SVLEN(data.longest_fixed);
if (longest_fixed_length
|| (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
&& (!(data.flags & SF_FIX_BEFORE_MEOL)
|| (RExC_flags & RXf_PMf_MULTILINE))))
{
I32 t,ml;
/* copy the information about the longest fixed
from the reg_scan_data over to the program. */
if (SvUTF8(data.longest_fixed)) {
r->anchored_utf8 = data.longest_fixed;
r->anchored_substr = NULL;
} else {
r->anchored_substr = data.longest_fixed;
r->anchored_utf8 = NULL;
}
/* fixed_end_shift is how many chars that must be matched that
follow this item. We calculate it ahead of time as once the
lookbehind offset is added in we lose the ability to correctly
calculate it.*/
ml = data.minlen_fixed ? *(data.minlen_fixed)
: (I32)longest_fixed_length;
r->anchored_end_shift = ml - data.offset_fixed
- longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
+ data.lookbehind_fixed;
r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
&& (!(data.flags & SF_FIX_BEFORE_MEOL)
|| (RExC_flags & RXf_PMf_MULTILINE)));
fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
}
else {
r->anchored_substr = r->anchored_utf8 = NULL;
SvREFCNT_dec(data.longest_fixed);
longest_fixed_length = 0;
}
if (ri->regstclass
&& (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
ri->regstclass = NULL;
if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
&& stclass_flag
&& !(data.start_class->flags & ANYOF_EOS)
&& !cl_is_anything(data.start_class))
{
const U32 n = add_data(pRExC_state, 1, "f");
Newx(RExC_rxi->data->data[n], 1,
struct regnode_charclass_class);
StructCopy(data.start_class,
(struct regnode_charclass_class*)RExC_rxi->data->data[n],
struct regnode_charclass_class);
ri->regstclass = (regnode*)RExC_rxi->data->data[n];
r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
regprop(r, sv, (regnode*)data.start_class);
PerlIO_printf(Perl_debug_log,
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
}
/* A temporary algorithm prefers floated substr to fixed one to dig more info. */
if (longest_fixed_length > longest_float_length) {
r->check_end_shift = r->anchored_end_shift;
r->check_substr = r->anchored_substr;
r->check_utf8 = r->anchored_utf8;
r->check_offset_min = r->check_offset_max = r->anchored_offset;
if (r->extflags & RXf_ANCH_SINGLE)
r->extflags |= RXf_NOSCAN;
}
else {
r->check_end_shift = r->float_end_shift;
r->check_substr = r->float_substr;
r->check_utf8 = r->float_utf8;
r->check_offset_min = r->float_min_offset;
r->check_offset_max = r->float_max_offset;
}
/* XXXX Currently intuiting is not compatible with ANCH_GPOS.
This should be changed ASAP! */
if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
r->extflags |= RXf_USE_INTUIT;
if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
r->extflags |= RXf_INTUIT_TAIL;
}
/* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
if ( (STRLEN)minlen < longest_float_length )
minlen= longest_float_length;
if ( (STRLEN)minlen < longest_fixed_length )
minlen= longest_fixed_length;
*/
}
else {
/* Several toplevels. Best we can is to set minlen. */
I32 fake;
struct regnode_charclass_class ch_class;
I32 last_close = 0;
DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
scan = ri->program + 1;
cl_init(pRExC_state, &ch_class);
data.start_class = &ch_class;
data.last_closep = &last_close;
minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
&data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
CHECK_RESTUDY_GOTO;
r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
= r->float_substr = r->float_utf8 = NULL;
if (!(data.start_class->flags & ANYOF_EOS)
&& !cl_is_anything(data.start_class))
{
const U32 n = add_data(pRExC_state, 1, "f");
Newx(RExC_rxi->data->data[n], 1,
struct regnode_charclass_class);
StructCopy(data.start_class,
(struct regnode_charclass_class*)RExC_rxi->data->data[n],
struct regnode_charclass_class);
ri->regstclass = (regnode*)RExC_rxi->data->data[n];
r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
regprop(r, sv, (regnode*)data.start_class);
PerlIO_printf(Perl_debug_log,
"synthetic stclass \"%s\".\n",
SvPVX_const(sv));});
}
}
/* Guard against an embedded (?=) or (?<=) with a longer minlen than
the "real" pattern. */
DEBUG_OPTIMISE_r({
PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
(IV)minlen, (IV)r->minlen);
});
r->minlenret = minlen;
if (r->minlen < minlen)
r->minlen = minlen;
if (RExC_seen & REG_SEEN_GPOS)
r->extflags |= RXf_GPOS_SEEN;
if (RExC_seen & REG_SEEN_LOOKBEHIND)
r->extflags |= RXf_LOOKBEHIND_SEEN;
if (RExC_seen & REG_SEEN_EVAL)
r->extflags |= RXf_EVAL_SEEN;
if (RExC_seen & REG_SEEN_CANY)
r->extflags |= RXf_CANY_SEEN;
if (RExC_seen & REG_SEEN_VERBARG)
r->intflags |= PREGf_VERBARG_SEEN;
if (RExC_seen & REG_SEEN_CUTGROUP)
r->intflags |= PREGf_CUTGROUP_SEEN;
if (RExC_paren_names)
RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
else
RXp_PAREN_NAMES(r) = NULL;
#ifdef STUPID_PATTERN_CHECKS
if (RX_PRELEN(rx) == 0)
r->extflags |= RXf_NULL;
if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
/* XXX: this should happen BEFORE we compile */
r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
r->extflags |= RXf_WHITE;
else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
r->extflags |= RXf_START_ONLY;
#else
if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
/* XXX: this should happen BEFORE we compile */
r->extflags |= (RXf_SKIPWHITE|RXf_WHITE);
else {
regnode *first = ri->program + 1;
U8 fop = OP(first);
U8 nop = OP(NEXTOPER(first));
if (PL_regkind[fop] == NOTHING && nop == END)
r->extflags |= RXf_NULL;
else if (PL_regkind[fop] == BOL && nop == END)
r->extflags |= RXf_START_ONLY;
else if (fop == PLUS && nop ==SPACE && OP(regnext(first))==END)
r->extflags |= RXf_WHITE;
}
#endif
#ifdef DEBUGGING
if (RExC_paren_names) {
ri->name_list_idx = add_data( pRExC_state, 1, "p" );
ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
} else
#endif
ri->name_list_idx = 0;
if (RExC_recurse_count) {
for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
const regnode *scan = RExC_recurse[RExC_recurse_count-1];
ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
}
}
Newxz(r->offs, RExC_npar, regexp_paren_pair);
/* assume we don't need to swap parens around before we match */
DEBUG_DUMP_r({
PerlIO_printf(Perl_debug_log,"Final program:\n");
regdump(r);
});
#ifdef RE_TRACK_PATTERN_OFFSETS
DEBUG_OFFSETS_r(if (ri->u.offsets) {
const U32 len = ri->u.offsets[0];
U32 i;
GET_RE_DEBUG_FLAGS_DECL;
PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
for (i = 1; i <= len; i++) {
if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
(UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
}
PerlIO_printf(Perl_debug_log, "\n");
});
#endif
return rx;
}
#undef RE_ENGINE_PTR
SV*
Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF;
PERL_UNUSED_ARG(value);
if (flags & RXapif_FETCH) {
return reg_named_buff_fetch(rx, key, flags);
} else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
Perl_croak(aTHX_ "%s", PL_no_modify);
return NULL;
} else if (flags & RXapif_EXISTS) {
return reg_named_buff_exists(rx, key, flags)
? &PL_sv_yes
: &PL_sv_no;
} else if (flags & RXapif_REGNAMES) {
return reg_named_buff_all(rx, flags);
} else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
return reg_named_buff_scalar(rx, flags);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
const U32 flags)
{
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
PERL_UNUSED_ARG(lastkey);
if (flags & RXapif_FIRSTKEY)
return reg_named_buff_firstkey(rx, flags);
else if (flags & RXapif_NEXTKEY)
return reg_named_buff_nextkey(rx, flags);
else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
return NULL;
}
}
SV*
Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
const U32 flags)
{
AV *retarray = NULL;
SV *ret;
struct regexp *const rx = (struct regexp *)SvANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
if (flags & RXapif_ALL)
retarray=newAV();
if (rx && RXp_PAREN_NAMES(rx)) {
HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
if (he_str) {
IV i;
SV* sv_dat=HeVAL(he_str);
I32 *nums=(I32*)SvPVX(sv_dat);
for ( i=0; i<SvIVX(sv_dat); i++ ) {
if ((I32)(rx->nparens) >= nums[i]
&& rx->offs[nums[i]].start != -1
&& rx->offs[nums[i]].end != -1)
{
ret = newSVpvs("");
CALLREG_NUMBUF_FETCH(r,nums[i],ret);
if (!retarray)
return ret;
} else {
ret = newSVsv(&PL_sv_undef);
}
if (retarray)
av_push(retarray, ret);
}
if (retarray)
return newRV_noinc(MUTABLE_SV(retarray));
}
}
return NULL;
}
bool
Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
const U32 flags)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & RXapif_ALL) {
return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
} else {
SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
if (sv) {
SvREFCNT_dec(sv);
return TRUE;
} else {
return FALSE;
}
}
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
if ( rx && RXp_PAREN_NAMES(rx) ) {
(void)hv_iterinit(RXp_PAREN_NAMES(rx));
return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
} else {
return FALSE;
}
}
SV*
Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv = RXp_PAREN_NAMES(rx);
HE *temphe;
while ( (temphe = hv_iternext_flags(hv,0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
return newSVhek(HeKEY_hek(temphe));
}
}
}
return NULL;
}
SV*
Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
{
SV *ret;
AV *av;
I32 length;
struct regexp *const rx = (struct regexp *)SvANY(r);
PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
if (rx && RXp_PAREN_NAMES(rx)) {
if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
} else if (flags & RXapif_ONE) {
ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
av = MUTABLE_AV(SvRV(ret));
length = av_len(av);
SvREFCNT_dec(ret);
return newSViv(length + 1);
} else {
Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
return NULL;
}
}
return &PL_sv_undef;
}
SV*
Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
AV *av = newAV();
PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
if (rx && RXp_PAREN_NAMES(rx)) {
HV *hv= RXp_PAREN_NAMES(rx);
HE *temphe;
(void)hv_iterinit(hv);
while ( (temphe = hv_iternext_flags(hv,0)) ) {
IV i;
IV parno = 0;
SV* sv_dat = HeVAL(temphe);
I32 *nums = (I32*)SvPVX(sv_dat);
for ( i = 0; i < SvIVX(sv_dat); i++ ) {
if ((I32)(rx->lastparen) >= nums[i] &&
rx->offs[nums[i]].start != -1 &&
rx->offs[nums[i]].end != -1)
{
parno = nums[i];
break;
}
}
if (parno || flags & RXapif_ALL) {
av_push(av, newSVhek(HeKEY_hek(temphe)));
}
}
}
return newRV_noinc(MUTABLE_SV(av));
}
void
Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
SV * const sv)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
char *s = NULL;
I32 i = 0;
I32 s1, t1;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
if (!rx->subbeg) {
sv_setsv(sv,&PL_sv_undef);
return;
}
else
if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
/* $` */
i = rx->offs[0].start;
s = rx->subbeg;
}
else
if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
/* $' */
s = rx->subbeg + rx->offs[0].end;
i = rx->sublen - rx->offs[0].end;
}
else
if ( 0 <= paren && paren <= (I32)rx->nparens &&
(s1 = rx->offs[paren].start) != -1 &&
(t1 = rx->offs[paren].end) != -1)
{
/* $& $1 ... */
i = t1 - s1;
s = rx->subbeg + s1;
} else {
sv_setsv(sv,&PL_sv_undef);
return;
}
assert(rx->sublen >= (s - rx->subbeg) + i );
if (i >= 0) {
const int oldtainted = PL_tainted;
TAINT_NOT;
sv_setpvn(sv, s, i);
PL_tainted = oldtainted;
if ( (rx->extflags & RXf_CANY_SEEN)
? (RXp_MATCH_UTF8(rx)
&& (!i || is_utf8_string((U8*)s, i)))
: (RXp_MATCH_UTF8(rx)) )
{
SvUTF8_on(sv);
}
else
SvUTF8_off(sv);
if (PL_tainting) {
if (RXp_MATCH_TAINTED(rx)) {
if (SvTYPE(sv) >= SVt_PVMG) {
MAGIC* const mg = SvMAGIC(sv);
MAGIC* mgt;
PL_tainted = 1;
SvMAGIC_set(sv, mg->mg_moremagic);
SvTAINT(sv);
if ((mgt = SvMAGIC(sv))) {
mg->mg_moremagic = mgt;
SvMAGIC_set(sv, mg);
}
} else {
PL_tainted = 1;
SvTAINT(sv);
}
} else
SvTAINTED_off(sv);
}
} else {
sv_setsv(sv,&PL_sv_undef);
return;
}
}
void
Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
SV const * const value)
{
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
PERL_UNUSED_ARG(rx);
PERL_UNUSED_ARG(paren);
PERL_UNUSED_ARG(value);
if (!PL_localizing)
Perl_croak(aTHX_ "%s", PL_no_modify);
}
I32
Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
const I32 paren)
{
struct regexp *const rx = (struct regexp *)SvANY(r);
I32 i;
I32 s1, t1;
PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
/* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
switch (paren) {
/* $` / ${^PREMATCH} */
case RX_BUFF_IDX_PREMATCH:
if (rx->offs[0].start != -1) {
i = rx->offs[0].start;
if (i > 0) {
s1 = 0;
t1 = i;
goto getlen;
}
}
return 0;
/* $' / ${^POSTMATCH} */
case RX_BUFF_IDX_POSTMATCH:
if (rx->offs[0].end != -1) {
i = rx->sublen - rx->offs[0].end;
if (i > 0) {
s1 = rx->offs[0].end;
t1 = rx->sublen;
goto getlen;
}
}
return 0;
/* $& / ${^MATCH}, $1, $2, ... */
default:
if (paren <= (I32)rx->nparens &&
(s1 = rx->offs[paren].start) != -1 &&
(t1 = rx->offs[paren].end) != -1)
{
i = t1 - s1;
goto getlen;
} else {
if (ckWARN(WARN_UNINITIALIZED))
report_uninit((const SV *)sv);
return 0;
}
}
getlen:
if (i > 0 && RXp_MATCH_UTF8(rx)) {
const char * const s = rx->subbeg + s1;
const U8 *ep;
STRLEN el;
i = t1 - s1;
if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
i = el;
}
return i;
}
SV*
Perl_reg_qr_package(pTHX_ REGEXP * const rx)
{
PERL_ARGS_ASSERT_REG_QR_PACKAGE;
PERL_UNUSED_ARG(rx);
if (0)
return NULL;
else
return newSVpvs("Regexp");
}
/* Scans the name of a named buffer from the pattern.
* If flags is REG_RSN_RETURN_NULL returns null.
* If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
* If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
* to the parsed name as looked up in the RExC_paren_names hash.
* If there is an error throws a vFAIL().. type exception.
*/
#define REG_RSN_RETURN_NULL 0
#define REG_RSN_RETURN_NAME 1
#define REG_RSN_RETURN_DATA 2
STATIC SV*
S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
{
char *name_start = RExC_parse;
PERL_ARGS_ASSERT_REG_SCAN_NAME;
if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
/* skip IDFIRST by using do...while */
if (UTF)
do {
RExC_parse += UTF8SKIP(RExC_parse);
} while (isALNUM_utf8((U8*)RExC_parse));
else
do {
RExC_parse++;
} while (isALNUM(*RExC_parse));
}
if ( flags ) {
SV* sv_name
= newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
SVs_TEMP | (UTF ? SVf_UTF8 : 0));
if ( flags == REG_RSN_RETURN_NAME)
return sv_name;
else if (flags==REG_RSN_RETURN_DATA) {
HE *he_str = NULL;
SV *sv_dat = NULL;
if ( ! sv_name ) /* should not happen*/
Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
if (RExC_paren_names)
he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat )
vFAIL("Reference to nonexistent named group");
return sv_dat;
}
else {
Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
}
/* NOT REACHED */
}
return NULL;
}
#define DEBUG_PARSE_MSG(funcname) DEBUG_PARSE_r({ \
int rem=(int)(RExC_end - RExC_parse); \
int cut; \
int num; \
int iscut=0; \
if (rem>10) { \
rem=10; \
iscut=1; \
} \
cut=10-rem; \
if (RExC_lastparse!=RExC_parse) \
PerlIO_printf(Perl_debug_log," >%.*s%-*s", \
rem, RExC_parse, \
cut + 4, \
iscut ? "..." : "<" \
); \
else \
PerlIO_printf(Perl_debug_log,"%16s",""); \
\
if (SIZE_ONLY) \
num = RExC_size + 1; \
else \
num=REG_NODE_NUM(RExC_emit); \
if (RExC_lastnum!=num) \
PerlIO_printf(Perl_debug_log,"|%4d",num); \
else \
PerlIO_printf(Perl_debug_log,"|%4s",""); \
PerlIO_printf(Perl_debug_log,"|%*s%-4s", \
(int)((depth*2)), "", \
(funcname) \
); \
RExC_lastnum=num; \
RExC_lastparse=RExC_parse; \
})
#define DEBUG_PARSE(funcname) DEBUG_PARSE_r({ \
DEBUG_PARSE_MSG((funcname)); \
PerlIO_printf(Perl_debug_log,"%4s","\n"); \
})
#define DEBUG_PARSE_FMT(funcname,fmt,args) DEBUG_PARSE_r({ \
DEBUG_PARSE_MSG((funcname)); \
PerlIO_printf(Perl_debug_log,fmt "\n",args); \
})
/*
- reg - regular expression, i.e. main body or parenthesized thing
*
* Caller must absorb opening parenthesis.
*
* Combining parenthesis handling with the base level of regular expression
* is a trifle forced, but the need to tie the tails of the branches to what
* follows makes it hard to avoid.
*/
#define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
#ifdef DEBUGGING
#define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
#else
#define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
#endif
STATIC regnode *
S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
/* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
{
dVAR;
register regnode *ret; /* Will be the head of the group. */
register regnode *br;
register regnode *lastbr;
register regnode *ender = NULL;
register I32 parno = 0;
I32 flags;
U32 oregflags = RExC_flags;
bool have_branch = 0;
bool is_open = 0;
I32 freeze_paren = 0;
I32 after_freeze = 0;
/* for (?g), (?gc), and (?o) warnings; warning
about (?c) will warn about (?g) -- japhy */
#define WASTED_O 0x01
#define WASTED_G 0x02
#define WASTED_C 0x04
#define WASTED_GC (0x02|0x04)
I32 wastedflags = 0x00;
char * parse_start = RExC_parse; /* MJD */
char * const oregcomp_parse = RExC_parse;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG;
DEBUG_PARSE("reg ");
*flagp = 0; /* Tentatively. */
/* Make an OPEN node, if parenthesized. */
if (paren) {
if ( *RExC_parse == '*') { /* (*VERB:ARG) */
char *start_verb = RExC_parse;
STRLEN verb_len = 0;
char *start_arg = NULL;
unsigned char op = 0;
int argok = 1;
int internal_argval = 0; /* internal_argval is only useful if !argok */
while ( *RExC_parse && *RExC_parse != ')' ) {
if ( *RExC_parse == ':' ) {
start_arg = RExC_parse + 1;
break;
}
RExC_parse++;
}
++start_verb;
verb_len = RExC_parse - start_verb;
if ( start_arg ) {
RExC_parse++;
while ( *RExC_parse && *RExC_parse != ')' )
RExC_parse++;
if ( *RExC_parse != ')' )
vFAIL("Unterminated verb pattern argument");
if ( RExC_parse == start_arg )
start_arg = NULL;
} else {
if ( *RExC_parse != ')' )
vFAIL("Unterminated verb pattern");
}
switch ( *start_verb ) {
case 'A': /* (*ACCEPT) */
if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
op = ACCEPT;
internal_argval = RExC_nestroot;
}
break;
case 'C': /* (*COMMIT) */
if ( memEQs(start_verb,verb_len,"COMMIT") )
op = COMMIT;
break;
case 'F': /* (*FAIL) */
if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
op = OPFAIL;
argok = 0;
}
break;
case ':': /* (*:NAME) */
case 'M': /* (*MARK:NAME) */
if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
op = MARKPOINT;
argok = -1;
}
break;
case 'P': /* (*PRUNE) */
if ( memEQs(start_verb,verb_len,"PRUNE") )
op = PRUNE;
break;
case 'S': /* (*SKIP) */
if ( memEQs(start_verb,verb_len,"SKIP") )
op = SKIP;
break;
case 'T': /* (*THEN) */
/* [19:06] <TimToady> :: is then */
if ( memEQs(start_verb,verb_len,"THEN") ) {
op = CUTGROUP;
RExC_seen |= REG_SEEN_CUTGROUP;
}
break;
}
if ( ! op ) {
RExC_parse++;
vFAIL3("Unknown verb pattern '%.*s'",
verb_len, start_verb);
}
if ( argok ) {
if ( start_arg && internal_argval ) {
vFAIL3("Verb pattern '%.*s' may not have an argument",
verb_len, start_verb);
} else if ( argok < 0 && !start_arg ) {
vFAIL3("Verb pattern '%.*s' has a mandatory argument",
verb_len, start_verb);
} else {
ret = reganode(pRExC_state, op, internal_argval);
if ( ! internal_argval && ! SIZE_ONLY ) {
if (start_arg) {
SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
ARG(ret) = add_data( pRExC_state, 1, "S" );
RExC_rxi->data->data[ARG(ret)]=(void*)sv;
ret->flags = 0;
} else {
ret->flags = 1;
}
}
}
if (!internal_argval)
RExC_seen |= REG_SEEN_VERBARG;
} else if ( start_arg ) {
vFAIL3("Verb pattern '%.*s' may not have an argument",
verb_len, start_verb);
} else {
ret = reg_node(pRExC_state, op);
}
nextchar(pRExC_state);
return ret;
} else
if (*RExC_parse == '?') { /* (?...) */
bool is_logical = 0;
const char * const seqstart = RExC_parse;
RExC_parse++;
paren = *RExC_parse++;
ret = NULL; /* For look-ahead/behind. */
switch (paren) {
case 'P': /* (?P...) variants for those used to PCRE/Python */
paren = *RExC_parse++;
if ( paren == '<') /* (?P<...>) named capture */
goto named_capture;
else if (paren == '>') { /* (?P>name) named recursion */
goto named_recursion;
}
else if (paren == '=') { /* (?P=...) named backref */
/* this pretty much dupes the code for \k<NAME> in regatom(), if
you change this make sure you change that */
char* name_start = RExC_parse;
U32 num = 0;
SV *sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
if (RExC_parse == name_start || *RExC_parse != ')')
vFAIL2("Sequence %.3s... not terminated",parse_start);
if (!SIZE_ONLY) {
num = add_data( pRExC_state, 1, "S" );
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void(sv_dat);
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
(U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
num);
*flagp |= HASWIDTH;
Set_Node_Offset(ret, parse_start+1);
Set_Node_Cur_Length(ret); /* MJD */
nextchar(pRExC_state);
return ret;
}
RExC_parse++;
vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
/*NOTREACHED*/
case '<': /* (?<...) */
if (*RExC_parse == '!')
paren = ',';
else if (*RExC_parse != '=')
named_capture:
{ /* (?<...>) */
char *name_start;
SV *svname;
paren= '>';
case '\'': /* (?'...') */
name_start= RExC_parse;
svname = reg_scan_name(pRExC_state,
SIZE_ONLY ? /* reverse test from the others */
REG_RSN_RETURN_NAME :
REG_RSN_RETURN_NULL);
if (RExC_parse == name_start) {
RExC_parse++;
vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
/*NOTREACHED*/
}
if (*RExC_parse != paren)
vFAIL2("Sequence (?%c... not terminated",
paren=='>' ? '<' : paren);
if (SIZE_ONLY) {
HE *he_str;
SV *sv_dat = NULL;
if (!svname) /* shouldnt happen */
Perl_croak(aTHX_
"panic: reg_scan_name returned NULL");
if (!RExC_paren_names) {
RExC_paren_names= newHV();
sv_2mortal(MUTABLE_SV(RExC_paren_names));
#ifdef DEBUGGING
RExC_paren_name_list= newAV();
sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
#endif
}
he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
if ( he_str )
sv_dat = HeVAL(he_str);
if ( ! sv_dat ) {
/* croak baby croak */
Perl_croak(aTHX_
"panic: paren_name hash element allocation failed");
} else if ( SvPOK(sv_dat) ) {
/* (?|...) can mean we have dupes so scan to check
its already been stored. Maybe a flag indicating
we are inside such a construct would be useful,
but the arrays are likely to be quite small, so
for now we punt -- dmq */
IV count = SvIV(sv_dat);
I32 *pv = (I32*)SvPVX(sv_dat);
IV i;
for ( i = 0 ; i < count ; i++ ) {
if ( pv[i] == RExC_npar ) {
count = 0;
break;
}
}
if ( count ) {
pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
pv[count] = RExC_npar;
SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
}
} else {
(void)SvUPGRADE(sv_dat,SVt_PVNV);
sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
SvIOK_on(sv_dat);
SvIV_set(sv_dat, 1);
}
#ifdef DEBUGGING
if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
SvREFCNT_dec(svname);
#endif
/*sv_dump(sv_dat);*/
}
nextchar(pRExC_state);
paren = 1;
goto capturing_parens;
}
RExC_seen |= REG_SEEN_LOOKBEHIND;
RExC_parse++;
case '=': /* (?=...) */
RExC_seen_zerolen++;
break;
case '!': /* (?!...) */
RExC_seen_zerolen++;
if (*RExC_parse == ')') {
ret=reg_node(pRExC_state, OPFAIL);
nextchar(pRExC_state);
return ret;
}
break;
case '|': /* (?|...) */
/* branch reset, behave like a (?:...) except that
buffers in alternations share the same numbers */
paren = ':';
after_freeze = freeze_paren = RExC_npar;
break;
case ':': /* (?:...) */
case '>': /* (?>...) */
break;
case '$': /* (?$...) */
case '@': /* (?@...) */
vFAIL2("Sequence (?%c...) not implemented", (int)paren);
break;
case '#': /* (?#...) */
while (*RExC_parse && *RExC_parse != ')')
RExC_parse++;
if (*RExC_parse != ')')
FAIL("Sequence (?#... not terminated");
nextchar(pRExC_state);
*flagp = TRYAGAIN;
return NULL;
case '0' : /* (?0) */
case 'R' : /* (?R) */
if (*RExC_parse != ')')
FAIL("Sequence (?R) not terminated");
ret = reg_node(pRExC_state, GOSTART);
*flagp |= POSTPONED;
nextchar(pRExC_state);
return ret;
/*notreached*/
{ /* named and numeric backreferences */
I32 num;
case '&': /* (?&NAME) */
parse_start = RExC_parse - 1;
named_recursion:
{
SV *sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
}
goto gen_recurse_regop;
/* NOT REACHED */
case '+':
if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
RExC_parse++;
vFAIL("Illegal pattern");
}
goto parse_recursion;
/* NOT REACHED*/
case '-': /* (?-1) */
if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
RExC_parse--; /* rewind to let it be handled later */
goto parse_flags;
}
/*FALLTHROUGH */
case '1': case '2': case '3': case '4': /* (?1) */
case '5': case '6': case '7': case '8': case '9':
RExC_parse--;
parse_recursion:
num = atoi(RExC_parse);
parse_start = RExC_parse - 1; /* MJD */
if (*RExC_parse == '-')
RExC_parse++;
while (isDIGIT(*RExC_parse))
RExC_parse++;
if (*RExC_parse!=')')
vFAIL("Expecting close bracket");
gen_recurse_regop:
if ( paren == '-' ) {
/*
Diagram of capture buffer numbering.
Top line is the normal capture buffer numbers
Botton line is the negative indexing as from
the X (the (?-2))
+ 1 2 3 4 5 X 6 7
/(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
- 5 4 3 2 1 X x x
*/
num = RExC_npar + num;
if (num < 1) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
} else if ( paren == '+' ) {
num = RExC_npar + num - 1;
}
ret = reganode(pRExC_state, GOSUB, num);
if (!SIZE_ONLY) {
if (num > (I32)RExC_rx->nparens) {
RExC_parse++;
vFAIL("Reference to nonexistent group");
}
ARG2L_SET( ret, RExC_recurse_count++);
RExC_emit++;
DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
"Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
} else {
RExC_size++;
}
RExC_seen |= REG_SEEN_RECURSE;
Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
Set_Node_Offset(ret, parse_start); /* MJD */
*flagp |= POSTPONED;
nextchar(pRExC_state);
return ret;
} /* named and numeric backreferences */
/* NOT REACHED */
case '?': /* (??...) */
is_logical = 1;
if (*RExC_parse != '{') {
RExC_parse++;
vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
/*NOTREACHED*/
}
*flagp |= POSTPONED;
paren = *RExC_parse++;
/* FALL THROUGH */
case '{': /* (?{...}) */
{
I32 count = 1;
U32 n = 0;
char c;
char *s = RExC_parse;
RExC_seen_zerolen++;
RExC_seen |= REG_SEEN_EVAL;
while (count && (c = *RExC_parse)) {
if (c == '\\') {
if (RExC_parse[1])
RExC_parse++;
}
else if (c == '{')
count++;
else if (c == '}')
count--;
RExC_parse++;
}
if (*RExC_parse != ')') {
RExC_parse = s;
vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
}
if (!SIZE_ONLY) {
PAD *pad;
OP_4tree *sop, *rop;
SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
ENTER;
Perl_save_re_context(aTHX);
rop = sv_compile_2op(sv, &sop, "re", &pad);
sop->op_private |= OPpREFCOUNTED;
/* re_dup will OpREFCNT_inc */
OpREFCNT_set(sop, 1);
LEAVE;
n = add_data(pRExC_state, 3, "nop");
RExC_rxi->data->data[n] = (void*)rop;
RExC_rxi->data->data[n+1] = (void*)sop;
RExC_rxi->data->data[n+2] = (void*)pad;
SvREFCNT_dec(sv);
}
else { /* First pass */
if (PL_reginterp_cnt < ++RExC_seen_evals
&& IN_PERL_RUNTIME)
/* No compiled RE interpolated, has runtime
components ===> unsafe. */
FAIL("Eval-group not allowed at runtime, use re 'eval'");
if (PL_tainting && PL_tainted)
FAIL("Eval-group in insecure regular expression");
#if PERL_VERSION > 8
if (IN_PERL_COMPILETIME)
PL_cv_has_eval = 1;
#endif
}
nextchar(pRExC_state);
if (is_logical) {
ret = reg_node(pRExC_state, LOGICAL);
if (!SIZE_ONLY)
ret->flags = 2;
REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
/* deal with the length of this later - MJD */
return ret;
}
ret = reganode(pRExC_state, EVAL, n);
Set_Node_Length(ret, RExC_parse - parse_start + 1);
Set_Node_Offset(ret, parse_start);
return ret;
}
case '(': /* (?(?{...})...) and (?(?=...)...) */
{
int is_define= 0;
if (RExC_parse[0] == '?') { /* (?(?...)) */
if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
|| RExC_parse[1] == '<'
|| RExC_parse[1] == '{') { /* Lookahead or eval. */
I32 flag;
ret = reg_node(pRExC_state, LOGICAL);
if (!SIZE_ONLY)
ret->flags = 1;
REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
goto insert_if;
}
}
else if ( RExC_parse[0] == '<' /* (?(<NAME>)...) */
|| RExC_parse[0] == '\'' ) /* (?('NAME')...) */
{
char ch = RExC_parse[0] == '<' ? '>' : '\'';
char *name_start= RExC_parse++;
U32 num = 0;
SV *sv_dat=reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
if (RExC_parse == name_start || *RExC_parse != ch)
vFAIL2("Sequence (?(%c... not terminated",
(ch == '>' ? '<' : ch));
RExC_parse++;
if (!SIZE_ONLY) {
num = add_data( pRExC_state, 1, "S" );
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void(sv_dat);
}
ret = reganode(pRExC_state,NGROUPP,num);
goto insert_if_check_paren;
}
else if (RExC_parse[0] == 'D' &&
RExC_parse[1] == 'E' &&
RExC_parse[2] == 'F' &&
RExC_parse[3] == 'I' &&
RExC_parse[4] == 'N' &&
RExC_parse[5] == 'E')
{
ret = reganode(pRExC_state,DEFINEP,0);
RExC_parse +=6 ;
is_define = 1;
goto insert_if_check_paren;
}
else if (RExC_parse[0] == 'R') {
RExC_parse++;
parno = 0;
if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
parno = atoi(RExC_parse++);
while (isDIGIT(*RExC_parse))
RExC_parse++;
} else if (RExC_parse[0] == '&') {
SV *sv_dat;
RExC_parse++;
sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
}
ret = reganode(pRExC_state,INSUBP,parno);
goto insert_if_check_paren;
}
else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
/* (?(1)...) */
char c;
parno = atoi(RExC_parse++);
while (isDIGIT(*RExC_parse))
RExC_parse++;
ret = reganode(pRExC_state, GROUPP, parno);
insert_if_check_paren:
if ((c = *nextchar(pRExC_state)) != ')')
vFAIL("Switch condition not recognized");
insert_if:
REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
br = regbranch(pRExC_state, &flags, 1,depth+1);
if (br == NULL)
br = reganode(pRExC_state, LONGJMP, 0);
else
REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
c = *nextchar(pRExC_state);
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
if (c == '|') {
if (is_define)
vFAIL("(?(DEFINE)....) does not allow branches");
lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
regbranch(pRExC_state, &flags, 1,depth+1);
REGTAIL(pRExC_state, ret, lastbr);
if (flags&HASWIDTH)
*flagp |= HASWIDTH;
c = *nextchar(pRExC_state);
}
else
lastbr = NULL;
if (c != ')')
vFAIL("Switch (?(condition)... contains too many branches");
ender = reg_node(pRExC_state, TAIL);
REGTAIL(pRExC_state, br, ender);
if (lastbr) {
REGTAIL(pRExC_state, lastbr, ender);
REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
}
else
REGTAIL(pRExC_state, ret, ender);
RExC_size++; /* XXX WHY do we need this?!!
For large programs it seems to be required
but I can't figure out why. -- dmq*/
return ret;
}
else {
vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
}
}
case 0:
RExC_parse--; /* for vFAIL to print correctly */
vFAIL("Sequence (? incomplete");
break;
default:
--RExC_parse;
parse_flags: /* (?i) */
{
U32 posflags = 0, negflags = 0;
U32 *flagsp = &posflags;
while (*RExC_parse) {
/* && strchr("iogcmsx", *RExC_parse) */
/* (?g), (?gc) and (?o) are useless here
and must be globally applied -- japhy */
switch (*RExC_parse) {
CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
case ONCE_PAT_MOD: /* 'o' */
case GLOBAL_PAT_MOD: /* 'g' */
if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
if (! (wastedflags & wflagbit) ) {
wastedflags |= wflagbit;
vWARN5(
RExC_parse + 1,
"Useless (%s%c) - %suse /%c modifier",
flagsp == &negflags ? "?-" : "?",
*RExC_parse,
flagsp == &negflags ? "don't " : "",
*RExC_parse
);
}
}
break;
case CONTINUE_PAT_MOD: /* 'c' */
if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
if (! (wastedflags & WASTED_C) ) {
wastedflags |= WASTED_GC;
vWARN3(
RExC_parse + 1,
"Useless (%sc) - %suse /gc modifier",
flagsp == &negflags ? "?-" : "?",
flagsp == &negflags ? "don't " : ""
);
}
}
break;
case KEEPCOPY_PAT_MOD: /* 'p' */
if (flagsp == &negflags) {
if (SIZE_ONLY)
ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
} else {
*flagsp |= RXf_PMf_KEEPCOPY;
}
break;
case '-':
if (flagsp == &negflags) {
RExC_parse++;
vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
/*NOTREACHED*/
}
flagsp = &negflags;
wastedflags = 0; /* reset so (?g-c) warns twice */
break;
case ':':
paren = ':';
/*FALLTHROUGH*/
case ')':
RExC_flags |= posflags;
RExC_flags &= ~negflags;
if (paren != ':') {
oregflags |= posflags;
oregflags &= ~negflags;
}
nextchar(pRExC_state);
if (paren != ':') {
*flagp = TRYAGAIN;
return NULL;
} else {
ret = NULL;
goto parse_rest;
}
/*NOTREACHED*/
default:
RExC_parse++;
vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
/*NOTREACHED*/
}
++RExC_parse;
}
}} /* one for the default block, one for the switch */
}
else { /* (...) */
capturing_parens:
parno = RExC_npar;
RExC_npar++;
ret = reganode(pRExC_state, OPEN, parno);
if (!SIZE_ONLY ){
if (!RExC_nestroot)
RExC_nestroot = parno;
if (RExC_seen & REG_SEEN_RECURSE
&& !RExC_open_parens[parno-1])
{
DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
"Setting open paren #%"IVdf" to %d\n",
(IV)parno, REG_NODE_NUM(ret)));
RExC_open_parens[parno-1]= ret;
}
}
Set_Node_Length(ret, 1); /* MJD */
Set_Node_Offset(ret, RExC_parse); /* MJD */
is_open = 1;
}
}
else /* ! paren */
ret = NULL;
parse_rest:
/* Pick up the branches, linking them together. */
parse_start = RExC_parse; /* MJD */
br = regbranch(pRExC_state, &flags, 1,depth+1);
if (freeze_paren) {
if (RExC_npar > after_freeze)
after_freeze = RExC_npar;
RExC_npar = freeze_paren;
}
/* branch_len = (paren != 0); */
if (br == NULL)
return(NULL);
if (*RExC_parse == '|') {
if (!SIZE_ONLY && RExC_extralen) {
reginsert(pRExC_state, BRANCHJ, br, depth+1);
}
else { /* MJD */
reginsert(pRExC_state, BRANCH, br, depth+1);
Set_Node_Length(br, paren != 0);
Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
}
have_branch = 1;
if (SIZE_ONLY)
RExC_extralen += 1; /* For BRANCHJ-BRANCH. */
}
else if (paren == ':') {
*flagp |= flags&SIMPLE;
}
if (is_open) { /* Starts with OPEN. */
REGTAIL(pRExC_state, ret, br); /* OPEN -> first. */
}
else if (paren != '?') /* Not Conditional */
ret = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
lastbr = br;
while (*RExC_parse == '|') {
if (!SIZE_ONLY && RExC_extralen) {
ender = reganode(pRExC_state, LONGJMP,0);
REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
}
if (SIZE_ONLY)
RExC_extralen += 2; /* Account for LONGJMP. */
nextchar(pRExC_state);
if (freeze_paren) {
if (RExC_npar > after_freeze)
after_freeze = RExC_npar;
RExC_npar = freeze_paren;
}
br = regbranch(pRExC_state, &flags, 0, depth+1);
if (br == NULL)
return(NULL);
REGTAIL(pRExC_state, lastbr, br); /* BRANCH -> BRANCH. */
lastbr = br;
*flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
}
if (have_branch || paren != ':') {
/* Make a closing node, and hook it on the end. */
switch (paren) {
case ':':
ender = reg_node(pRExC_state, TAIL);
break;
case 1:
ender = reganode(pRExC_state, CLOSE, parno);
if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
"Setting close paren #%"IVdf" to %d\n",
(IV)parno, REG_NODE_NUM(ender)));
RExC_close_parens[parno-1]= ender;
if (RExC_nestroot == parno)
RExC_nestroot = 0;
}
Set_Node_Offset(ender,RExC_parse+1); /* MJD */
Set_Node_Length(ender,1); /* MJD */
break;
case '<':
case ',':
case '=':
case '!':
*flagp &= ~HASWIDTH;
/* FALL THROUGH */
case '>':
ender = reg_node(pRExC_state, SUCCEED);
break;
case 0:
ender = reg_node(pRExC_state, END);
if (!SIZE_ONLY) {
assert(!RExC_opend); /* there can only be one! */
RExC_opend = ender;
}
break;
}
REGTAIL(pRExC_state, lastbr, ender);
if (have_branch && !SIZE_ONLY) {
if (depth==1)
RExC_seen |= REG_TOP_LEVEL_BRANCHES;
/* Hook the tails of the branches to the closing node. */
for (br = ret; br; br = regnext(br)) {
const U8 op = PL_regkind[OP(br)];
if (op == BRANCH) {
REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
}
else if (op == BRANCHJ) {
REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
}
}
}
}
{
const char *p;
static const char parens[] = "=!<,>";
if (paren && (p = strchr(parens, paren))) {
U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
int flag = (p - parens) > 1;
if (paren == '>')
node = SUSPEND, flag = 0;
reginsert(pRExC_state, node,ret, depth+1);
Set_Node_Cur_Length(ret);
Set_Node_Offset(ret, parse_start + 1);
ret->flags = flag;
REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
}
}
/* Check for proper termination. */
if (paren) {
RExC_flags = oregflags;
if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched (");
}
}
else if (!paren && RExC_parse < RExC_end) {
if (*RExC_parse == ')') {
RExC_parse++;
vFAIL("Unmatched )");
}
else
FAIL("Junk on end of regexp"); /* "Can't happen". */
/* NOTREACHED */
}
if (after_freeze)
RExC_npar = after_freeze;
return(ret);
}
/*
- regbranch - one alternative of an | operator
*
* Implements the concatenation operator.
*/
STATIC regnode *
S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
{
dVAR;
register regnode *ret;
register regnode *chain = NULL;
register regnode *latest;
I32 flags = 0, c = 0;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGBRANCH;
DEBUG_PARSE("brnc");
if (first)
ret = NULL;
else {
if (!SIZE_ONLY && RExC_extralen)
ret = reganode(pRExC_state, BRANCHJ,0);
else {
ret = reg_node(pRExC_state, BRANCH);
Set_Node_Length(ret, 1);
}
}
if (!first && SIZE_ONLY)
RExC_extralen += 1; /* BRANCHJ */
*flagp = WORST; /* Tentatively. */
RExC_parse--;
nextchar(pRExC_state);
while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
flags &= ~TRYAGAIN;
latest = regpiece(pRExC_state, &flags,depth+1);
if (latest == NULL) {
if (flags & TRYAGAIN)
continue;
return(NULL);
}
else if (ret == NULL)
ret = latest;
*flagp |= flags&(HASWIDTH|POSTPONED);
if (chain == NULL) /* First piece. */
*flagp |= flags&SPSTART;
else {
RExC_naughty++;
REGTAIL(pRExC_state, chain, latest);
}
chain = latest;
c++;
}
if (chain == NULL) { /* Loop ran zero times. */
chain = reg_node(pRExC_state, NOTHING);
if (ret == NULL)
ret = chain;
}
if (c == 1) {
*flagp |= flags&SIMPLE;
}
return ret;
}
/*
- regpiece - something followed by possible [*+?]
*
* Note that the branching code sequences used for ? and the general cases
* of * and + are somewhat optimized: they use the same NOTHING node as
* both the endmarker for their branch list and the body of the last branch.
* It might seem that this node could be dispensed with entirely, but the
* endmarker role is not redundant.
*/
STATIC regnode *
S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
dVAR;
register regnode *ret;
register char op;
register char *next;
I32 flags;
const char * const origparse = RExC_parse;
I32 min;
I32 max = REG_INFTY;
char *parse_start;
const char *maxpos = NULL;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPIECE;
DEBUG_PARSE("piec");
ret = regatom(pRExC_state, &flags,depth+1);
if (ret == NULL) {
if (flags & TRYAGAIN)
*flagp |= TRYAGAIN;
return(NULL);
}
op = *RExC_parse;
if (op == '{' && regcurly(RExC_parse)) {
maxpos = NULL;
parse_start = RExC_parse; /* MJD */
next = RExC_parse + 1;
while (isDIGIT(*next) || *next == ',') {
if (*next == ',') {
if (maxpos)
break;
else
maxpos = next;
}
next++;
}
if (*next == '}') { /* got one */
if (!maxpos)
maxpos = next;
RExC_parse++;
min = atoi(RExC_parse);
if (*maxpos == ',')
maxpos++;
else
maxpos = RExC_parse;
max = atoi(maxpos);
if (!max && *maxpos != '0')
max = REG_INFTY; /* meaning "infinity" */
else if (max >= REG_INFTY)
vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
RExC_parse = next;
nextchar(pRExC_state);
do_curly:
if ((flags&SIMPLE)) {
RExC_naughty += 2 + RExC_naughty / 2;
reginsert(pRExC_state, CURLY, ret, depth+1);
Set_Node_Offset(ret, parse_start+1); /* MJD */
Set_Node_Cur_Length(ret);
}
else {
regnode * const w = reg_node(pRExC_state, WHILEM);
w->flags = 0;
REGTAIL(pRExC_state, ret, w);
if (!SIZE_ONLY && RExC_extralen) {
reginsert(pRExC_state, LONGJMP,ret, depth+1);
reginsert(pRExC_state, NOTHING,ret, depth+1);
NEXT_OFF(ret) = 3; /* Go over LONGJMP. */
}
reginsert(pRExC_state, CURLYX,ret, depth+1);
/* MJD hk */
Set_Node_Offset(ret, parse_start+1);
Set_Node_Length(ret,
op == '{' ? (RExC_parse - parse_start) : 1);
if (!SIZE_ONLY && RExC_extralen)
NEXT_OFF(ret) = 3; /* Go over NOTHING to LONGJMP. */
REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
if (SIZE_ONLY)
RExC_whilem_seen++, RExC_extralen += 3;
RExC_naughty += 4 + RExC_naughty; /* compound interest */
}
ret->flags = 0;
if (min > 0)
*flagp = WORST;
if (max > 0)
*flagp |= HASWIDTH;
if (max < min)
vFAIL("Can't do {n,m} with n > m");
if (!SIZE_ONLY) {
ARG1_SET(ret, (U16)min);
ARG2_SET(ret, (U16)max);
}
goto nest_check;
}
}
if (!ISMULT1(op)) {
*flagp = flags;
return(ret);
}
#if 0 /* Now runtime fix should be reliable. */
/* if this is reinstated, don't forget to put this back into perldiag:
=item Regexp *+ operand could be empty at {#} in regex m/%s/
(F) The part of the regexp subject to either the * or + quantifier
could match an empty string. The {#} shows in the regular
expression about where the problem was discovered.
*/
if (!(flags&HASWIDTH) && op != '?')
vFAIL("Regexp *+ operand could be empty");
#endif
parse_start = RExC_parse;
nextchar(pRExC_state);
*flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
if (op == '*' && (flags&SIMPLE)) {
reginsert(pRExC_state, STAR, ret, depth+1);
ret->flags = 0;
RExC_naughty += 4;
}
else if (op == '*') {
min = 0;
goto do_curly;
}
else if (op == '+' && (flags&SIMPLE)) {
reginsert(pRExC_state, PLUS, ret, depth+1);
ret->flags = 0;
RExC_naughty += 3;
}
else if (op == '+') {
min = 1;
goto do_curly;
}
else if (op == '?') {
min = 0; max = 1;
goto do_curly;
}
nest_check:
if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
ckWARN3reg(RExC_parse,
"%.*s matches null string many times",
(int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
origparse);
}
if (RExC_parse < RExC_end && *RExC_parse == '?') {
nextchar(pRExC_state);
reginsert(pRExC_state, MINMOD, ret, depth+1);
REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
}
#ifndef REG_ALLOW_MINMOD_SUSPEND
else
#endif
if (RExC_parse < RExC_end && *RExC_parse == '+') {
regnode *ender;
nextchar(pRExC_state);
ender = reg_node(pRExC_state, SUCCEED);
REGTAIL(pRExC_state, ret, ender);
reginsert(pRExC_state, SUSPEND, ret, depth+1);
ret->flags = 0;
ender = reg_node(pRExC_state, TAIL);
REGTAIL(pRExC_state, ret, ender);
/*ret= ender;*/
}
if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
RExC_parse++;
vFAIL("Nested quantifiers");
}
return(ret);
}
/* reg_namedseq(pRExC_state,UVp)
This is expected to be called by a parser routine that has
recognized '\N' and needs to handle the rest. RExC_parse is
expected to point at the first char following the N at the time
of the call.
The \N may be inside (indicated by valuep not being NULL) or outside a
character class.
\N may begin either a named sequence, or if outside a character class, mean
to match a non-newline. For non single-quoted regexes, the tokenizer has
attempted to decide which, and in the case of a named sequence converted it
into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
where c1... are the characters in the sequence. For single-quoted regexes,
the tokenizer passes the \N sequence through unchanged; this code will not
attempt to determine this nor expand those. The net effect is that if the
beginning of the passed-in pattern isn't '{U+' or there is no '}', it
signals that this \N occurrence means to match a non-newline.
Only the \N{U+...} form should occur in a character class, for the same
reason that '.' inside a character class means to just match a period: it
just doesn't make sense.
If valuep is non-null then it is assumed that we are parsing inside
of a charclass definition and the first codepoint in the resolved
string is returned via *valuep and the routine will return NULL.
In this mode if a multichar string is returned from the charnames
handler, a warning will be issued, and only the first char in the
sequence will be examined. If the string returned is zero length
then the value of *valuep is undefined and NON-NULL will
be returned to indicate failure. (This will NOT be a valid pointer
to a regnode.)
If valuep is null then it is assumed that we are parsing normal text and a
new EXACT node is inserted into the program containing the resolved string,
and a pointer to the new node is returned. But if the string is zero length
a NOTHING node is emitted instead.
On success RExC_parse is set to the char following the endbrace.
Parsing failures will generate a fatal error via vFAIL(...)
*/
STATIC regnode *
S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep, I32 *flagp)
{
char * endbrace; /* '}' following the name */
regnode *ret = NULL;
#ifdef DEBUGGING
char* parse_start = RExC_parse - 2; /* points to the '\N' */
#endif
char* p;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG_NAMEDSEQ;
GET_RE_DEBUG_FLAGS;
/* The [^\n] meaning of \N ignores spaces and comments under the /x
* modifier. The other meaning does not */
p = (RExC_flags & RXf_PMf_EXTENDED)
? regwhite( pRExC_state, RExC_parse )
: RExC_parse;
/* Disambiguate between \N meaning a named character versus \N meaning
* [^\n]. The former is assumed when it can't be the latter. */
if (*p != '{' || regcurly(p)) {
RExC_parse = p;
if (valuep) {
/* no bare \N in a charclass */
vFAIL("\\N in a character class must be a named character: \\N{...}");
}
nextchar(pRExC_state);
ret = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
RExC_naughty++;
RExC_parse--;
Set_Node_Length(ret, 1); /* MJD */
return ret;
}
/* Here, we have decided it should be a named sequence */
/* The test above made sure that the next real character is a '{', but
* under the /x modifier, it could be separated by space (or a comment and
* \n) and this is not allowed (for consistency with \x{...} and the
* tokenizer handling of \N{NAME}). */
if (*RExC_parse != '{') {
vFAIL("Missing braces on \\N{}");
}
RExC_parse++; /* Skip past the '{' */
if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
|| ! (endbrace == RExC_parse /* nothing between the {} */
|| (endbrace - RExC_parse >= 2 /* U+ (bad hex is checked below */
&& strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
{
if (endbrace) RExC_parse = endbrace; /* position msg's '<--HERE' */
vFAIL("\\N{NAME} must be resolved by the lexer");
}
if (endbrace == RExC_parse) { /* empty: \N{} */
if (! valuep) {
RExC_parse = endbrace + 1;
return reg_node(pRExC_state,NOTHING);
}
if (SIZE_ONLY) {
ckWARNreg(RExC_parse,
"Ignoring zero length \\N{} in character class"
);
RExC_parse = endbrace + 1;
}
*valuep = 0;
return (regnode *) &RExC_parse; /* Invalid regnode pointer */
}
RExC_utf8 = 1; /* named sequences imply Unicode semantics */
RExC_parse += 2; /* Skip past the 'U+' */
if (valuep) { /* In a bracketed char class */
/* We only pay attention to the first char of
multichar strings being returned. I kinda wonder
if this makes sense as it does change the behaviour
from earlier versions, OTOH that behaviour was broken
as well. XXX Solution is to recharacterize as
[rest-of-class]|multi1|multi2... */
STRLEN length_of_hex;
I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX
| (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
char * endchar = RExC_parse + strcspn(RExC_parse, ".}");
if (endchar < endbrace) {
ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
}
length_of_hex = (STRLEN)(endchar - RExC_parse);
*valuep = grok_hex(RExC_parse, &length_of_hex, &flags, NULL);
/* The tokenizer should have guaranteed validity, but it's possible to
* bypass it by using single quoting, so check */
if (length_of_hex == 0
|| length_of_hex != (STRLEN)(endchar - RExC_parse) )
{
RExC_parse += length_of_hex; /* Includes all the valid */
RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
? UTF8SKIP(RExC_parse)
: 1;
/* Guard against malformed utf8 */
if (RExC_parse >= endchar) RExC_parse = endchar;
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
RExC_parse = endbrace + 1;
if (endchar == endbrace) return NULL;
ret = (regnode *) &RExC_parse; /* Invalid regnode pointer */
}
else { /* Not a char class */
char *s; /* String to put in generated EXACT node */
STRLEN len = 0; /* Its current length */
char *endchar; /* Points to '.' or '}' ending cur char in the input
stream */
ret = reg_node(pRExC_state,
(U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
s= STRING(ret);
/* Exact nodes can hold only a U8 length's of text = 255. Loop through
* the input which is of the form now 'c1.c2.c3...}' until find the
* ending brace or exeed length 255. The characters that exceed this
* limit are dropped. The limit could be relaxed should it become
* desirable by reparsing this as (?:\N{NAME}), so could generate
* multiple EXACT nodes, as is done for just regular input. But this
* is primarily a named character, and not intended to be a huge long
* string, so 255 bytes should be good enough */
while (1) {
STRLEN length_of_hex;
I32 grok_flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX
| (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
UV cp; /* Ord of current character */
/* Code points are separated by dots. If none, there is only one
* code point, and is terminated by the brace */
endchar = RExC_parse + strcspn(RExC_parse, ".}");
/* The values are Unicode even on EBCDIC machines */
length_of_hex = (STRLEN)(endchar - RExC_parse);
cp = grok_hex(RExC_parse, &length_of_hex, &grok_flags, NULL);
if ( length_of_hex == 0
|| length_of_hex != (STRLEN)(endchar - RExC_parse) )
{
RExC_parse += length_of_hex; /* Includes all the valid */
RExC_parse += (RExC_orig_utf8) /* point to after 1st invalid */
? UTF8SKIP(RExC_parse)
: 1;
/* Guard against malformed utf8 */
if (RExC_parse >= endchar) RExC_parse = endchar;
vFAIL("Invalid hexadecimal number in \\N{U+...}");
}
if (! FOLD) { /* Not folding, just append to the string */
STRLEN unilen;
/* Quit before adding this character if would exceed limit */
if (len + UNISKIP(cp) > U8_MAX) break;
unilen = reguni(pRExC_state, cp, s);
if (unilen > 0) {
s += unilen;
len += unilen;
}
} else { /* Folding, output the folded equivalent */
STRLEN foldlen,numlen;
U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
cp = toFOLD_uni(cp, tmpbuf, &foldlen);
/* Quit before exceeding size limit */
if (len + foldlen > U8_MAX) break;
for (foldbuf = tmpbuf;
foldlen;
foldlen -= numlen)
{
cp = utf8_to_uvchr(foldbuf, &numlen);
if (numlen > 0) {
const STRLEN unilen = reguni(pRExC_state, cp, s);
s += unilen;
len += unilen;
/* In EBCDIC the numlen and unilen can differ. */
foldbuf += numlen;
if (numlen >= foldlen)
break;
}
else
break; /* "Can't happen." */
}
}
/* Point to the beginning of the next character in the sequence. */
RExC_parse = endchar + 1;
/* Quit if no more characters */
if (RExC_parse >= endbrace) break;
}
if (SIZE_ONLY) {
if (RExC_parse < endbrace) {
ckWARNreg(RExC_parse - 1,
"Using just the first characters returned by \\N{}");
}
RExC_size += STR_SZ(len);
} else {
STR_LEN(ret) = len;
RExC_emit += STR_SZ(len);
}
RExC_parse = endbrace + 1;
*flagp |= HASWIDTH; /* Not SIMPLE, as that causes the engine to fail
with malformed in t/re/pat_advanced.t */
RExC_parse --;
Set_Node_Cur_Length(ret); /* MJD */
nextchar(pRExC_state);
}
return ret;
}
/*
* reg_recode
*
* It returns the code point in utf8 for the value in *encp.
* value: a code value in the source encoding
* encp: a pointer to an Encode object
*
* If the result from Encode is not a single character,
* it returns U+FFFD (Replacement character) and sets *encp to NULL.
*/
STATIC UV
S_reg_recode(pTHX_ const char value, SV **encp)
{
STRLEN numlen = 1;
SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
const STRLEN newlen = SvCUR(sv);
UV uv = UNICODE_REPLACEMENT;
PERL_ARGS_ASSERT_REG_RECODE;
if (newlen)
uv = SvUTF8(sv)
? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
: *(U8*)s;
if (!newlen || numlen != newlen) {
uv = UNICODE_REPLACEMENT;
*encp = NULL;
}
return uv;
}
/*
- regatom - the lowest level
Try to identify anything special at the start of the pattern. If there
is, then handle it as required. This may involve generating a single regop,
such as for an assertion; or it may involve recursing, such as to
handle a () structure.
If the string doesn't start with something special then we gobble up
as much literal text as we can.
Once we have been able to handle whatever type of thing started the
sequence, we return.
Note: we have to be careful with escapes, as they can be both literal
and special, and in the case of \10 and friends can either, depending
on context. Specifically there are two seperate switches for handling
escape sequences, with the one for handling literal escapes requiring
a dummy entry for all of the special escapes that are actually handled
by the other.
*/
STATIC regnode *
S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
{
dVAR;
register regnode *ret = NULL;
I32 flags;
char *parse_start = RExC_parse;
GET_RE_DEBUG_FLAGS_DECL;
DEBUG_PARSE("atom");
*flagp = WORST; /* Tentatively. */
PERL_ARGS_ASSERT_REGATOM;
tryagain:
switch ((U8)*RExC_parse) {
case '^':
RExC_seen_zerolen++;
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MBOL);
else if (RExC_flags & RXf_PMf_SINGLELINE)
ret = reg_node(pRExC_state, SBOL);
else
ret = reg_node(pRExC_state, BOL);
Set_Node_Length(ret, 1); /* MJD */
break;
case '$':
nextchar(pRExC_state);
if (*RExC_parse)
RExC_seen_zerolen++;
if (RExC_flags & RXf_PMf_MULTILINE)
ret = reg_node(pRExC_state, MEOL);
else if (RExC_flags & RXf_PMf_SINGLELINE)
ret = reg_node(pRExC_state, SEOL);
else
ret = reg_node(pRExC_state, EOL);
Set_Node_Length(ret, 1); /* MJD */
break;
case '.':
nextchar(pRExC_state);
if (RExC_flags & RXf_PMf_SINGLELINE)
ret = reg_node(pRExC_state, SANY);
else
ret = reg_node(pRExC_state, REG_ANY);
*flagp |= HASWIDTH|SIMPLE;
RExC_naughty++;
Set_Node_Length(ret, 1); /* MJD */
break;
case '[':
{
char * const oregcomp_parse = ++RExC_parse;
ret = regclass(pRExC_state,depth+1);
if (*RExC_parse != ']') {
RExC_parse = oregcomp_parse;
vFAIL("Unmatched [");
}
nextchar(pRExC_state);
*flagp |= HASWIDTH|SIMPLE;
Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
break;
}
case '(':
nextchar(pRExC_state);
ret = reg(pRExC_state, 1, &flags,depth+1);
if (ret == NULL) {
if (flags & TRYAGAIN) {
if (RExC_parse == RExC_end) {
/* Make parent create an empty node if needed. */
*flagp |= TRYAGAIN;
return(NULL);
}
goto tryagain;
}
return(NULL);
}
*flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
break;
case '|':
case ')':
if (flags & TRYAGAIN) {
*flagp |= TRYAGAIN;
return NULL;
}
vFAIL("Internal urp");
/* Supposed to be caught earlier. */
break;
case '{':
if (!regcurly(RExC_parse)) {
RExC_parse++;
goto defchar;
}
/* FALL THROUGH */
case '?':
case '+':
case '*':
RExC_parse++;
vFAIL("Quantifier follows nothing");
break;
case 0xDF:
case 0xC3:
case 0xCE:
do_foldchar:
if (!LOC && FOLD) {
U32 len,cp;
len=0; /* silence a spurious compiler warning */
if ((cp = what_len_TRICKYFOLD_safe(RExC_parse,RExC_end,UTF,len))) {
*flagp |= HASWIDTH; /* could be SIMPLE too, but needs a handler in regexec.regrepeat */
RExC_parse+=len-1; /* we get one from nextchar() as well. :-( */
ret = reganode(pRExC_state, FOLDCHAR, cp);
Set_Node_Length(ret, 1); /* MJD */
nextchar(pRExC_state); /* kill whitespace under /x */
return ret;
}
}
goto outer_default;
case '\\':
/* Special Escapes
This switch handles escape sequences that resolve to some kind
of special regop and not to literal text. Escape sequnces that
resolve to literal text are handled below in the switch marked
"Literal Escapes".
Every entry in this switch *must* have a corresponding entry
in the literal escape switch. However, the opposite is not
required, as the default for this switch is to jump to the
literal text handling code.
*/
switch ((U8)*++RExC_parse) {
case 0xDF:
case 0xC3:
case 0xCE:
goto do_foldchar;
/* Special Escapes */
case 'A':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, SBOL);
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'G':
ret = reg_node(pRExC_state, GPOS);
RExC_seen |= REG_SEEN_GPOS;
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'K':
RExC_seen_zerolen++;
ret = reg_node(pRExC_state, KEEPS);
*flagp |= SIMPLE;
/* XXX:dmq : disabling in-place substitution seems to
* be necessary here to avoid cases of memory corruption, as
* with: C<$_="x" x 80; s/x\K/y/> -- rgs
*/
RExC_seen |= REG_SEEN_LOOKBEHIND;
goto finish_meta_pat;
case 'Z':
ret = reg_node(pRExC_state, SEOL);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'z':
ret = reg_node(pRExC_state, EOS);
*flagp |= SIMPLE;
RExC_seen_zerolen++; /* Do not optimize RE away */
goto finish_meta_pat;
case 'C':
ret = reg_node(pRExC_state, CANY);
RExC_seen |= REG_SEEN_CANY;
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'X':
ret = reg_node(pRExC_state, CLUMP);
*flagp |= HASWIDTH;
goto finish_meta_pat;
case 'w':
ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML : ALNUM));
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'W':
ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML : NALNUM));
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'b':
RExC_seen_zerolen++;
RExC_seen |= REG_SEEN_LOOKBEHIND;
ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL : BOUND));
*flagp |= SIMPLE;
goto finish_meta_pat;
case 'B':
RExC_seen_zerolen++;
RExC_seen |= REG_SEEN_LOOKBEHIND;
ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL : NBOUND));
*flagp |= SIMPLE;
goto finish_meta_pat;
case 's':
ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL : SPACE));
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'S':
ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL : NSPACE));
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'd':
ret = reg_node(pRExC_state, DIGIT);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'D':
ret = reg_node(pRExC_state, NDIGIT);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'R':
ret = reg_node(pRExC_state, LNBREAK);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'h':
ret = reg_node(pRExC_state, HORIZWS);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'H':
ret = reg_node(pRExC_state, NHORIZWS);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'v':
ret = reg_node(pRExC_state, VERTWS);
*flagp |= HASWIDTH|SIMPLE;
goto finish_meta_pat;
case 'V':
ret = reg_node(pRExC_state, NVERTWS);
*flagp |= HASWIDTH|SIMPLE;
finish_meta_pat:
nextchar(pRExC_state);
Set_Node_Length(ret, 2); /* MJD */
break;
case 'p':
case 'P':
{
char* const oldregxend = RExC_end;
#ifdef DEBUGGING
char* parse_start = RExC_parse - 2;
#endif
if (RExC_parse[1] == '{') {
/* a lovely hack--pretend we saw [\pX] instead */
RExC_end = strchr(RExC_parse, '}');
if (!RExC_end) {
const U8 c = (U8)*RExC_parse;
RExC_parse += 2;
RExC_end = oldregxend;
vFAIL2("Missing right brace on \\%c{}", c);
}
RExC_end++;
}
else {
RExC_end = RExC_parse + 2;
if (RExC_end > oldregxend)
RExC_end = oldregxend;
}
RExC_parse--;
ret = regclass(pRExC_state,depth+1);
RExC_end = oldregxend;
RExC_parse--;
Set_Node_Offset(ret, parse_start + 2);
Set_Node_Cur_Length(ret);
nextchar(pRExC_state);
*flagp |= HASWIDTH|SIMPLE;
}
break;
case 'N':
/* Handle \N and \N{NAME} here and not below because it can be
multicharacter. join_exact() will join them up later on.
Also this makes sure that things like /\N{BLAH}+/ and
\N{BLAH} being multi char Just Happen. dmq*/
++RExC_parse;
ret= reg_namedseq(pRExC_state, NULL, flagp);
break;
case 'k': /* Handle \k<NAME> and \k'NAME' */
parse_named_seq:
{
char ch= RExC_parse[1];
if (ch != '<' && ch != '\'' && ch != '{') {
RExC_parse++;
vFAIL2("Sequence %.2s... not terminated",parse_start);
} else {
/* this pretty much dupes the code for (?P=...) in reg(), if
you change this make sure you change that */
char* name_start = (RExC_parse += 2);
U32 num = 0;
SV *sv_dat = reg_scan_name(pRExC_state,
SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
if (RExC_parse == name_start || *RExC_parse != ch)
vFAIL2("Sequence %.3s... not terminated",parse_start);
if (!SIZE_ONLY) {
num = add_data( pRExC_state, 1, "S" );
RExC_rxi->data->data[num]=(void*)sv_dat;
SvREFCNT_inc_simple_void(sv_dat);
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
(U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
num);
*flagp |= HASWIDTH;
/* override incorrect value set in reganode MJD */
Set_Node_Offset(ret, parse_start+1);
Set_Node_Cur_Length(ret); /* MJD */
nextchar(pRExC_state);
}
break;
}
case 'g':
case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
I32 num;
bool isg = *RExC_parse == 'g';
bool isrel = 0;
bool hasbrace = 0;
if (isg) {
RExC_parse++;
if (*RExC_parse == '{') {
RExC_parse++;
hasbrace = 1;
}
if (*RExC_parse == '-') {
RExC_parse++;
isrel = 1;
}
if (hasbrace && !isDIGIT(*RExC_parse)) {
if (isrel) RExC_parse--;
RExC_parse -= 2;
goto parse_named_seq;
} }
num = atoi(RExC_parse);
if (isg && num == 0)
vFAIL("Reference to invalid group 0");
if (isrel) {
num = RExC_npar - num;
if (num < 1)
vFAIL("Reference to nonexistent or unclosed group");
}
if (!isg && num > 9 && num >= RExC_npar)
goto defchar;
else {
char * const parse_start = RExC_parse - 1; /* MJD */
while (isDIGIT(*RExC_parse))
RExC_parse++;
if (parse_start == RExC_parse - 1)
vFAIL("Unterminated \\g... pattern");
if (hasbrace) {
if (*RExC_parse != '}')
vFAIL("Unterminated \\g{...} pattern");
RExC_parse++;
}
if (!SIZE_ONLY) {
if (num > (I32)RExC_rx->nparens)
vFAIL("Reference to nonexistent group");
}
RExC_sawback = 1;
ret = reganode(pRExC_state,
(U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
num);
*flagp |= HASWIDTH;
/* override incorrect value set in reganode MJD */
Set_Node_Offset(ret, parse_start+1);
Set_Node_Cur_Length(ret); /* MJD */
RExC_parse--;
nextchar(pRExC_state);
}
}
break;
case '\0':
if (RExC_parse >= RExC_end)
FAIL("Trailing \\");
/* FALL THROUGH */
default:
/* Do not generate "unrecognized" warnings here, we fall
back into the quick-grab loop below */
parse_start--;
goto defchar;
}
break;
case '#':
if (RExC_flags & RXf_PMf_EXTENDED) {
if ( reg_skipcomment( pRExC_state ) )
goto tryagain;
}
/* FALL THROUGH */
default:
outer_default:{
register STRLEN len;
register UV ender;
register char *p;
char *s;
STRLEN foldlen;
U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
parse_start = RExC_parse - 1;
RExC_parse++;
defchar:
ender = 0;
ret = reg_node(pRExC_state,
(U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
s = STRING(ret);
for (len = 0, p = RExC_parse - 1;
len < 127 && p < RExC_end;
len++)
{
char * const oldp = p;
if (RExC_flags & RXf_PMf_EXTENDED)
p = regwhite( pRExC_state, p );
switch ((U8)*p) {
case 0xDF:
case 0xC3:
case 0xCE:
if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
goto normal_default;
case '^':
case '$':
case '.':
case '[':
case '(':
case ')':
case '|':
goto loopdone;
case '\\':
/* Literal Escapes Switch
This switch is meant to handle escape sequences that
resolve to a literal character.
Every escape sequence that represents something
else, like an assertion or a char class, is handled
in the switch marked 'Special Escapes' above in this
routine, but also has an entry here as anything that
isn't explicitly mentioned here will be treated as
an unescaped equivalent literal.
*/
switch ((U8)*++p) {
/* These are all the special escapes. */
case 0xDF:
case 0xC3:
case 0xCE:
if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
goto normal_default;
case 'A': /* Start assertion */
case 'b': case 'B': /* Word-boundary assertion*/
case 'C': /* Single char !DANGEROUS! */
case 'd': case 'D': /* digit class */
case 'g': case 'G': /* generic-backref, pos assertion */
case 'h': case 'H': /* HORIZWS */
case 'k': case 'K': /* named backref, keep marker */
case 'N': /* named char sequence */
case 'p': case 'P': /* Unicode property */
case 'R': /* LNBREAK */
case 's': case 'S': /* space class */
case 'v': case 'V': /* VERTWS */
case 'w': case 'W': /* word class */
case 'X': /* eXtended Unicode "combining character sequence" */
case 'z': case 'Z': /* End of line/string assertion */
--p;
goto loopdone;
/* Anything after here is an escape that resolves to a
literal. (Except digits, which may or may not)
*/
case 'n':
ender = '\n';
p++;
break;
case 'r':
ender = '\r';
p++;
break;
case 't':
ender = '\t';
p++;
break;
case 'f':
ender = '\f';
p++;
break;
case 'e':
ender = ASCII_TO_NATIVE('\033');
p++;
break;
case 'a':
ender = ASCII_TO_NATIVE('\007');
p++;
break;
case 'x':
if (*++p == '{') {
char* const e = strchr(p, '}');
if (!e) {
RExC_parse = p + 1;
vFAIL("Missing right brace on \\x{}");
}
else {
I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX;
STRLEN numlen = e - p - 1;
ender = grok_hex(p + 1, &numlen, &flags, NULL);
if (ender > 0xff)
RExC_utf8 = 1;
p = e + 1;
}
}
else {
I32 flags = PERL_SCAN_DISALLOW_PREFIX;
STRLEN numlen = 2;
ender = grok_hex(p, &numlen, &flags, NULL);
p += numlen;
}
if (PL_encoding && ender < 0x100)
goto recode_encoding;
break;
case 'c':
p++;
ender = UCHARAT(p++);
ender = toCTRL(ender);
break;
case '0': case '1': case '2': case '3':case '4':
case '5': case '6': case '7': case '8':case '9':
if (*p == '0' ||
(isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
I32 flags = 0;
STRLEN numlen = 3;
ender = grok_oct(p, &numlen, &flags, NULL);
/* An octal above 0xff is interpreted differently
* depending on if the re is in utf8 or not. If it
* is in utf8, the value will be itself, otherwise
* it is interpreted as modulo 0x100. It has been
* decided to discourage the use of octal above the
* single-byte range. For now, warn only when
* it ends up modulo */
if (SIZE_ONLY && ender >= 0x100
&& ! UTF && ! PL_encoding) {
ckWARNregdep(p, "Use of octal value above 377 is deprecated");
}
p += numlen;
}
else {
--p;
goto loopdone;
}
if (PL_encoding && ender < 0x100)
goto recode_encoding;
break;
recode_encoding:
{
SV* enc = PL_encoding;
ender = reg_recode((const char)(U8)ender, &enc);
if (!enc && SIZE_ONLY)
ckWARNreg(p, "Invalid escape in the specified encoding");
RExC_utf8 = 1;
}
break;
case '\0':
if (p >= RExC_end)
FAIL("Trailing \\");
/* FALL THROUGH */
default:
if (!SIZE_ONLY&& isALPHA(*p))
ckWARN2reg(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
goto normal_default;
}
break;
default:
normal_default:
if (UTF8_IS_START(*p) && UTF) {
STRLEN numlen;
ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
&numlen, UTF8_ALLOW_DEFAULT);
p += numlen;
}
else
ender = *p++;
break;
}
if ( RExC_flags & RXf_PMf_EXTENDED)
p = regwhite( pRExC_state, p );
if (UTF && FOLD) {
/* Prime the casefolded buffer. */
ender = toFOLD_uni(ender, tmpbuf, &foldlen);
}
if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
if (len)
p = oldp;
else if (UTF) {
if (FOLD) {
/* Emit all the Unicode characters. */
STRLEN numlen;
for (foldbuf = tmpbuf;
foldlen;
foldlen -= numlen) {
ender = utf8_to_uvchr(foldbuf, &numlen);
if (numlen > 0) {
const STRLEN unilen = reguni(pRExC_state, ender, s);
s += unilen;
len += unilen;
/* In EBCDIC the numlen
* and unilen can differ. */
foldbuf += numlen;
if (numlen >= foldlen)
break;
}
else
break; /* "Can't happen." */
}
}
else {
const STRLEN unilen = reguni(pRExC_state, ender, s);
if (unilen > 0) {
s += unilen;
len += unilen;
}
}
}
else {
len++;
REGC((char)ender, s++);
}
break;
}
if (UTF) {
if (FOLD) {
/* Emit all the Unicode characters. */
STRLEN numlen;
for (foldbuf = tmpbuf;
foldlen;
foldlen -= numlen) {
ender = utf8_to_uvchr(foldbuf, &numlen);
if (numlen > 0) {
const STRLEN unilen = reguni(pRExC_state, ender, s);
len += unilen;
s += unilen;
/* In EBCDIC the numlen
* and unilen can differ. */
foldbuf += numlen;
if (numlen >= foldlen)
break;
}
else
break;
}
}
else {
const STRLEN unilen = reguni(pRExC_state, ender, s);
if (unilen > 0) {
s += unilen;
len += unilen;
}
}
len--;
}
else
REGC((char)ender, s++);
}
loopdone:
RExC_parse = p - 1;
Set_Node_Cur_Length(ret); /* MJD */
nextchar(pRExC_state);
{
/* len is STRLEN which is unsigned, need to copy to signed */
IV iv = len;
if (iv < 0)
vFAIL("Internal disaster");
}
if (len > 0)
*flagp |= HASWIDTH;
if (len == 1 && UNI_IS_INVARIANT(ender))
*flagp |= SIMPLE;
if (SIZE_ONLY)
RExC_size += STR_SZ(len);
else {
STR_LEN(ret) = len;
RExC_emit += STR_SZ(len);
}
}
break;
}
return(ret);
}
STATIC char *
S_regwhite( RExC_state_t *pRExC_state, char *p )
{
const char *e = RExC_end;
PERL_ARGS_ASSERT_REGWHITE;
while (p < e) {
if (isSPACE(*p))
++p;
else if (*p == '#') {
bool ended = 0;
do {
if (*p++ == '\n') {
ended = 1;
break;
}
} while (p < e);
if (!ended)
RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
}
else
break;
}
return p;
}
/* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
Character classes ([:foo:]) can also be negated ([:^foo:]).
Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
but trigger failures because they are currently unimplemented. */
#define POSIXCC_DONE(c) ((c) == ':')
#define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
#define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
STATIC I32
S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
{
dVAR;
I32 namedclass = OOB_NAMEDCLASS;
PERL_ARGS_ASSERT_REGPPOSIXCC;
if (value == '[' && RExC_parse + 1 < RExC_end &&
/* I smell either [: or [= or [. -- POSIX has been here, right? */
POSIXCC(UCHARAT(RExC_parse))) {
const char c = UCHARAT(RExC_parse);
char* const s = RExC_parse++;
while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
RExC_parse++;
if (RExC_parse == RExC_end)
/* Grandfather lone [:, [=, [. */
RExC_parse = s;
else {
const char* const t = RExC_parse++; /* skip over the c */
assert(*t == c);
if (UCHARAT(RExC_parse) == ']') {
const char *posixcc = s + 1;
RExC_parse++; /* skip over the ending ] */
if (*s == ':') {
const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
const I32 skip = t - posixcc;
/* Initially switch on the length of the name. */
switch (skip) {
case 4:
if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
break;
case 5:
/* Names all of length 5. */
/* alnum alpha ascii blank cntrl digit graph lower
print punct space upper */
/* Offset 4 gives the best switch position. */
switch (posixcc[4]) {
case 'a':
if (memEQ(posixcc, "alph", 4)) /* alpha */
namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
break;
case 'e':
if (memEQ(posixcc, "spac", 4)) /* space */
namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
break;
case 'h':
if (memEQ(posixcc, "grap", 4)) /* graph */
namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
break;
case 'i':
if (memEQ(posixcc, "asci", 4)) /* ascii */
namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
break;
case 'k':
if (memEQ(posixcc, "blan", 4)) /* blank */
namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
break;
case 'l':
if (memEQ(posixcc, "cntr", 4)) /* cntrl */
namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
break;
case 'm':
if (memEQ(posixcc, "alnu", 4)) /* alnum */
namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
break;
case 'r':
if (memEQ(posixcc, "lowe", 4)) /* lower */
namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
else if (memEQ(posixcc, "uppe", 4)) /* upper */
namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
break;
case 't':
if (memEQ(posixcc, "digi", 4)) /* digit */
namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
else if (memEQ(posixcc, "prin", 4)) /* print */
namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
else if (memEQ(posixcc, "punc", 4)) /* punct */
namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
break;
}
break;
case 6:
if (memEQ(posixcc, "xdigit", 6))
namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
break;
}
if (namedclass == OOB_NAMEDCLASS)
Simple_vFAIL3("POSIX class [:%.*s:] unknown",
t - s - 1, s + 1);
assert (posixcc[skip] == ':');
assert (posixcc[skip+1] == ']');
} else if (!SIZE_ONLY) {
/* [[=foo=]] and [[.foo.]] are still future. */
/* adjust RExC_parse so the warning shows after
the class closes */
while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
RExC_parse++;
Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
}
} else {
/* Maternal grandfather:
* "[:" ending in ":" but not in ":]" */
RExC_parse = s;
}
}
}
return namedclass;
}
STATIC void
S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
{
dVAR;
PERL_ARGS_ASSERT_CHECKPOSIXCC;
if (POSIXCC(UCHARAT(RExC_parse))) {
const char *s = RExC_parse;
const char c = *s++;
while (isALNUM(*s))
s++;
if (*s && c == *s && s[1] == ']') {
ckWARN3reg(s+2,
"POSIX syntax [%c %c] belongs inside character classes",
c, c);
/* [[=foo=]] and [[.foo.]] are still future. */
if (POSIXCC_NOTYET(c)) {
/* adjust RExC_parse so the error shows after
the class closes */
while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
NOOP;
Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
}
}
}
}
#define _C_C_T_(NAME,TEST,WORD) \
ANYOF_##NAME: \
if (LOC) \
ANYOF_CLASS_SET(ret, ANYOF_##NAME); \
else { \
for (value = 0; value < 256; value++) \
if (TEST) \
ANYOF_BITMAP_SET(ret, value); \
} \
yesno = '+'; \
what = WORD; \
break; \
case ANYOF_N##NAME: \
if (LOC) \
ANYOF_CLASS_SET(ret, ANYOF_N##NAME); \
else { \
for (value = 0; value < 256; value++) \
if (!TEST) \
ANYOF_BITMAP_SET(ret, value); \
} \
yesno = '!'; \
what = WORD; \
break
#define _C_C_T_NOLOC_(NAME,TEST,WORD) \
ANYOF_##NAME: \
for (value = 0; value < 256; value++) \
if (TEST) \
ANYOF_BITMAP_SET(ret, value); \
yesno = '+'; \
what = WORD; \
break; \
case ANYOF_N##NAME: \
for (value = 0; value < 256; value++) \
if (!TEST) \
ANYOF_BITMAP_SET(ret, value); \
yesno = '!'; \
what = WORD; \
break
/*
We dont use PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS as the direct test
so that it is possible to override the option here without having to
rebuild the entire core. as we are required to do if we change regcomp.h
which is where PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS is defined.
*/
#if PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS
#define BROKEN_UNICODE_CHARCLASS_MAPPINGS
#endif
#ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
#define POSIX_CC_UNI_NAME(CCNAME) CCNAME
#else
#define POSIX_CC_UNI_NAME(CCNAME) "Posix" CCNAME
#endif
/*
parse a class specification and produce either an ANYOF node that
matches the pattern or if the pattern matches a single char only and
that char is < 256 and we are case insensitive then we produce an
EXACT node instead.
*/
STATIC regnode *
S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
{
dVAR;
register UV nextvalue;
register IV prevvalue = OOB_UNICODE;
register IV range = 0;
UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
register regnode *ret;
STRLEN numlen;
IV namedclass;
char *rangebegin = NULL;
bool need_class = 0;
SV *listsv = NULL;
UV n;
bool optimize_invert = TRUE;
AV* unicode_alternate = NULL;
#ifdef EBCDIC
UV literal_endpoint = 0;
#endif
UV stored = 0; /* number of chars stored in the class */
regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
case we need to change the emitted regop to an EXACT. */
const char * orig_parse = RExC_parse;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGCLASS;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
DEBUG_PARSE("clas");
/* Assume we are going to generate an ANYOF node. */
ret = reganode(pRExC_state, ANYOF, 0);
if (!SIZE_ONLY)
ANYOF_FLAGS(ret) = 0;
if (UCHARAT(RExC_parse) == '^') { /* Complement of range. */
RExC_naughty++;
RExC_parse++;
if (!SIZE_ONLY)
ANYOF_FLAGS(ret) |= ANYOF_INVERT;
}
if (SIZE_ONLY) {
RExC_size += ANYOF_SKIP;
listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
}
else {
RExC_emit += ANYOF_SKIP;
if (FOLD)
ANYOF_FLAGS(ret) |= ANYOF_FOLD;
if (LOC)
ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
ANYOF_BITMAP_ZERO(ret);
listsv = newSVpvs("# comment\n");
}
nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
if (!SIZE_ONLY && POSIXCC(nextvalue))
checkposixcc(pRExC_state);
/* allow 1st char to be ] (allowing it to be - is dealt with later) */
if (UCHARAT(RExC_parse) == ']')
goto charclassloop;
parseit:
while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
charclassloop:
namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
if (!range)
rangebegin = RExC_parse;
if (UTF) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
if (value == '[' && POSIXCC(nextvalue))
namedclass = regpposixcc(pRExC_state, value);
else if (value == '\\') {
if (UTF) {
value = utf8n_to_uvchr((U8*)RExC_parse,
RExC_end - RExC_parse,
&numlen, UTF8_ALLOW_DEFAULT);
RExC_parse += numlen;
}
else
value = UCHARAT(RExC_parse++);
/* Some compilers cannot handle switching on 64-bit integer
* values, therefore value cannot be an UV. Yes, this will
* be a problem later if we want switch on Unicode.
* A similar issue a little bit later when switching on
* namedclass. --jhi */
switch ((I32)value) {
case 'w': namedclass = ANYOF_ALNUM; break;
case 'W': namedclass = ANYOF_NALNUM; break;
case 's': namedclass = ANYOF_SPACE; break;
case 'S': namedclass = ANYOF_NSPACE; break;
case 'd': namedclass = ANYOF_DIGIT; break;
case 'D': namedclass = ANYOF_NDIGIT; break;
case 'v': namedclass = ANYOF_VERTWS; break;
case 'V': namedclass = ANYOF_NVERTWS; break;
case 'h': namedclass = ANYOF_HORIZWS; break;
case 'H': namedclass = ANYOF_NHORIZWS; break;
case 'N': /* Handle \N{NAME} in class */
{
/* We only pay attention to the first char of
multichar strings being returned. I kinda wonder
if this makes sense as it does change the behaviour
from earlier versions, OTOH that behaviour was broken
as well. */
UV v; /* value is register so we cant & it /grrr */
if (reg_namedseq(pRExC_state, &v, NULL)) {
goto parseit;
}
value= v;
}
break;
case 'p':
case 'P':
{
char *e;
if (RExC_parse >= RExC_end)
vFAIL2("Empty \\%c{}", (U8)value);
if (*RExC_parse == '{') {
const U8 c = (U8)value;
e = strchr(RExC_parse++, '}');
if (!e)
vFAIL2("Missing right brace on \\%c{}", c);
while (isSPACE(UCHARAT(RExC_parse)))
RExC_parse++;
if (e == RExC_parse)
vFAIL2("Empty \\%c{}", c);
n = e - RExC_parse;
while (isSPACE(UCHARAT(RExC_parse + n - 1)))
n--;
}
else {
e = RExC_parse;
n = 1;
}
if (!SIZE_ONLY) {
if (UCHARAT(RExC_parse) == '^') {
RExC_parse++;
n--;
value = value == 'p' ? 'P' : 'p'; /* toggle */
while (isSPACE(UCHARAT(RExC_parse))) {
RExC_parse++;
n--;
}
}
Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
(value=='p' ? '+' : '!'), (int)n, RExC_parse);
}
RExC_parse = e + 1;
ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
namedclass = ANYOF_MAX; /* no official name, but it's named */
}
break;
case 'n': value = '\n'; break;
case 'r': value = '\r'; break;
case 't': value = '\t'; break;
case 'f': value = '\f'; break;
case 'b': value = '\b'; break;
case 'e': value = ASCII_TO_NATIVE('\033');break;
case 'a': value = ASCII_TO_NATIVE('\007');break;
case 'x':
if (*RExC_parse == '{') {
I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
| PERL_SCAN_DISALLOW_PREFIX;
char * const e = strchr(RExC_parse++, '}');
if (!e)
vFAIL("Missing right brace on \\x{}");
numlen = e - RExC_parse;
value = grok_hex(RExC_parse, &numlen, &flags, NULL);
RExC_parse = e + 1;
}
else {
I32 flags = PERL_SCAN_DISALLOW_PREFIX;
numlen = 2;
value = grok_hex(RExC_parse, &numlen, &flags, NULL);
RExC_parse += numlen;
}
if (PL_encoding && value < 0x100)
goto recode_encoding;
break;
case 'c':
value = UCHARAT(RExC_parse++);
value = toCTRL(value);
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
I32 flags = 0;
numlen = 3;
value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
RExC_parse += numlen;
if (PL_encoding && value < 0x100)
goto recode_encoding;
break;
}
recode_encoding:
{
SV* enc = PL_encoding;
value = reg_recode((const char)(U8)value, &enc);
if (!enc && SIZE_ONLY)
ckWARNreg(RExC_parse,
"Invalid escape in the specified encoding");
break;
}
default:
if (!SIZE_ONLY && isALPHA(value))
ckWARN2reg(RExC_parse,
"Unrecognized escape \\%c in character class passed through",
(int)value);
break;
}
} /* end of \blah */
#ifdef EBCDIC
else
literal_endpoint++;
#endif
if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
if (!SIZE_ONLY && !need_class)
ANYOF_CLASS_ZERO(ret);
need_class = 1;
/* a bad range like a-\d, a-[:digit:] ? */
if (range) {
if (!SIZE_ONLY) {
const int w =
RExC_parse >= rangebegin ?
RExC_parse - rangebegin : 0;
ckWARN4reg(RExC_parse,
"False [] range \"%*.*s\"",
w, w, rangebegin);
if (prevvalue < 256) {
ANYOF_BITMAP_SET(ret, prevvalue);
ANYOF_BITMAP_SET(ret, '-');
}
else {
ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
Perl_sv_catpvf(aTHX_ listsv,
"%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
}
}
range = 0; /* this was not a true range */
}
if (!SIZE_ONLY) {
const char *what = NULL;
char yesno = 0;
if (namedclass > OOB_NAMEDCLASS)
optimize_invert = FALSE;
/* Possible truncation here but in some 64-bit environments
* the compiler gets heartburn about switch on 64-bit values.
* A similar issue a little earlier when switching on value.
* --jhi */
switch ((I32)namedclass) {
case _C_C_T_(ALNUMC, isALNUMC(value), POSIX_CC_UNI_NAME("Alnum"));
case _C_C_T_(ALPHA, isALPHA(value), POSIX_CC_UNI_NAME("Alpha"));
case _C_C_T_(BLANK, isBLANK(value), POSIX_CC_UNI_NAME("Blank"));
case _C_C_T_(CNTRL, isCNTRL(value), POSIX_CC_UNI_NAME("Cntrl"));
case _C_C_T_(GRAPH, isGRAPH(value), POSIX_CC_UNI_NAME("Graph"));
case _C_C_T_(LOWER, isLOWER(value), POSIX_CC_UNI_NAME("Lower"));
case _C_C_T_(PRINT, isPRINT(value), POSIX_CC_UNI_NAME("Print"));
case _C_C_T_(PSXSPC, isPSXSPC(value), POSIX_CC_UNI_NAME("Space"));
case _C_C_T_(PUNCT, isPUNCT(value), POSIX_CC_UNI_NAME("Punct"));
case _C_C_T_(UPPER, isUPPER(value), POSIX_CC_UNI_NAME("Upper"));
#ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
case _C_C_T_(ALNUM, isALNUM(value), "Word");
case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
#else
case _C_C_T_(SPACE, isSPACE(value), "PerlSpace");
case _C_C_T_(ALNUM, isALNUM(value), "PerlWord");
#endif
case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
case _C_C_T_NOLOC_(VERTWS, is_VERTWS_latin1(&value), "VertSpace");
case _C_C_T_NOLOC_(HORIZWS, is_HORIZWS_latin1(&value), "HorizSpace");
case ANYOF_ASCII:
if (LOC)
ANYOF_CLASS_SET(ret, ANYOF_ASCII);
else {
#ifndef EBCDIC
for (value = 0; value < 128; value++)
ANYOF_BITMAP_SET(ret, value);
#else /* EBCDIC */
for (value = 0; value < 256; value++) {
if (isASCII(value))
ANYOF_BITMAP_SET(ret, value);
}
#endif /* EBCDIC */
}
yesno = '+';
what = "ASCII";
break;
case ANYOF_NASCII:
if (LOC)
ANYOF_CLASS_SET(ret, ANYOF_NASCII);
else {
#ifndef EBCDIC
for (value = 128; value < 256; value++)
ANYOF_BITMAP_SET(ret, value);
#else /* EBCDIC */
for (value = 0; value < 256; value++) {
if (!isASCII(value))
ANYOF_BITMAP_SET(ret, value);
}
#endif /* EBCDIC */
}
yesno = '!';
what = "ASCII";
break;
case ANYOF_DIGIT:
if (LOC)
ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
else {
/* consecutive digits assumed */
for (value = '0'; value <= '9'; value++)
ANYOF_BITMAP_SET(ret, value);
}
yesno = '+';
what = POSIX_CC_UNI_NAME("Digit");
break;
case ANYOF_NDIGIT:
if (LOC)
ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
else {
/* consecutive digits assumed */
for (value = 0; value < '0'; value++)
ANYOF_BITMAP_SET(ret, value);
for (value = '9' + 1; value < 256; value++)
ANYOF_BITMAP_SET(ret, value);
}
yesno = '!';
what = POSIX_CC_UNI_NAME("Digit");
break;
case ANYOF_MAX:
/* this is to handle \p and \P */
break;
default:
vFAIL("Invalid [::] class");
break;
}
if (what) {
/* Strings such as "+utf8::isWord\n" */
Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
}
if (LOC)
ANYOF_FLAGS(ret) |= ANYOF_CLASS;
continue;
}
} /* end of namedclass \blah */
if (range) {
if (prevvalue > (IV)value) /* b-a */ {
const int w = RExC_parse - rangebegin;
Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
range = 0; /* not a valid range */
}
}
else {
prevvalue = value; /* save the beginning of the range */
if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
RExC_parse[1] != ']') {
RExC_parse++;
/* a bad range like \w-, [:word:]- ? */
if (namedclass > OOB_NAMEDCLASS) {
if (ckWARN(WARN_REGEXP)) {
const int w =
RExC_parse >= rangebegin ?
RExC_parse - rangebegin : 0;
vWARN4(RExC_parse,
"False [] range \"%*.*s\"",
w, w, rangebegin);
}
if (!SIZE_ONLY)
ANYOF_BITMAP_SET(ret, '-');
} else
range = 1; /* yeah, it's a range! */
continue; /* but do it the next time */
}
}
/* now is the next time */
/*stored += (value - prevvalue + 1);*/
if (!SIZE_ONLY) {
if (prevvalue < 256) {
const IV ceilvalue = value < 256 ? value : 255;
IV i;
#ifdef EBCDIC
/* In EBCDIC [\x89-\x91] should include
* the \x8e but [i-j] should not. */
if (literal_endpoint == 2 &&
((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
(isUPPER(prevvalue) && isUPPER(ceilvalue))))
{
if (isLOWER(prevvalue)) {
for (i = prevvalue; i <= ceilvalue; i++)
if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
stored++;
ANYOF_BITMAP_SET(ret, i);
}
} else {
for (i = prevvalue; i <= ceilvalue; i++)
if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
stored++;
ANYOF_BITMAP_SET(ret, i);
}
}
}
else
#endif
for (i = prevvalue; i <= ceilvalue; i++) {
if (!ANYOF_BITMAP_TEST(ret,i)) {
stored++;
ANYOF_BITMAP_SET(ret, i);
}
}
}
if (value > 255 || UTF) {
const UV prevnatvalue = NATIVE_TO_UNI(prevvalue);
const UV natvalue = NATIVE_TO_UNI(value);
stored+=2; /* can't optimize this class */
ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
if (prevnatvalue < natvalue) { /* what about > ? */
Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
prevnatvalue, natvalue);
}
else if (prevnatvalue == natvalue) {
Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
if (FOLD) {
U8 foldbuf[UTF8_MAXBYTES_CASE+1];
STRLEN foldlen;
const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
#ifdef EBCDIC /* RD t/uni/fold ff and 6b */
if (RExC_precomp[0] == ':' &&
RExC_precomp[1] == '[' &&
(f == 0xDF || f == 0x92)) {
f = NATIVE_TO_UNI(f);
}
#endif
/* If folding and foldable and a single
* character, insert also the folded version
* to the charclass. */
if (f != value) {
#ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
if ((RExC_precomp[0] == ':' &&
RExC_precomp[1] == '[' &&
(f == 0xA2 &&
(value == 0xFB05 || value == 0xFB06))) ?
foldlen == ((STRLEN)UNISKIP(f) - 1) :
foldlen == (STRLEN)UNISKIP(f) )
#else
if (foldlen == (STRLEN)UNISKIP(f))
#endif
Perl_sv_catpvf(aTHX_ listsv,
"%04"UVxf"\n", f);
else {
/* Any multicharacter foldings
* require the following transform:
* [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
* where E folds into "pq" and F folds
* into "rst", all other characters
* fold to single characters. We save
* away these multicharacter foldings,
* to be later saved as part of the
* additional "s" data. */
SV *sv;
if (!unicode_alternate)
unicode_alternate = newAV();
sv = newSVpvn_utf8((char*)foldbuf, foldlen,
TRUE);
av_push(unicode_alternate, sv);
}
}
/* If folding and the value is one of the Greek
* sigmas insert a few more sigmas to make the
* folding rules of the sigmas to work right.
* Note that not all the possible combinations
* are handled here: some of them are handled
* by the standard folding rules, and some of
* them (literal or EXACTF cases) are handled
* during runtime in regexec.c:S_find_byclass(). */
if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
(UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
(UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
}
else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
(UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
}
}
}
#ifdef EBCDIC
literal_endpoint = 0;
#endif
}
range = 0; /* this range (if it was one) is done now */
}
if (need_class) {
ANYOF_FLAGS(ret) |= ANYOF_LARGE;
if (SIZE_ONLY)
RExC_size += ANYOF_CLASS_ADD_SKIP;
else
RExC_emit += ANYOF_CLASS_ADD_SKIP;
}
if (SIZE_ONLY)
return ret;
/****** !SIZE_ONLY AFTER HERE *********/
if( stored == 1 && (value < 128 || (value < 256 && !UTF))
&& !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
) {
/* optimize single char class to an EXACT node
but *only* when its not a UTF/high char */
const char * cur_parse= RExC_parse;
RExC_emit = (regnode *)orig_emit;
RExC_parse = (char *)orig_parse;
ret = reg_node(pRExC_state,
(U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
RExC_parse = (char *)cur_parse;
*STRING(ret)= (char)value;
STR_LEN(ret)= 1;
RExC_emit += STR_SZ(1);
SvREFCNT_dec(listsv);
return ret;
}
/* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
if ( /* If the only flag is folding (plus possibly inversion). */
((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
) {
for (value = 0; value < 256; ++value) {
if (ANYOF_BITMAP_TEST(ret, value)) {
UV fold = PL_fold[value];
if (fold != value)
ANYOF_BITMAP_SET(ret, fold);
}
}
ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
}
/* optimize inverted simple patterns (e.g. [^a-z]) */
if (optimize_invert &&
/* If the only flag is inversion. */
(ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
}
{
AV * const av = newAV();
SV *rv;
/* The 0th element stores the character class description
* in its textual form: used later (regexec.c:Perl_regclass_swash())
* to initialize the appropriate swash (which gets stored in
* the 1st element), and also useful for dumping the regnode.
* The 2nd element stores the multicharacter foldings,
* used later (regexec.c:S_reginclass()). */
av_store(av, 0, listsv);
av_store(av, 1, NULL);
av_store(av, 2, MUTABLE_SV(unicode_alternate));
rv = newRV_noinc(MUTABLE_SV(av));
n = add_data(pRExC_state, 1, "s");
RExC_rxi->data->data[n] = (void*)rv;
ARG_SET(ret, n);
}
return ret;
}
#undef _C_C_T_
/* reg_skipcomment()
Absorbs an /x style # comments from the input stream.
Returns true if there is more text remaining in the stream.
Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
terminates the pattern without including a newline.
Note its the callers responsibility to ensure that we are
actually in /x mode
*/
STATIC bool
S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
{
bool ended = 0;
PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
while (RExC_parse < RExC_end)
if (*RExC_parse++ == '\n') {
ended = 1;
break;
}
if (!ended) {
/* we ran off the end of the pattern without ending
the comment, so we have to add an \n when wrapping */
RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
return 0;
} else
return 1;
}
/* nextchar()
Advance that parse position, and optionall absorbs
"whitespace" from the inputstream.
Without /x "whitespace" means (?#...) style comments only,
with /x this means (?#...) and # comments and whitespace proper.
Returns the RExC_parse point from BEFORE the scan occurs.
This is the /x friendly way of saying RExC_parse++.
*/
STATIC char*
S_nextchar(pTHX_ RExC_state_t *pRExC_state)
{
char* const retval = RExC_parse++;
PERL_ARGS_ASSERT_NEXTCHAR;
for (;;) {
if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
RExC_parse[2] == '#') {
while (*RExC_parse != ')') {
if (RExC_parse == RExC_end)
FAIL("Sequence (?#... not terminated");
RExC_parse++;
}
RExC_parse++;
continue;
}
if (RExC_flags & RXf_PMf_EXTENDED) {
if (isSPACE(*RExC_parse)) {
RExC_parse++;
continue;
}
else if (*RExC_parse == '#') {
if ( reg_skipcomment( pRExC_state ) )
continue;
}
}
return retval;
}
}
/*
- reg_node - emit a node
*/
STATIC regnode * /* Location. */
S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
{
dVAR;
register regnode *ptr;
regnode * const ret = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REG_NODE;
if (SIZE_ONLY) {
SIZE_ALIGN(RExC_size);
RExC_size += 1;
return(ret);
}
if (RExC_emit >= RExC_emit_bound)
Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
NODE_ALIGN_FILL(ret);
ptr = ret;
FILL_ADVANCE_NODE(ptr, op);
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n",
"reg_node", __LINE__,
PL_reg_name[op],
(UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(RExC_emit - RExC_emit_start),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
}
#endif
RExC_emit = ptr;
return(ret);
}
/*
- reganode - emit a node with an argument
*/
STATIC regnode * /* Location. */
S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
{
dVAR;
register regnode *ptr;
regnode * const ret = RExC_emit;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGANODE;
if (SIZE_ONLY) {
SIZE_ALIGN(RExC_size);
RExC_size += 2;
/*
We can't do this:
assert(2==regarglen[op]+1);
Anything larger than this has to allocate the extra amount.
If we changed this to be:
RExC_size += (1 + regarglen[op]);
then it wouldn't matter. Its not clear what side effect
might come from that so its not done so far.
-- dmq
*/
return(ret);
}
if (RExC_emit >= RExC_emit_bound)
Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
NODE_ALIGN_FILL(ret);
ptr = ret;
FILL_ADVANCE_NODE_ARG(ptr, op, arg);
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
"reganode",
__LINE__,
PL_reg_name[op],
(UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ?
"Overwriting end of array!\n" : "OK",
(UV)(RExC_emit - RExC_emit_start),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Cur_Node_Offset;
}
#endif
RExC_emit = ptr;
return(ret);
}
/*
- reguni - emit (if appropriate) a Unicode character
*/
STATIC STRLEN
S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
{
dVAR;
PERL_ARGS_ASSERT_REGUNI;
return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
}
/*
- reginsert - insert an operator in front of already-emitted operand
*
* Means relocating the operand.
*/
STATIC void
S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
{
dVAR;
register regnode *src;
register regnode *dst;
register regnode *place;
const int offset = regarglen[(U8)op];
const int size = NODE_STEP_REGNODE + offset;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGINSERT;
PERL_UNUSED_ARG(depth);
/* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
if (SIZE_ONLY) {
RExC_size += size;
return;
}
src = RExC_emit;
RExC_emit += size;
dst = RExC_emit;
if (RExC_open_parens) {
int paren;
/*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
for ( paren=0 ; paren < RExC_npar ; paren++ ) {
if ( RExC_open_parens[paren] >= opnd ) {
/*DEBUG_PARSE_FMT("open"," - %d",size);*/
RExC_open_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("open"," - %s","ok");*/
}
if ( RExC_close_parens[paren] >= opnd ) {
/*DEBUG_PARSE_FMT("close"," - %d",size);*/
RExC_close_parens[paren] += size;
} else {
/*DEBUG_PARSE_FMT("close"," - %s","ok");*/
}
}
}
while (src > opnd) {
StructCopy(--src, --dst, regnode);
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD 20010112 */
MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
"reg_insert",
__LINE__,
PL_reg_name[op],
(UV)(dst - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(src - RExC_emit_start),
(UV)(dst - RExC_emit_start),
(UV)RExC_offsets[0]));
Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
}
#endif
}
place = opnd; /* Op node, where operand used to be. */
#ifdef RE_TRACK_PATTERN_OFFSETS
if (RExC_offsets) { /* MJD */
MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n",
"reginsert",
__LINE__,
PL_reg_name[op],
(UV)(place - RExC_emit_start) > RExC_offsets[0]
? "Overwriting end of array!\n" : "OK",
(UV)(place - RExC_emit_start),
(UV)(RExC_parse - RExC_start),
(UV)RExC_offsets[0]));
Set_Node_Offset(place, RExC_parse);
Set_Node_Length(place, 1);
}
#endif
src = NEXTOPER(place);
FILL_ADVANCE_NODE(place, op);
Zero(src, offset, regnode);
}
/*
- regtail - set the next-pointer at the end of a node chain of p to val.
- SEE ALSO: regtail_study
*/
/* TODO: All three parms should be const */
STATIC void
S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
{
dVAR;
register regnode *scan;
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL;
#ifndef DEBUGGING
PERL_UNUSED_ARG(depth);
#endif
if (SIZE_ONLY)
return;
/* Find last node. */
scan = p;
for (;;) {
regnode * const temp = regnext(scan);
DEBUG_PARSE_r({
SV * const mysv=sv_newmortal();
DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
regprop(RExC_rx, mysv, scan);
PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
(temp == NULL ? "->" : ""),
(temp == NULL ? PL_reg_name[OP(val)] : "")
);
});
if (temp == NULL)
break;
scan = temp;
}
if (reg_off_by_arg[OP(scan)]) {
ARG_SET(scan, val - scan);
}
else {
NEXT_OFF(scan) = val - scan;
}
}
#ifdef DEBUGGING
/*
- regtail_study - set the next-pointer at the end of a node chain of p to val.
- Look for optimizable sequences at the same time.
- currently only looks for EXACT chains.
This is expermental code. The idea is to use this routine to perform
in place optimizations on branches and groups as they are constructed,
with the long term intention of removing optimization from study_chunk so
that it is purely analytical.
Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
to control which is which.
*/
/* TODO: All four parms should be const */
STATIC U8
S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
{
dVAR;
register regnode *scan;
U8 exact = PSEUDO;
#ifdef EXPERIMENTAL_INPLACESCAN
I32 min = 0;
#endif
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGTAIL_STUDY;
if (SIZE_ONLY)
return exact;
/* Find last node. */
scan = p;
for (;;) {
regnode * const temp = regnext(scan);
#ifdef EXPERIMENTAL_INPLACESCAN
if (PL_regkind[OP(scan)] == EXACT)
if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
return EXACT;
#endif
if ( exact ) {
switch (OP(scan)) {
case EXACT:
case EXACTF:
case EXACTFL:
if( exact == PSEUDO )
exact= OP(scan);
else if ( exact != OP(scan) )
exact= 0;
case NOTHING:
break;
default:
exact= 0;
}
}
DEBUG_PARSE_r({
SV * const mysv=sv_newmortal();
DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
regprop(RExC_rx, mysv, scan);
PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
SvPV_nolen_const(mysv),
REG_NODE_NUM(scan),
PL_reg_name[exact]);
});
if (temp == NULL)
break;
scan = temp;
}
DEBUG_PARSE_r({
SV * const mysv_val=sv_newmortal();
DEBUG_PARSE_MSG("");
regprop(RExC_rx, mysv_val, val);
PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
SvPV_nolen_const(mysv_val),
(IV)REG_NODE_NUM(val),
(IV)(val - scan)
);
});
if (reg_off_by_arg[OP(scan)]) {
ARG_SET(scan, val - scan);
}
else {
NEXT_OFF(scan) = val - scan;
}
return exact;
}
#endif
/*
- regcurly - a little FSA that accepts {\d+,?\d*}
*/
#ifndef PERL_IN_XSUB_RE
I32
Perl_regcurly(register const char *s)
{
PERL_ARGS_ASSERT_REGCURLY;
if (*s++ != '{')
return FALSE;
if (!isDIGIT(*s))
return FALSE;
while (isDIGIT(*s))
s++;
if (*s == ',')
s++;
while (isDIGIT(*s))
s++;
if (*s != '}')
return FALSE;
return TRUE;
}
#endif
/*
- regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
*/
#ifdef DEBUGGING
static void
S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
{
int bit;
int set=0;
for (bit=0; bit<32; bit++) {
if (flags & (1<<bit)) {
if (!set++ && lead)
PerlIO_printf(Perl_debug_log, "%s",lead);
PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
}
}
if (lead) {
if (set)
PerlIO_printf(Perl_debug_log, "\n");
else
PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
}
}
#endif
void
Perl_regdump(pTHX_ const regexp *r)
{
#ifdef DEBUGGING
dVAR;
SV * const sv = sv_newmortal();
SV *dsv= sv_newmortal();
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGDUMP;
(void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
/* Header fields of interest. */
if (r->anchored_substr) {
RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr),
RE_SV_DUMPLEN(r->anchored_substr), 30);
PerlIO_printf(Perl_debug_log,
"anchored %s%s at %"IVdf" ",
s, RE_SV_TAIL(r->anchored_substr),
(IV)r->anchored_offset);
} else if (r->anchored_utf8) {
RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8),
RE_SV_DUMPLEN(r->anchored_utf8), 30);
PerlIO_printf(Perl_debug_log,
"anchored utf8 %s%s at %"IVdf" ",
s, RE_SV_TAIL(r->anchored_utf8),
(IV)r->anchored_offset);
}
if (r->float_substr) {
RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr),
RE_SV_DUMPLEN(r->float_substr), 30);
PerlIO_printf(Perl_debug_log,
"floating %s%s at %"IVdf"..%"UVuf" ",
s, RE_SV_TAIL(r->float_substr),
(IV)r->float_min_offset, (UV)r->float_max_offset);
} else if (r->float_utf8) {
RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8),
RE_SV_DUMPLEN(r->float_utf8), 30);
PerlIO_printf(Perl_debug_log,
"floating utf8 %s%s at %"IVdf"..%"UVuf" ",
s, RE_SV_TAIL(r->float_utf8),
(IV)r->float_min_offset, (UV)r->float_max_offset);
}
if (r->check_substr || r->check_utf8)
PerlIO_printf(Perl_debug_log,
(const char *)
(r->check_substr == r->float_substr
&& r->check_utf8 == r->float_utf8
? "(checking floating" : "(checking anchored"));
if (r->extflags & RXf_NOSCAN)
PerlIO_printf(Perl_debug_log, " noscan");
if (r->extflags & RXf_CHECK_ALL)
PerlIO_printf(Perl_debug_log, " isall");
if (r->check_substr || r->check_utf8)
PerlIO_printf(Perl_debug_log, ") ");
if (ri->regstclass) {
regprop(r, sv, ri->regstclass);
PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
}
if (r->extflags & RXf_ANCH) {
PerlIO_printf(Perl_debug_log, "anchored");
if (r->extflags & RXf_ANCH_BOL)
PerlIO_printf(Perl_debug_log, "(BOL)");
if (r->extflags & RXf_ANCH_MBOL)
PerlIO_printf(Perl_debug_log, "(MBOL)");
if (r->extflags & RXf_ANCH_SBOL)
PerlIO_printf(Perl_debug_log, "(SBOL)");
if (r->extflags & RXf_ANCH_GPOS)
PerlIO_printf(Perl_debug_log, "(GPOS)");
PerlIO_putc(Perl_debug_log, ' ');
}
if (r->extflags & RXf_GPOS_SEEN)
PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
if (r->intflags & PREGf_SKIP)
PerlIO_printf(Perl_debug_log, "plus ");
if (r->intflags & PREGf_IMPLICIT)
PerlIO_printf(Perl_debug_log, "implicit ");
PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
if (r->extflags & RXf_EVAL_SEEN)
PerlIO_printf(Perl_debug_log, "with eval ");
PerlIO_printf(Perl_debug_log, "\n");
DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));
#else
PERL_ARGS_ASSERT_REGDUMP;
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(r);
#endif /* DEBUGGING */
}
/*
- regprop - printable representation of opcode
*/
#define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
STMT_START { \
if (do_sep) { \
Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
if (flags & ANYOF_INVERT) \
/*make sure the invert info is in each */ \
sv_catpvs(sv, "^"); \
do_sep = 0; \
} \
} STMT_END
void
Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
{
#ifdef DEBUGGING
dVAR;
register int k;
RXi_GET_DECL(prog,progi);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGPROP;
sv_setpvs(sv, "");
if (OP(o) > REGNODE_MAX) /* regnode.type is unsigned */
/* It would be nice to FAIL() here, but this may be called from
regexec.c, and it would be hard to supply pRExC_state. */
Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
k = PL_regkind[OP(o)];
if (k == EXACT) {
sv_catpvs(sv, " ");
/* Using is_utf8_string() (via PERL_PV_UNI_DETECT)
* is a crude hack but it may be the best for now since
* we have no flag "this EXACTish node was UTF-8"
* --jhi */
pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
PERL_PV_ESCAPE_UNI_DETECT |
PERL_PV_PRETTY_ELLIPSES |
PERL_PV_PRETTY_LTGT |
PERL_PV_PRETTY_NOCLEAR
);
} else if (k == TRIE) {
/* print the details of the trie in dumpuntil instead, as
* progi->data isn't available here */
const char op = OP(o);
const U32 n = ARG(o);
const reg_ac_data * const ac = IS_TRIE_AC(op) ?
(reg_ac_data *)progi->data->data[n] :
NULL;
const reg_trie_data * const trie
= (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
DEBUG_TRIE_COMPILE_r(
Perl_sv_catpvf(aTHX_ sv,
"<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
(UV)trie->startstate,
(IV)trie->statecount-1, /* -1 because of the unused 0 element */
(UV)trie->wordcount,
(UV)trie->minlen,
(UV)trie->maxlen,
(UV)TRIE_CHARCOUNT(trie),
(UV)trie->uniquecharcount
)
);
if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
int i;
int rangestart = -1;
U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
sv_catpvs(sv, "[");
for (i = 0; i <= 256; i++) {
if (i < 256 && BITMAP_TEST(bitmap,i)) {
if (rangestart == -1)
rangestart = i;
} else if (rangestart != -1) {
if (i <= rangestart + 3)
for (; rangestart < i; rangestart++)
put_byte(sv, rangestart);
else {
put_byte(sv, rangestart);
sv_catpvs(sv, "-");
put_byte(sv, i - 1);
}
rangestart = -1;
}
}
sv_catpvs(sv, "]");
}
} else if (k == CURLY) {
if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
}
else if (k == WHILEM && o->flags) /* Ordinal/of */
Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o)); /* Parenth number */
if ( RXp_PAREN_NAMES(prog) ) {
if ( k != REF || OP(o) < NREF) {
AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
SV **name= av_fetch(list, ARG(o), 0 );
if (name)
Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
}
else {
AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
I32 *nums=(I32*)SvPVX(sv_dat);
SV **name= av_fetch(list, nums[0], 0 );
I32 n;
if (name) {
for ( n=0; n<SvIVX(sv_dat); n++ ) {
Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
(n ? "," : ""), (IV)nums[n]);
}
Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
}
}
}
} else if (k == GOSUB)
Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
else if (k == VERB) {
if (!o->flags)
Perl_sv_catpvf(aTHX_ sv, ":%"SVf,
SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
} else if (k == LOGICAL)
Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* 2: embedded, otherwise 1 */
else if (k == FOLDCHAR)
Perl_sv_catpvf(aTHX_ sv, "[0x%"UVXf"]", PTR2UV(ARG(o)) );
else if (k == ANYOF) {
int i, rangestart = -1;
const U8 flags = ANYOF_FLAGS(o);
int do_sep = 0;
/* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
static const char * const anyofs[] = {
"\\w",
"\\W",
"\\s",
"\\S",
"\\d",
"\\D",
"[:alnum:]",
"[:^alnum:]",
"[:alpha:]",
"[:^alpha:]",
"[:ascii:]",
"[:^ascii:]",
"[:cntrl:]",
"[:^cntrl:]",
"[:graph:]",
"[:^graph:]",
"[:lower:]",
"[:^lower:]",
"[:print:]",
"[:^print:]",
"[:punct:]",
"[:^punct:]",
"[:upper:]",
"[:^upper:]",
"[:xdigit:]",
"[:^xdigit:]",
"[:space:]",
"[:^space:]",
"[:blank:]",
"[:^blank:]"
};
if (flags & ANYOF_LOCALE)
sv_catpvs(sv, "{loc}");
if (flags & ANYOF_FOLD)
sv_catpvs(sv, "{i}");
Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
if (flags & ANYOF_INVERT)
sv_catpvs(sv, "^");
/* output what the standard cp 0-255 bitmap matches */
for (i = 0; i <= 256; i++) {
if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
if (rangestart == -1)
rangestart = i;
} else if (rangestart != -1) {
if (i <= rangestart + 3)
for (; rangestart < i; rangestart++)
put_byte(sv, rangestart);
else {
put_byte(sv, rangestart);
sv_catpvs(sv, "-");
put_byte(sv, i - 1);
}
do_sep = 1;
rangestart = -1;
}
}
EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
/* output any special charclass tests (used mostly under use locale) */
if (o->flags & ANYOF_CLASS)
for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
if (ANYOF_CLASS_TEST(o,i)) {
sv_catpv(sv, anyofs[i]);
do_sep = 1;
}
EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
/* output information about the unicode matching */
if (flags & ANYOF_UNICODE)
sv_catpvs(sv, "{unicode}");
else if (flags & ANYOF_UNICODE_ALL)
sv_catpvs(sv, "{unicode_all}");
{
SV *lv;
SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
if (lv) {
if (sw) {
U8 s[UTF8_MAXBYTES_CASE+1];
for (i = 0; i <= 256; i++) { /* just the first 256 */
uvchr_to_utf8(s, i);
if (i < 256 && swash_fetch(sw, s, TRUE)) {
if (rangestart == -1)
rangestart = i;
} else if (rangestart != -1) {
if (i <= rangestart + 3)
for (; rangestart < i; rangestart++) {
const U8 * const e = uvchr_to_utf8(s,rangestart);
U8 *p;
for(p = s; p < e; p++)
put_byte(sv, *p);
}
else {
const U8 *e = uvchr_to_utf8(s,rangestart);
U8 *p;
for (p = s; p < e; p++)
put_byte(sv, *p);
sv_catpvs(sv, "-");
e = uvchr_to_utf8(s, i-1);
for (p = s; p < e; p++)
put_byte(sv, *p);
}
rangestart = -1;
}
}
sv_catpvs(sv, "..."); /* et cetera */
}
{
char *s = savesvpv(lv);
char * const origs = s;
while (*s && *s != '\n')
s++;
if (*s == '\n') {
const char * const t = ++s;
while (*s) {
if (*s == '\n')
*s = ' ';
s++;
}
if (s[-1] == ' ')
s[-1] = 0;
sv_catpv(sv, t);
}
Safefree(origs);
}
}
}
Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
}
else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
#else
PERL_UNUSED_CONTEXT;
PERL_UNUSED_ARG(sv);
PERL_UNUSED_ARG(o);
PERL_UNUSED_ARG(prog);
#endif /* DEBUGGING */
}
SV *
Perl_re_intuit_string(pTHX_ REGEXP * const r)
{ /* Assume that RE_INTUIT is set */
dVAR;
struct regexp *const prog = (struct regexp *)SvANY(r);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_RE_INTUIT_STRING;
PERL_UNUSED_CONTEXT;
DEBUG_COMPILE_r(
{
const char * const s = SvPV_nolen_const(prog->check_substr
? prog->check_substr : prog->check_utf8);
if (!PL_colorset) reginitcolors();
PerlIO_printf(Perl_debug_log,
"%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
PL_colors[4],
prog->check_substr ? "" : "utf8 ",
PL_colors[5],PL_colors[0],
s,
PL_colors[1],
(strlen(s) > 60 ? "..." : ""));
} );
return prog->check_substr ? prog->check_substr : prog->check_utf8;
}
/*
pregfree()
handles refcounting and freeing the perl core regexp structure. When
it is necessary to actually free the structure the first thing it
does is call the 'free' method of the regexp_engine associated to to
the regexp, allowing the handling of the void *pprivate; member
first. (This routine is not overridable by extensions, which is why
the extensions free is called first.)
See regdupe and regdupe_internal if you change anything here.
*/
#ifndef PERL_IN_XSUB_RE
void
Perl_pregfree(pTHX_ REGEXP *r)
{
SvREFCNT_dec(r);
}
void
Perl_pregfree2(pTHX_ REGEXP *rx)
{
dVAR;
struct regexp *const r = (struct regexp *)SvANY(rx);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_PREGFREE2;
if (r->mother_re) {
ReREFCNT_dec(r->mother_re);
} else {
CALLREGFREE_PVT(rx); /* free the private data */
SvREFCNT_dec(RXp_PAREN_NAMES(r));
}
if (r->substrs) {
SvREFCNT_dec(r->anchored_substr);
SvREFCNT_dec(r->anchored_utf8);
SvREFCNT_dec(r->float_substr);
SvREFCNT_dec(r->float_utf8);
Safefree(r->substrs);
}
RX_MATCH_COPY_FREE(rx);
#ifdef PERL_OLD_COPY_ON_WRITE
SvREFCNT_dec(r->saved_copy);
#endif
Safefree(r->offs);
}
/* reg_temp_copy()
This is a hacky workaround to the structural issue of match results
being stored in the regexp structure which is in turn stored in
PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
could be PL_curpm in multiple contexts, and could require multiple
result sets being associated with the pattern simultaneously, such
as when doing a recursive match with (??{$qr})
The solution is to make a lightweight copy of the regexp structure
when a qr// is returned from the code executed by (??{$qr}) this
lightweight copy doesnt actually own any of its data except for
the starp/end and the actual regexp structure itself.
*/
REGEXP *
Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
{
struct regexp *ret;
struct regexp *const r = (struct regexp *)SvANY(rx);
register const I32 npar = r->nparens+1;
PERL_ARGS_ASSERT_REG_TEMP_COPY;
if (!ret_x)
ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
ret = (struct regexp *)SvANY(ret_x);
(void)ReREFCNT_inc(rx);
/* We can take advantage of the existing "copied buffer" mechanism in SVs
by pointing directly at the buffer, but flagging that the allocated
space in the copy is zero. As we've just done a struct copy, it's now
a case of zero-ing that, rather than copying the current length. */
SvPV_set(ret_x, RX_WRAPPED(rx));
SvFLAGS(ret_x) |= SvFLAGS(rx) & (SVf_POK|SVp_POK|SVf_UTF8);
memcpy(&(ret->xpv_cur), &(r->xpv_cur),
sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
SvLEN_set(ret_x, 0);
SvSTASH_set(ret_x, NULL);
SvMAGIC_set(ret_x, NULL);
Newx(ret->offs, npar, regexp_paren_pair);
Copy(r->offs, ret->offs, npar, regexp_paren_pair);
if (r->substrs) {
Newx(ret->substrs, 1, struct reg_substr_data);
StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
SvREFCNT_inc_void(ret->anchored_substr);
SvREFCNT_inc_void(ret->anchored_utf8);
SvREFCNT_inc_void(ret->float_substr);
SvREFCNT_inc_void(ret->float_utf8);
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
}
RX_MATCH_COPIED_off(ret_x);
#ifdef PERL_OLD_COPY_ON_WRITE
ret->saved_copy = NULL;
#endif
ret->mother_re = rx;
return ret_x;
}
#endif
/* regfree_internal()
Free the private data in a regexp. This is overloadable by
extensions. Perl takes care of the regexp structure in pregfree(),
this covers the *pprivate pointer which technically perldoesnt
know about, however of course we have to handle the
regexp_internal structure when no extension is in use.
Note this is called before freeing anything in the regexp
structure.
*/
void
Perl_regfree_internal(pTHX_ REGEXP * const rx)
{
dVAR;
struct regexp *const r = (struct regexp *)SvANY(rx);
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_REGFREE_INTERNAL;
DEBUG_COMPILE_r({
if (!PL_colorset)
reginitcolors();
{
SV *dsv= sv_newmortal();
RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n",
PL_colors[4],PL_colors[5],s);
}
});
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets)
Safefree(ri->u.offsets); /* 20010421 MJD */
#endif
if (ri->data) {
int n = ri->data->count;
PAD* new_comppad = NULL;
PAD* old_comppad;
PADOFFSET refcnt;
while (--n >= 0) {
/* If you add a ->what type here, update the comment in regcomp.h */
switch (ri->data->what[n]) {
case 's':
case 'S':
case 'u':
SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
break;
case 'f':
Safefree(ri->data->data[n]);
break;
case 'p':
new_comppad = MUTABLE_AV(ri->data->data[n]);
break;
case 'o':
if (new_comppad == NULL)
Perl_croak(aTHX_ "panic: pregfree comppad");
PAD_SAVE_LOCAL(old_comppad,
/* Watch out for global destruction's random ordering. */
(SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
);
OP_REFCNT_LOCK;
refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
OP_REFCNT_UNLOCK;
if (!refcnt)
op_free((OP_4tree*)ri->data->data[n]);
PAD_RESTORE_LOCAL(old_comppad);
SvREFCNT_dec(MUTABLE_SV(new_comppad));
new_comppad = NULL;
break;
case 'n':
break;
case 'T':
{ /* Aho Corasick add-on structure for a trie node.
Used in stclass optimization only */
U32 refcount;
reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
OP_REFCNT_LOCK;
refcount = --aho->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(aho->states);
PerlMemShared_free(aho->fail);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
PerlMemShared_free(ri->regstclass);
}
}
break;
case 't':
{
/* trie structure. */
U32 refcount;
reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
OP_REFCNT_LOCK;
refcount = --trie->refcount;
OP_REFCNT_UNLOCK;
if ( !refcount ) {
PerlMemShared_free(trie->charmap);
PerlMemShared_free(trie->states);
PerlMemShared_free(trie->trans);
if (trie->bitmap)
PerlMemShared_free(trie->bitmap);
if (trie->wordlen)
PerlMemShared_free(trie->wordlen);
if (trie->jump)
PerlMemShared_free(trie->jump);
if (trie->nextword)
PerlMemShared_free(trie->nextword);
/* do this last!!!! */
PerlMemShared_free(ri->data->data[n]);
}
}
break;
default:
Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
}
}
Safefree(ri->data->what);
Safefree(ri->data);
}
Safefree(ri);
}
#define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
#define av_dup_inc(s,t) MUTABLE_AV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
#define hv_dup_inc(s,t) MUTABLE_HV(SvREFCNT_inc(sv_dup((const SV *)s,t)))
#define SAVEPVN(p,n) ((p) ? savepvn(p,n) : NULL)
/*
re_dup - duplicate a regexp.
This routine is expected to clone a given regexp structure. It is only
compiled under USE_ITHREADS.
After all of the core data stored in struct regexp is duplicated
the regexp_engine.dupe method is used to copy any private data
stored in the *pprivate pointer. This allows extensions to handle
any duplication it needs to do.
See pregfree() and regfree_internal() if you change anything here.
*/
#if defined(USE_ITHREADS)
#ifndef PERL_IN_XSUB_RE
void
Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
{
dVAR;
I32 npar;
const struct regexp *r = (const struct regexp *)SvANY(sstr);
struct regexp *ret = (struct regexp *)SvANY(dstr);
PERL_ARGS_ASSERT_RE_DUP_GUTS;
npar = r->nparens+1;
Newx(ret->offs, npar, regexp_paren_pair);
Copy(r->offs, ret->offs, npar, regexp_paren_pair);
if(ret->swap) {
/* no need to copy these */
Newx(ret->swap, npar, regexp_paren_pair);
}
if (ret->substrs) {
/* Do it this way to avoid reading from *r after the StructCopy().
That way, if any of the sv_dup_inc()s dislodge *r from the L1
cache, it doesn't matter. */
const bool anchored = r->check_substr
? r->check_substr == r->anchored_substr
: r->check_utf8 == r->anchored_utf8;
Newx(ret->substrs, 1, struct reg_substr_data);
StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
ret->float_substr = sv_dup_inc(ret->float_substr, param);
ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
/* check_substr and check_utf8, if non-NULL, point to either their
anchored or float namesakes, and don't hold a second reference. */
if (ret->check_substr) {
if (anchored) {
assert(r->check_utf8 == r->anchored_utf8);
ret->check_substr = ret->anchored_substr;
ret->check_utf8 = ret->anchored_utf8;
} else {
assert(r->check_substr == r->float_substr);
assert(r->check_utf8 == r->float_utf8);
ret->check_substr = ret->float_substr;
ret->check_utf8 = ret->float_utf8;
}
} else if (ret->check_utf8) {
if (anchored) {
ret->check_utf8 = ret->anchored_utf8;
} else {
ret->check_utf8 = ret->float_utf8;
}
}
}
RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
if (ret->pprivate)
RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
if (RX_MATCH_COPIED(dstr))
ret->subbeg = SAVEPVN(ret->subbeg, ret->sublen);
else
ret->subbeg = NULL;
#ifdef PERL_OLD_COPY_ON_WRITE
ret->saved_copy = NULL;
#endif
if (ret->mother_re) {
if (SvPVX_const(dstr) == SvPVX_const(ret->mother_re)) {
/* Our storage points directly to our mother regexp, but that's
1: a buffer in a different thread
2: something we no longer hold a reference on
so we need to copy it locally. */
/* Note we need to sue SvCUR() on our mother_re, because it, in
turn, may well be pointing to its own mother_re. */
SvPV_set(dstr, SAVEPVN(SvPVX_const(ret->mother_re),
SvCUR(ret->mother_re)+1));
SvLEN_set(dstr, SvCUR(ret->mother_re)+1);
}
ret->mother_re = NULL;
}
ret->gofs = 0;
}
#endif /* PERL_IN_XSUB_RE */
/*
regdupe_internal()
This is the internal complement to regdupe() which is used to copy
the structure pointed to by the *pprivate pointer in the regexp.
This is the core version of the extension overridable cloning hook.
The regexp structure being duplicated will be copied by perl prior
to this and will be provided as the regexp *r argument, however
with the /old/ structures pprivate pointer value. Thus this routine
may override any copying normally done by perl.
It returns a pointer to the new regexp_internal structure.
*/
void *
Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
{
dVAR;
struct regexp *const r = (struct regexp *)SvANY(rx);
regexp_internal *reti;
int len, npar;
RXi_GET_DECL(r,ri);
PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
npar = r->nparens+1;
len = ProgLen(ri);
Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
Copy(ri->program, reti->program, len+1, regnode);
reti->regstclass = NULL;
if (ri->data) {
struct reg_data *d;
const int count = ri->data->count;
int i;
Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
char, struct reg_data);
Newx(d->what, count, U8);
d->count = count;
for (i = 0; i < count; i++) {
d->what[i] = ri->data->what[i];
switch (d->what[i]) {
/* legal options are one of: sSfpontTu
see also regcomp.h and pregfree() */
case 's':
case 'S':
case 'p': /* actually an AV, but the dup function is identical. */
case 'u': /* actually an HV, but the dup function is identical. */
d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
break;
case 'f':
/* This is cheating. */
Newx(d->data[i], 1, struct regnode_charclass_class);
StructCopy(ri->data->data[i], d->data[i],
struct regnode_charclass_class);
reti->regstclass = (regnode*)d->data[i];
break;
case 'o':
/* Compiled op trees are readonly and in shared memory,
and can thus be shared without duplication. */
OP_REFCNT_LOCK;
d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
OP_REFCNT_UNLOCK;
break;
case 'T':
/* Trie stclasses are readonly and can thus be shared
* without duplication. We free the stclass in pregfree
* when the corresponding reg_ac_data struct is freed.
*/
reti->regstclass= ri->regstclass;
/* Fall through */
case 't':
OP_REFCNT_LOCK;
((reg_trie_data*)ri->data->data[i])->refcount++;
OP_REFCNT_UNLOCK;
/* Fall through */
case 'n':
d->data[i] = ri->data->data[i];
break;
default:
Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
}
}
reti->data = d;
}
else
reti->data = NULL;
reti->name_list_idx = ri->name_list_idx;
#ifdef RE_TRACK_PATTERN_OFFSETS
if (ri->u.offsets) {
Newx(reti->u.offsets, 2*len+1, U32);
Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
}
#else
SetProgLen(reti,len);
#endif
return (void*)reti;
}
#endif /* USE_ITHREADS */
#ifndef PERL_IN_XSUB_RE
/*
- regnext - dig the "next" pointer out of a node
*/
regnode *
Perl_regnext(pTHX_ register regnode *p)
{
dVAR;
register I32 offset;
if (!p)
return(NULL);
offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
if (offset == 0)
return(NULL);
return(p+offset);
}
#endif
STATIC void
S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
{
va_list args;
STRLEN l1 = strlen(pat1);
STRLEN l2 = strlen(pat2);
char buf[512];
SV *msv;
const char *message;
PERL_ARGS_ASSERT_RE_CROAK2;
if (l1 > 510)
l1 = 510;
if (l1 + l2 > 510)
l2 = 510 - l1;
Copy(pat1, buf, l1 , char);
Copy(pat2, buf + l1, l2 , char);
buf[l1 + l2] = '\n';
buf[l1 + l2 + 1] = '\0';
#ifdef I_STDARG
/* ANSI variant takes additional second argument */
va_start(args, pat2);
#else
va_start(args);
#endif
msv = vmess(buf, &args);
va_end(args);
message = SvPV_const(msv,l1);
if (l1 > 512)
l1 = 512;
Copy(message, buf, l1 , char);
buf[l1-1] = '\0'; /* Overwrite \n */
Perl_croak(aTHX_ "%s", buf);
}
/* XXX Here's a total kludge. But we need to re-enter for swash routines. */
#ifndef PERL_IN_XSUB_RE
void
Perl_save_re_context(pTHX)
{
dVAR;
struct re_save_state *state;
SAVEVPTR(PL_curcop);
SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
SSPUSHINT(SAVEt_RE_STATE);
Copy(&PL_reg_state, state, 1, struct re_save_state);
PL_reg_start_tmp = 0;
PL_reg_start_tmpl = 0;
PL_reg_oldsaved = NULL;
PL_reg_oldsavedlen = 0;
PL_reg_maxiter = 0;
PL_reg_leftiter = 0;
PL_reg_poscache = NULL;
PL_reg_poscache_size = 0;
#ifdef PERL_OLD_COPY_ON_WRITE
PL_nrs = NULL;
#endif
/* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
if (PL_curpm) {
const REGEXP * const rx = PM_GETRE(PL_curpm);
if (rx) {
U32 i;
for (i = 1; i <= RX_NPARENS(rx); i++) {
char digits[TYPE_CHARS(long)];
const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
GV *const *const gvp
= (GV**)hv_fetch(PL_defstash, digits, len, 0);
if (gvp) {
GV * const gv = *gvp;
if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
save_scalar(gv);
}
}
}
}
}
#endif
static void
clear_re(pTHX_ void *r)
{
dVAR;
ReREFCNT_dec((REGEXP *)r);
}
#ifdef DEBUGGING
STATIC void
S_put_byte(pTHX_ SV *sv, int c)
{
PERL_ARGS_ASSERT_PUT_BYTE;
/* Our definition of isPRINT() ignores locales, so only bytes that are
not part of UTF-8 are considered printable. I assume that the same
holds for UTF-EBCDIC.
Also, code point 255 is not printable in either (it's E0 in EBCDIC,
which Wikipedia says:
EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
ones (binary 1111 1111, hexadecimal FF). It is similar, but not
identical, to the ASCII delete (DEL) or rubout control character.
) So the old condition can be simplified to !isPRINT(c) */
if (!isPRINT(c))
Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
else {
const char string = c;
if (c == '-' || c == ']' || c == '\\' || c == '^')
sv_catpvs(sv, "\\");
sv_catpvn(sv, &string, 1);
}
}
#define CLEAR_OPTSTART \
if (optstart) STMT_START { \
DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
optstart=NULL; \
} STMT_END
#define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
STATIC const regnode *
S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
const regnode *last, const regnode *plast,
SV* sv, I32 indent, U32 depth)
{
dVAR;
register U8 op = PSEUDO; /* Arbitrary non-END op. */
register const regnode *next;
const regnode *optstart= NULL;
RXi_GET_DECL(r,ri);
GET_RE_DEBUG_FLAGS_DECL;
PERL_ARGS_ASSERT_DUMPUNTIL;
#ifdef DEBUG_DUMPUNTIL
PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
last ? last-start : 0,plast ? plast-start : 0);
#endif
if (plast && plast < last)
last= plast;
while (PL_regkind[op] != END && (!last || node < last)) {
/* While that wasn't END last time... */
NODE_ALIGN(node);
op = OP(node);
if (op == CLOSE || op == WHILEM)
indent--;
next = regnext((regnode *)node);
/* Where, what. */
if (OP(node) == OPTIMIZED) {
if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
optstart = node;
else
goto after_print;
} else
CLEAR_OPTSTART;
regprop(r, sv, node);
PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
(int)(2*indent + 1), "", SvPVX_const(sv));
if (OP(node) != OPTIMIZED) {
if (next == NULL) /* Next ptr. */
PerlIO_printf(Perl_debug_log, " (0)");
else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
PerlIO_printf(Perl_debug_log, " (FAIL)");
else
PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
(void)PerlIO_putc(Perl_debug_log, '\n');
}
after_print:
if (PL_regkind[(U8)op] == BRANCHJ) {
assert(next);
{
register const regnode *nnode = (OP(next) == LONGJMP
? regnext((regnode *)next)
: next);
if (last && nnode > last)
nnode = last;
DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
}
}
else if (PL_regkind[(U8)op] == BRANCH) {
assert(next);
DUMPUNTIL(NEXTOPER(node), next);
}
else if ( PL_regkind[(U8)op] == TRIE ) {
const regnode *this_trie = node;
const char op = OP(node);
const U32 n = ARG(node);
const reg_ac_data * const ac = op>=AHOCORASICK ?
(reg_ac_data *)ri->data->data[n] :
NULL;
const reg_trie_data * const trie =
(reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
#ifdef DEBUGGING
AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
#endif
const regnode *nextbranch= NULL;
I32 word_idx;
sv_setpvs(sv, "");
for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
PerlIO_printf(Perl_debug_log, "%*s%s ",
(int)(2*(indent+3)), "",
elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
PL_colors[0], PL_colors[1],
(SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
PERL_PV_PRETTY_ELLIPSES |
PERL_PV_PRETTY_LTGT
)
: "???"
);
if (trie->jump) {
U16 dist= trie->jump[word_idx+1];
PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
(UV)((dist ? this_trie + dist : next) - start));
if (dist) {
if (!nextbranch)
nextbranch= this_trie + trie->jump[0];
DUMPUNTIL(this_trie + dist, nextbranch);
}
if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
nextbranch= regnext((regnode *)nextbranch);
} else {
PerlIO_printf(Perl_debug_log, "\n");
}
}
if (last && next > last)
node= last;
else
node= next;
}
else if ( op == CURLY ) { /* "next" might be very big: optimizer */
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
}
else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
assert(next);
DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
}
else if ( op == PLUS || op == STAR) {
DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
}
else if (op == ANYOF) {
/* arglen 1 + class block */
node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
? ANYOF_CLASS_SKIP : ANYOF_SKIP);
node = NEXTOPER(node);
}
else if (PL_regkind[(U8)op] == EXACT) {
/* Literal string, where present. */
node += NODE_SZ_STR(node) - 1;
node = NEXTOPER(node);
}
else {
node = NEXTOPER(node);
node += regarglen[(U8)op];
}
if (op == CURLYX || op == OPEN)
indent++;
}
CLEAR_OPTSTART;
#ifdef DEBUG_DUMPUNTIL
PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
#endif
return node;
}
#endif /* DEBUGGING */
/*
* Local variables:
* c-indentation-style: bsd
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*
* ex: set ts=8 sts=4 sw=4 noet:
*/
|
./openacc-vv/data_create.F90 | #ifndef T1
!T1:data,data_region,construct-independent,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
b = 0
c = 0
!$acc data create(b(1:LOOPCOUNT))
!$acc data copyin(a(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
b(x) = a(x)
END DO
!$acc end parallel
!$acc end data
!$acc data copyout(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = b(x)
END DO
!$acc end parallel
!$acc end data
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(a(x) - c(x)) .gt. PRECISION) THEN
errors = errors + 1
EXIT
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
#ifndef T2
!T2:data,data_region,construct-independent,V:1.0-2.7
LOGICAL FUNCTION test2()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
b = 0
c = 0
!$acc data present_or_create(b(1:LOOPCOUNT))
!$acc data copyin(a(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
b(x) = a(x)
END DO
!$acc end parallel
!$acc end data
!$acc data copyout(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = b(x)
END DO
!$acc end parallel
!$acc end data
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(a(x) - c(x)) .gt. PRECISION) THEN
errors = errors + 2
EXIT
END IF
END DO
IF (errors .eq. 0) THEN
test2 = .FALSE.
ELSE
test2 = .TRUE.
END IF
END
#endif
#ifndef T3
!T3:data,data_region,construct-independent,V:1.0-2.7
LOGICAL FUNCTION test3()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
b = 0
c = 0
!$acc data pcreate(b(1:LOOPCOUNT))
!$acc data copyin(a(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
b(x) = a(x)
END DO
!$acc end parallel
!$acc end data
!$acc data copyout(c(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = b(x)
END DO
!$acc end parallel
!$acc end data
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(a(x) - c(x)) .gt. PRECISION) THEN
errors = errors + 4
EXIT
END IF
END DO
IF (errors .eq. 0) THEN
test3 = .FALSE.
ELSE
test3 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
#ifndef T2
LOGICAL :: test2
#endif
#ifndef T3
LOGICAL :: test3
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
#ifndef T2
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test2()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 1
failed = .FALSE.
END IF
#endif
#ifndef T3
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test3()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 2
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/parallel_loop_reduction_bitand_general.c | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
n = 10;
unsigned int * a = (unsigned int *)malloc(n * sizeof(unsigned int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
unsigned int b;
unsigned int host_b;
for (int x = 0; x < n; ++x){
a[x] = 0;
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX < false_margin){
for (int z = 0; z < y; ++z){
temp *= 2;
}
a[x] += temp;
temp = 1;
}
}
}
b = a[0];
host_b = a[0];
#pragma acc data copyin(a[0:n])
{
#pragma acc parallel loop reduction(&:b)
for (int x = 0; x < n; ++x){
b = b & a[x];
}
}
for (int x = 1; x < n; ++x){
host_b = host_b & a[x];
}
if (b != host_b){
err = 1;
}
return err;
}
#endif
#ifndef T2
//T2:parallel,reduction,combined-constructs,loop,V:2.7-2.7
int test2(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int device[10];
unsigned int host[10];
for (int x = 0; x < 10 * n; ++x) {
a[x] = 0;
for (int y = 0; y < 16; ++y){
if (rand() / (real_t)RAND_MAX < false_margin) {
a[x] += 1<<y;
}
}
}
for (int x = 0; x < 10; ++x) {
device[x] = 0;
host[x] = 0;
for (int y = 0; y < 16; ++y) {
device[x] += 1<<y;
host[x] += 1<<y;
}
}
#pragma acc data copyin(a[0:10*n])
{
#pragma acc parallel loop reduction(&:device)
for (int x = 0; x < 10 * n; ++x) {
device[x%10] = device[x%10] & a[x];
}
}
for (int x = 0; x < 10 * n; ++x) {
host[x%10] = host[x%10] & a[x];
}
for (int x = 0; x < 10; ++x) {
if (host[x] != device[x]) {
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
return failcode;
}
|
./openacc-npb/BT/BT/rhs.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB BT code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
//// //
//// The OpenACC C version of the NAS BT code is developed by the //
//// HPCTools Group of University of Houston and derived from the serial //
//// C version developed by SNU and Fortran versions in "NPB3.3-SER" //
//// developed by NAS. //
//// //
//// Permission to use, copy, distribute and modify this software for any //
//// purpose with or without fee is hereby granted. This software is //
//// provided "as is" without express or implied warranty. //
//// //
//// Send comments or suggestions for this OpenACC version to //
//// hpctools@cs.uh.edu //
////
//// Information on NPB 3.3, including the technical report, the original //
//// specifications, source code, results and information on how to submit //
//// new results, is available at: //
//// //
//// http://www.nas.nasa.gov/Software/NPB/ //
//// //
////-------------------------------------------------------------------------//
//
////-------------------------------------------------------------------------//
//// Authors: Rengan Xu, Sunita Chandrasekaran, Barbara Chapman //
////-------------------------------------------------------------------------//
#include "header.h"
//#include "timers.h"
#include<stdio.h>
void compute_rhs()
{
int i, j, k, m;
double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1;
int gp0, gp1, gp2;
int gp01,gp11,gp21;
int gp02,gp12,gp22;
gp0 = grid_points[0];
gp1 = grid_points[1];
gp2 = grid_points[2];
gp01 = grid_points[0]-1;
gp11 = grid_points[1]-1;
gp21 = grid_points[2]-1;
gp02 = grid_points[0]-2;
gp12 = grid_points[1]-2;
gp22 = grid_points[2]-2;
// printf("gp01=%d, gp11=%d\n", gp01, gp11);
// printf("gp21=%d, gp02=%d\n", gp21, gp02);
// printf("gp12=%d, gp22=%d\n", gp12, gp22);
//---------------------------------------------------------------------
// compute the reciprocal of density, and the kinetic energy,
// and the speed of sound.
//---------------------------------------------------------------------
#pragma acc data present(forcing,rho_i,u,us,vs,ws,square,qs,rhs)
{
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 0; k <= gp21; k++) {
#pragma acc loop worker
for (j = 0; j <= gp11; j++) {
#pragma acc loop vector
for (i = 0; i <= gp01; i++) {
rho_inv = 1.0/u[0][k][j][i];
rho_i[k][j][i] = rho_inv;
us[k][j][i] = u[1][k][j][i] * rho_inv;
vs[k][j][i] = u[2][k][j][i] * rho_inv;
ws[k][j][i] = u[3][k][j][i] * rho_inv;
square[k][j][i] = 0.5* (
u[1][k][j][i]*u[1][k][j][i] +
u[2][k][j][i]*u[2][k][j][i] +
u[3][k][j][i]*u[3][k][j][i] ) * rho_inv;
qs[k][j][i] = square[k][j][i] * rho_inv;
}
}
}
//---------------------------------------------------------------------
// copy the exact forcingterm to the right hand side; because
// this forcingterm is known, we can store it on the whole grid
// including the boundary
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 0; k <= gp21; k++) {
#pragma acc loop worker
for (j = 0; j <= gp11; j++) {
#pragma acc loop vector
for (i = 0; i <= gp01; i++) {
rhs[0][k][j][i] = forcing[0][k][j][i];
rhs[1][k][j][i] = forcing[1][k][j][i];
rhs[2][k][j][i] = forcing[2][k][j][i];
rhs[3][k][j][i] = forcing[3][k][j][i];
rhs[4][k][j][i] = forcing[4][k][j][i];
}
}
}
//---------------------------------------------------------------------
// compute xi-direction fluxes
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
uijk = us[k][j][i];
up1 = us[k][j][i+1];
um1 = us[k][j][i-1];
rhs[0][k][j][i] = rhs[0][k][j][i] + dx1tx1 *
(u[0][k][j][i+1] - 2.0*u[0][k][j][i] +
u[0][k][j][i-1]) -
tx2 * (u[1][k][j][i+1] - u[1][k][j][i-1]);
rhs[1][k][j][i] = rhs[1][k][j][i] + dx2tx1 *
(u[1][k][j][i+1] - 2.0*u[1][k][j][i] +
u[1][k][j][i-1]) +
xxcon2*con43 * (up1 - 2.0*uijk + um1) -
tx2 * (u[1][k][j][i+1]*up1 -
u[1][k][j][i-1]*um1 +
(u[4][k][j][i+1]- square[k][j][i+1]-
u[4][k][j][i-1]+ square[k][j][i-1])*
c2);
rhs[2][k][j][i] = rhs[2][k][j][i] + dx3tx1 *
(u[2][k][j][i+1] - 2.0*u[2][k][j][i] +
u[2][k][j][i-1]) +
xxcon2 * (vs[k][j][i+1] - 2.0*vs[k][j][i] +
vs[k][j][i-1]) -
tx2 * (u[2][k][j][i+1]*up1 -
u[2][k][j][i-1]*um1);
rhs[3][k][j][i] = rhs[3][k][j][i] + dx4tx1 *
(u[3][k][j][i+1] - 2.0*u[3][k][j][i] +
u[3][k][j][i-1]) +
xxcon2 * (ws[k][j][i+1] - 2.0*ws[k][j][i] +
ws[k][j][i-1]) -
tx2 * (u[3][k][j][i+1]*up1 -
u[3][k][j][i-1]*um1);
rhs[4][k][j][i] = rhs[4][k][j][i] + dx5tx1 *
(u[4][k][j][i+1] - 2.0*u[4][k][j][i] +
u[4][k][j][i-1]) +
xxcon3 * (qs[k][j][i+1] - 2.0*qs[k][j][i] +
qs[k][j][i-1]) +
xxcon4 * (up1*up1 - 2.0*uijk*uijk +
um1*um1) +
xxcon5 * (u[4][k][j][i+1]*rho_i[k][j][i+1] -
2.0*u[4][k][j][i]*rho_i[k][j][i] +
u[4][k][j][i-1]*rho_i[k][j][i-1]) -
tx2 * ( (c1*u[4][k][j][i+1] -
c2*square[k][j][i+1])*up1 -
(c1*u[4][k][j][i-1] -
c2*square[k][j][i-1])*um1 );
}
}
}
//---------------------------------------------------------------------
// add fourth order xi-direction dissipation
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker vector
for (j = 1; j <= gp12; j++) {
i = 1;
rhs[0][k][j][i] = rhs[0][k][j][i]- dssp *
( 5.0*u[0][k][j][i] - 4.0*u[0][k][j][i+1] +
u[0][k][j][i+2]);
rhs[1][k][j][i] = rhs[1][k][j][i]- dssp *
( 5.0*u[1][k][j][i] - 4.0*u[1][k][j][i+1] +
u[1][k][j][i+2]);
rhs[2][k][j][i] = rhs[2][k][j][i]- dssp *
( 5.0*u[2][k][j][i] - 4.0*u[2][k][j][i+1] +
u[2][k][j][i+2]);
rhs[3][k][j][i] = rhs[3][k][j][i]- dssp *
( 5.0*u[3][k][j][i] - 4.0*u[3][k][j][i+1] +
u[3][k][j][i+2]);
rhs[4][k][j][i] = rhs[4][k][j][i]- dssp *
( 5.0*u[4][k][j][i] - 4.0*u[4][k][j][i+1] +
u[4][k][j][i+2]);
i = 2;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
(-4.0*u[0][k][j][i-1] + 6.0*u[0][k][j][i] -
4.0*u[0][k][j][i+1] + u[0][k][j][i+2]);
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
(-4.0*u[1][k][j][i-1] + 6.0*u[1][k][j][i] -
4.0*u[1][k][j][i+1] + u[1][k][j][i+2]);
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
(-4.0*u[2][k][j][i-1] + 6.0*u[2][k][j][i] -
4.0*u[2][k][j][i+1] + u[2][k][j][i+2]);
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
(-4.0*u[3][k][j][i-1] + 6.0*u[3][k][j][i] -
4.0*u[3][k][j][i+1] + u[3][k][j][i+2]);
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
(-4.0*u[4][k][j][i-1] + 6.0*u[4][k][j][i] -
4.0*u[4][k][j][i+1] + u[4][k][j][i+2]);
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 3; i <= gp02-2; i++) {
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp*
( u[0][k][j][i-2] - 4.0*u[0][k][j][i-1] +
6.0*u[0][k][j][i] - 4.0*u[0][k][j][i+1] +
u[0][k][j][i+2] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp*
( u[1][k][j][i-2] - 4.0*u[1][k][j][i-1] +
6.0*u[1][k][j][i] - 4.0*u[1][k][j][i+1] +
u[1][k][j][i+2] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp*
( u[2][k][j][i-2] - 4.0*u[2][k][j][i-1] +
6.0*u[2][k][j][i] - 4.0*u[2][k][j][i+1] +
u[2][k][j][i+2] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp*
( u[3][k][j][i-2] - 4.0*u[3][k][j][i-1] +
6.0*u[3][k][j][i] - 4.0*u[3][k][j][i+1] +
u[3][k][j][i+2] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp*
( u[4][k][j][i-2] - 4.0*u[4][k][j][i-1] +
6.0*u[4][k][j][i] - 4.0*u[4][k][j][i+1] +
u[4][k][j][i+2] );
}
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker vector
for (j = 1; j <= gp12; j++) {
i = gp0-3;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k][j][i-2] - 4.0*u[0][k][j][i-1] +
6.0*u[0][k][j][i] - 4.0*u[0][k][j][i+1] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k][j][i-2] - 4.0*u[1][k][j][i-1] +
6.0*u[1][k][j][i] - 4.0*u[1][k][j][i+1] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k][j][i-2] - 4.0*u[2][k][j][i-1] +
6.0*u[2][k][j][i] - 4.0*u[2][k][j][i+1] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k][j][i-2] - 4.0*u[3][k][j][i-1] +
6.0*u[3][k][j][i] - 4.0*u[3][k][j][i+1] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k][j][i-2] - 4.0*u[4][k][j][i-1] +
6.0*u[4][k][j][i] - 4.0*u[4][k][j][i+1] );
i = gp02;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k][j][i-2] - 4.*u[0][k][j][i-1] +
5.*u[0][k][j][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k][j][i-2] - 4.*u[1][k][j][i-1] +
5.*u[1][k][j][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k][j][i-2] - 4.*u[2][k][j][i-1] +
5.*u[2][k][j][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k][j][i-2] - 4.*u[3][k][j][i-1] +
5.*u[3][k][j][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k][j][i-2] - 4.*u[4][k][j][i-1] +
5.*u[4][k][j][i] );
}
}
//---------------------------------------------------------------------
// compute eta-direction fluxes
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
vijk = vs[k][j][i];
vp1 = vs[k][j+1][i];
vm1 = vs[k][j-1][i];
rhs[0][k][j][i] = rhs[0][k][j][i] + dy1ty1 *
(u[0][k][j+1][i] - 2.0*u[0][k][j][i] +
u[0][k][j-1][i]) -
ty2 * (u[2][k][j+1][i] - u[2][k][j-1][i]);
rhs[1][k][j][i] = rhs[1][k][j][i] + dy2ty1 *
(u[1][k][j+1][i] - 2.0*u[1][k][j][i] +
u[1][k][j-1][i]) +
yycon2 * (us[k][j+1][i] - 2.0*us[k][j][i] +
us[k][j-1][i]) -
ty2 * (u[1][k][j+1][i]*vp1 -
u[1][k][j-1][i]*vm1);
rhs[2][k][j][i] = rhs[2][k][j][i] + dy3ty1 *
(u[2][k][j+1][i] - 2.0*u[2][k][j][i] +
u[2][k][j-1][i]) +
yycon2*con43 * (vp1 - 2.0*vijk + vm1) -
ty2 * (u[2][k][j+1][i]*vp1 -
u[2][k][j-1][i]*vm1 +
(u[4][k][j+1][i] - square[k][j+1][i] -
u[4][k][j-1][i] + square[k][j-1][i])
*c2);
rhs[3][k][j][i] = rhs[3][k][j][i] + dy4ty1 *
(u[3][k][j+1][i] - 2.0*u[3][k][j][i] +
u[3][k][j-1][i]) +
yycon2 * (ws[k][j+1][i] - 2.0*ws[k][j][i] +
ws[k][j-1][i]) -
ty2 * (u[3][k][j+1][i]*vp1 -
u[3][k][j-1][i]*vm1);
rhs[4][k][j][i] = rhs[4][k][j][i] + dy5ty1 *
(u[4][k][j+1][i] - 2.0*u[4][k][j][i] +
u[4][k][j-1][i]) +
yycon3 * (qs[k][j+1][i] - 2.0*qs[k][j][i] +
qs[k][j-1][i]) +
yycon4 * (vp1*vp1 - 2.0*vijk*vijk +
vm1*vm1) +
yycon5 * (u[4][k][j+1][i]*rho_i[k][j+1][i] -
2.0*u[4][k][j][i]*rho_i[k][j][i] +
u[4][k][j-1][i]*rho_i[k][j-1][i]) -
ty2 * ((c1*u[4][k][j+1][i] -
c2*square[k][j+1][i]) * vp1 -
(c1*u[4][k][j-1][i] -
c2*square[k][j-1][i]) * vm1);
}
}
}
//---------------------------------------------------------------------
// add fourth order eta-direction dissipation
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker vector
for (i = 1; i <= gp02; i++) {
j = 1;
rhs[0][k][j][i] = rhs[0][k][j][i]- dssp *
( 5.0*u[0][k][j][i] - 4.0*u[0][k][j+1][i] +
u[0][k][j+2][i]);
rhs[1][k][j][i] = rhs[1][k][j][i]- dssp *
( 5.0*u[1][k][j][i] - 4.0*u[1][k][j+1][i] +
u[1][k][j+2][i]);
rhs[2][k][j][i] = rhs[2][k][j][i]- dssp *
( 5.0*u[2][k][j][i] - 4.0*u[2][k][j+1][i] +
u[2][k][j+2][i]);
rhs[3][k][j][i] = rhs[3][k][j][i]- dssp *
( 5.0*u[3][k][j][i] - 4.0*u[3][k][j+1][i] +
u[3][k][j+2][i]);
rhs[4][k][j][i] = rhs[4][k][j][i]- dssp *
( 5.0*u[4][k][j][i] - 4.0*u[4][k][j+1][i] +
u[4][k][j+2][i]);
j = 2;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
(-4.0*u[0][k][j-1][i] + 6.0*u[0][k][j][i] -
4.0*u[0][k][j+1][i] + u[0][k][j+2][i]);
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
(-4.0*u[1][k][j-1][i] + 6.0*u[1][k][j][i] -
4.0*u[1][k][j+1][i] + u[1][k][j+2][i]);
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
(-4.0*u[2][k][j-1][i] + 6.0*u[2][k][j][i] -
4.0*u[2][k][j+1][i] + u[2][k][j+2][i]);
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
(-4.0*u[3][k][j-1][i] + 6.0*u[3][k][j][i] -
4.0*u[3][k][j+1][i] + u[3][k][j+2][i]);
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
(-4.0*u[4][k][j-1][i] + 6.0*u[4][k][j][i] -
4.0*u[4][k][j+1][i] + u[4][k][j+2][i]);
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 3; j <= gp1-4; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k][j-2][i] - 4.0*u[0][k][j-1][i] +
6.0*u[0][k][j][i] - 4.0*u[0][k][j+1][i] +
u[0][k][j+2][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k][j-2][i] - 4.0*u[1][k][j-1][i] +
6.0*u[1][k][j][i] - 4.0*u[1][k][j+1][i] +
u[1][k][j+2][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k][j-2][i] - 4.0*u[2][k][j-1][i] +
6.0*u[2][k][j][i] - 4.0*u[2][k][j+1][i] +
u[2][k][j+2][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k][j-2][i] - 4.0*u[3][k][j-1][i] +
6.0*u[3][k][j][i] - 4.0*u[3][k][j+1][i] +
u[3][k][j+2][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k][j-2][i] - 4.0*u[4][k][j-1][i] +
6.0*u[4][k][j][i] - 4.0*u[4][k][j+1][i] +
u[4][k][j+2][i] );
}
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker vector
for (i = 1; i <= gp02; i++) {
j = gp1-3;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k][j-2][i] - 4.0*u[0][k][j-1][i] +
6.0*u[0][k][j][i] - 4.0*u[0][k][j+1][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k][j-2][i] - 4.0*u[1][k][j-1][i] +
6.0*u[1][k][j][i] - 4.0*u[1][k][j+1][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k][j-2][i] - 4.0*u[2][k][j-1][i] +
6.0*u[2][k][j][i] - 4.0*u[2][k][j+1][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k][j-2][i] - 4.0*u[3][k][j-1][i] +
6.0*u[3][k][j][i] - 4.0*u[3][k][j+1][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k][j-2][i] - 4.0*u[4][k][j-1][i] +
6.0*u[4][k][j][i] - 4.0*u[4][k][j+1][i] );
j = gp12;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k][j-2][i] - 4.*u[0][k][j-1][i] +
5.*u[0][k][j][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k][j-2][i] - 4.*u[1][k][j-1][i] +
5.*u[1][k][j][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k][j-2][i] - 4.*u[2][k][j-1][i] +
5.*u[2][k][j][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k][j-2][i] - 4.*u[3][k][j-1][i] +
5.*u[3][k][j][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k][j-2][i] - 4.*u[4][k][j-1][i] +
5.*u[4][k][j][i] );
}
}
//---------------------------------------------------------------------
// compute zeta-direction fluxes
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
wijk = ws[k][j][i];
wp1 = ws[k+1][j][i];
wm1 = ws[k-1][j][i];
rhs[0][k][j][i] = rhs[0][k][j][i] + dz1tz1 *
(u[0][k+1][j][i] - 2.0*u[0][k][j][i] +
u[0][k-1][j][i]) -
tz2 * (u[3][k+1][j][i] - u[3][k-1][j][i]);
rhs[1][k][j][i] = rhs[1][k][j][i] + dz2tz1 *
(u[1][k+1][j][i] - 2.0*u[1][k][j][i] +
u[1][k-1][j][i]) +
zzcon2 * (us[k+1][j][i] - 2.0*us[k][j][i] +
us[k-1][j][i]) -
tz2 * (u[1][k+1][j][i]*wp1 -
u[1][k-1][j][i]*wm1);
rhs[2][k][j][i] = rhs[2][k][j][i] + dz3tz1 *
(u[2][k+1][j][i] - 2.0*u[2][k][j][i] +
u[2][k-1][j][i]) +
zzcon2 * (vs[k+1][j][i] - 2.0*vs[k][j][i] +
vs[k-1][j][i]) -
tz2 * (u[2][k+1][j][i]*wp1 -
u[2][k-1][j][i]*wm1);
rhs[3][k][j][i] = rhs[3][k][j][i] + dz4tz1 *
(u[3][k+1][j][i] - 2.0*u[3][k][j][i] +
u[3][k-1][j][i]) +
zzcon2*con43 * (wp1 - 2.0*wijk + wm1) -
tz2 * (u[3][k+1][j][i]*wp1 -
u[3][k-1][j][i]*wm1 +
(u[4][k+1][j][i] - square[k+1][j][i] -
u[4][k-1][j][i] + square[k-1][j][i])
*c2);
rhs[4][k][j][i] = rhs[4][k][j][i] + dz5tz1 *
(u[4][k+1][j][i] - 2.0*u[4][k][j][i] +
u[4][k-1][j][i]) +
zzcon3 * (qs[k+1][j][i] - 2.0*qs[k][j][i] +
qs[k-1][j][i]) +
zzcon4 * (wp1*wp1 - 2.0*wijk*wijk +
wm1*wm1) +
zzcon5 * (u[4][k+1][j][i]*rho_i[k+1][j][i] -
2.0*u[4][k][j][i]*rho_i[k][j][i] +
u[4][k-1][j][i]*rho_i[k-1][j][i]) -
tz2 * ( (c1*u[4][k+1][j][i] -
c2*square[k+1][j][i])*wp1 -
(c1*u[4][k-1][j][i] -
c2*square[k-1][j][i])*wm1);
}
}
}
//---------------------------------------------------------------------
// add fourth order zeta-direction dissipation
//---------------------------------------------------------------------
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (j = 1; j <= gp12; j++) {
#pragma acc loop worker vector
for (i = 1; i <= gp02; i++) {
k = 1;
rhs[0][k][j][i] = rhs[0][k][j][i]- dssp *
( 5.0*u[0][k][j][i] - 4.0*u[0][k+1][j][i] +
u[0][k+2][j][i]);
rhs[1][k][j][i] = rhs[1][k][j][i]- dssp *
( 5.0*u[1][k][j][i] - 4.0*u[1][k+1][j][i] +
u[1][k+2][j][i]);
rhs[2][k][j][i] = rhs[2][k][j][i]- dssp *
( 5.0*u[2][k][j][i] - 4.0*u[2][k+1][j][i] +
u[2][k+2][j][i]);
rhs[3][k][j][i] = rhs[3][k][j][i]- dssp *
( 5.0*u[3][k][j][i] - 4.0*u[3][k+1][j][i] +
u[3][k+2][j][i]);
rhs[4][k][j][i] = rhs[4][k][j][i]- dssp *
( 5.0*u[4][k][j][i] - 4.0*u[4][k+1][j][i] +
u[4][k+2][j][i]);
k = 2;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
(-4.0*u[0][k-1][j][i] + 6.0*u[0][k][j][i] -
4.0*u[0][k+1][j][i] + u[0][k+2][j][i]);
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
(-4.0*u[1][k-1][j][i] + 6.0*u[1][k][j][i] -
4.0*u[1][k+1][j][i] + u[1][k+2][j][i]);
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
(-4.0*u[2][k-1][j][i] + 6.0*u[2][k][j][i] -
4.0*u[2][k+1][j][i] + u[2][k+2][j][i]);
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
(-4.0*u[3][k-1][j][i] + 6.0*u[3][k][j][i] -
4.0*u[3][k+1][j][i] + u[3][k+2][j][i]);
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
(-4.0*u[4][k-1][j][i] + 6.0*u[4][k][j][i] -
4.0*u[4][k+1][j][i] + u[4][k+2][j][i]);
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 3; k <= gp2-4; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k-2][j][i] - 4.0*u[0][k-1][j][i] +
6.0*u[0][k][j][i] - 4.0*u[0][k+1][j][i] +
u[0][k+2][j][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k-2][j][i] - 4.0*u[1][k-1][j][i] +
6.0*u[1][k][j][i] - 4.0*u[1][k+1][j][i] +
u[1][k+2][j][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k-2][j][i] - 4.0*u[2][k-1][j][i] +
6.0*u[2][k][j][i] - 4.0*u[2][k+1][j][i] +
u[2][k+2][j][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k-2][j][i] - 4.0*u[3][k-1][j][i] +
6.0*u[3][k][j][i] - 4.0*u[3][k+1][j][i] +
u[3][k+2][j][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k-2][j][i] - 4.0*u[4][k-1][j][i] +
6.0*u[4][k][j][i] - 4.0*u[4][k+1][j][i] +
u[4][k+2][j][i] );
}
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (j = 1; j <= gp12; j++) {
#pragma acc loop worker vector
for (i = 1; i <= gp02; i++) {
k = gp2-3;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k-2][j][i] - 4.0*u[0][k-1][j][i] +
6.0*u[0][k][j][i] - 4.0*u[0][k+1][j][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k-2][j][i] - 4.0*u[1][k-1][j][i] +
6.0*u[1][k][j][i] - 4.0*u[1][k+1][j][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k-2][j][i] - 4.0*u[2][k-1][j][i] +
6.0*u[2][k][j][i] - 4.0*u[2][k+1][j][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k-2][j][i] - 4.0*u[3][k-1][j][i] +
6.0*u[3][k][j][i] - 4.0*u[3][k+1][j][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k-2][j][i] - 4.0*u[4][k-1][j][i] +
6.0*u[4][k][j][i] - 4.0*u[4][k+1][j][i] );
k = gp22;
rhs[0][k][j][i] = rhs[0][k][j][i] - dssp *
( u[0][k-2][j][i] - 4.*u[0][k-1][j][i] +
5.*u[0][k][j][i] );
rhs[1][k][j][i] = rhs[1][k][j][i] - dssp *
( u[1][k-2][j][i] - 4.*u[1][k-1][j][i] +
5.*u[1][k][j][i] );
rhs[2][k][j][i] = rhs[2][k][j][i] - dssp *
( u[2][k-2][j][i] - 4.*u[2][k-1][j][i] +
5.*u[2][k][j][i] );
rhs[3][k][j][i] = rhs[3][k][j][i] - dssp *
( u[3][k-2][j][i] - 4.*u[3][k-1][j][i] +
5.*u[3][k][j][i] );
rhs[4][k][j][i] = rhs[4][k][j][i] - dssp *
( u[4][k-2][j][i] - 4.*u[4][k-1][j][i] +
5.*u[4][k][j][i] );
}
}
#pragma acc parallel loop gang num_gangs(192) num_workers(16) vector_length(32)
for (k = 1; k <= gp22; k++) {
#pragma acc loop worker
for (j = 1; j <= gp12; j++) {
#pragma acc loop vector
for (i = 1; i <= gp02; i++) {
rhs[0][k][j][i] = rhs[0][k][j][i] * dt;
rhs[1][k][j][i] = rhs[1][k][j][i] * dt;
rhs[2][k][j][i] = rhs[2][k][j][i] * dt;
rhs[3][k][j][i] = rhs[3][k][j][i] * dt;
rhs[4][k][j][i] = rhs[4][k][j][i] * dt;
}
}
}
}/*end acc data*/
}
|
./openacc-vv/parallel_implicit_data_attributes.c | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,data,data-region,V:2.0-3.3
int test1(){
int err = 0;
srand(SEED);
int test = rand()/(real_t)(RAND_MAX/10);
int host = test;
#pragma acc parallel default(none) reduction(+:test)
for(int x = 0; x < n; ++x){
test += 1;
}
if(fabs( test - host) > PRECISION){
err++;
}
return err;
}
#endif
#ifndef T2
//T2:parallel,data,data-region,V:2.0-3.3
int test2(){
int err = 0;
srand(SEED);
real_t a = rand()/(real_t)(RAND_MAX/10);
real_t host = a;
#pragma acc parallel loop reduction(+:a)
for( int x = 0; x < n; ++x){
a += 1.0;
}
if( fabs( a - host) > PRECISION){
err++;
}
return err;
}
#endif
#ifndef T3
//firstprivate test with only parallel and reduction with scalar variable
int test3(){
int err = 0;
srand(SEED);
int host_value = rand()/ (real_t)(RAND_MAX/10);
int device_value = host_value;
#pragma acc parallel reduction(+:device_value)
for( int x = 0; x > n; ++ x){
device_value += device_value;
}
if( fabs(host_value - device_value) > PRECISION){
err = 1;
}
return err;
}
#endif
#ifndef T4
//copy clause wtth that calles detach action only parallel loop with aggregate variables
int test4(){
int err = 0;
srand(SEED);
real_t *host_array = (real_t *)malloc( n * sizeof(real_t));
real_t *device_array = (real_t *)malloc( n * sizeof(real_t));
for(int x = 0; x < n; ++ x){
host_array[x] = rand()/(real_t)(RAND_MAX/10);
device_array[x] = host_array[x];
}
#pragma acc parallel loop
for( int x = 0; x < n; ++x){
device_array[x] += device_array[x];
}
for(int x = 0; x < n; ++x){
if(fabs(host_array[x]*2 - device_array[x]) > PRECISION){
err = 1;
}
}
free(host_array);
free(device_array);
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for( int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test1();
}
if(failed){
failcode += ( 1 << 0);
}
#endif
#ifndef T2
failed = 0;
for( int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test2();
}
if(failed){
failcode += ( 1 << 1);
}
#endif
#ifndef T3
failed = 0;
for( int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test3();
}
if(failed){
failcode += ( 1 << 2);
}
#endif
#ifndef T4
failed = 0;
for( int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test4();
}
if(failed){
failcode += ( 1 << 3);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_x_neqv_expr_end.F90 | #ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: randoms
LOGICAL,DIMENSION(LOOPCOUNT, 10):: a !Data
LOGICAL,DIMENSION(LOOPCOUNT):: totals, totals_comparison
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(randoms)
DO x = 1, LOOPCOUNT
DO y = 1, 10
IF (randoms(x, y) > .5) THEN
a(x, y) = .TRUE.
ELSE
a(x, y) = .FALSE.
END IF
END DO
END DO
totals = .FALSE.
totals_comparison = .FALSE.
!$acc data copyin(a(1:LOOPCOUNT,1:10)) copy(totals(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic
totals(x) = totals(x) .NEQV. a(x, y)
!$acc end atomic
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
totals_comparison(x) = totals_comparison(x) .NEQV. a(x, y)
END DO
END DO
DO x = 1, LOOPCOUNT
IF (totals_comparison(x) .NEQV. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_structured_x_multiply_expr_assign.cpp | #include "acc_testsuite.h"
bool is_possible(real_t* a, real_t* b, int length, real_t prev){
if (length == 0){
return true;
}
real_t *passed_a = new real_t[(length - 1)];
real_t *passed_b = new real_t[(length - 1)];
for (int x = 0; x < length; ++x){
if (fabs(b[x] - (a[x] * prev)) < PRECISION){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, b[x])){
delete[] passed_a;
delete[] passed_b;
return true;
}
}
}
delete[] passed_a;
delete[] passed_b;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *totals = new real_t[(n/10 + 1)];
real_t *totals_comparison = new real_t[(n/10 + 1)];
real_t * passed_ab = new real_t[10];
real_t * passed_c = new real_t[10];
int passed_indexer;
int absolute_indexer;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 1;
totals_comparison[x] = 1;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(totals[0:n/10 + 1]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
totals[x%(n/10 + 1)] = totals[x%(n/10 + 1)] * (a[x] + b[x]);
c[x] = totals[x%(n/10 + 1)];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x%(n/10 + 1)] *= a[x] + b[x];
}
for (int x = 0; x < 10; ++x){
if (fabs(totals_comparison[x] - totals[x]) > PRECISION * totals_comparison[x]){
err += 1;
break;
}
}
for (int x = 0; x < n/10 + 1; ++x){
for (passed_indexer = 0, absolute_indexer = x; absolute_indexer < n; passed_indexer++, absolute_indexer += n/10 + 1){
passed_ab[passed_indexer] = a[absolute_indexer] + b[absolute_indexer];
passed_c[passed_indexer] = c[absolute_indexer];
}
if (!is_possible(passed_ab, passed_c, passed_indexer, 1)){
err++;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./SPEChpc/benchspec/HPC/618.tealeaf_s/src/2d/c_kernels/diffuse_overload.c | #include "../drivers/drivers.h"
#include "../application.h"
#include "../comms.h"
void solve(Chunk* chunks, Settings* settings, int tt, double* wallclock_prev);
// An implementation specific overload of the main timestep loop
void diffuse_overload(Chunk* chunks, Settings* settings)
{
int n = chunks->x*chunks->y;
#ifndef SPEC
print_and_log(settings,
"This implementation overloads the diffuse function.\n");
#endif
// Currently have to place all structure enclose pointers
// into local variables for OMP 4.0 to accept them in mapping clauses
double* r = chunks->r;
double* sd = chunks->sd;
double* kx = chunks->kx;
double* ky = chunks->ky;
double* w = chunks->w;
double* p = chunks->p;
double* cheby_alphas = chunks->cheby_alphas;
double* cheby_betas = chunks->cheby_betas;
double* cg_alphas = chunks->cg_alphas;
double* cg_betas = chunks->cg_betas;
double* energy = chunks->energy;
double* density = chunks->density;
double* energy0 = chunks->energy0;
double* density0 = chunks->density0;
double* u = chunks->u;
double* u0 = chunks->u0;
settings->is_offload = true;
#ifdef SPEC_OPENACC
#pragma acc data \
copyin(r[:n], sd[:n], kx[:n], ky[:n], w[:n], p[:n], \
cheby_alphas[:settings->max_iters], \
cheby_betas[:settings->max_iters], \
cg_alphas[:settings->max_iters], \
cg_betas[:settings->max_iters]) \
copy(density[:n], energy[:n], density0[:n], energy0[:n], u[:n], u0[:n])
#endif
#ifdef SPEC_OPENMP_TARGET
//Fix this when we optimize to, from and update across the app
#pragma omp target data \
map(to: r[:n], sd[:n], kx[:n], ky[:n], w[:n], \
p[:n], cheby_alphas[:settings->max_iters], \
cheby_betas[:settings->max_iters], cg_alphas[:settings->max_iters], \
cg_betas[:settings->max_iters]) \
map(tofrom: density[:n], energy[:n], density0[:n], energy0[:n], \
u[:n], u0[:n])
#endif
{
double wallclock_prev = 0.0;
for(int tt = 0; tt < settings->end_step; ++tt)
{
solve(chunks, settings, tt, &wallclock_prev);
}
}
settings->is_offload = false;
field_summary_driver(chunks, settings, true);
}
|
./openacc-vv/atomic_structured_assign_x_plus_expr.c | #include "acc_testsuite.h"
bool is_possible(real_t* a, real_t* b, int length, real_t prev){
if (length == 0){
return true;
}
real_t *passed_a = (real_t *)malloc((length - 1) * sizeof(real_t));
real_t *passed_b = (real_t *)malloc((length - 1) * sizeof(real_t));
for (int x = 0; x < length; ++x){
if (fabs(b[x] - prev) < PRECISION){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, a[x] + prev)){
free(passed_a);
free(passed_b);
return true;
}
}
}
free(passed_a);
free(passed_b);
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
real_t *c = (real_t *)malloc(n * sizeof(real_t));
real_t *totals = (real_t *)malloc((n/10 + 1) * sizeof(real_t));
real_t *totals_comparison = (real_t *)malloc((n/10 + 1) * sizeof(real_t));
real_t *passed_ab = (real_t *)malloc(10 * sizeof(real_t));
real_t *passed_c = (real_t *)malloc(10 * sizeof(real_t));
int passed_indexer;
int absolute_indexer;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 0;
totals_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(totals[0:n/10 + 1]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
c[x] = totals[x%(n/10 + 1)];
totals[x%(n/10 + 1)] = totals[x%(n/10 + 1)] + (a[x] * b[x]);
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x%(n/10 + 1)] += a[x] * b[x];
}
for (int x = 0; x < n/10 + 1; ++x){
if (fabs(totals_comparison[x] - totals[x]) > PRECISION){
err += 1;
break;
}
}
for (int x = 0; x < n/10 + 1; ++x){
for (passed_indexer = 0, absolute_indexer = x; absolute_indexer < n; passed_indexer++, absolute_indexer+= (n/10 + 1)){
passed_ab[passed_indexer] = a[absolute_indexer] * b[absolute_indexer];
passed_c[passed_indexer] = c[absolute_indexer];
}
if (!is_possible(passed_ab, passed_c, passed_indexer, 0)){
err++;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_reduction_bitand_vector_loop.F90 | #ifndef T1
!T1:kernels,private,reduction,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y, z, i !Iterators
INTEGER,DIMENSION(10*LOOPCOUNT):: a !Data
INTEGER,DIMENSION(10):: b
INTEGER :: c
REAL(8),DIMENSION(160*LOOPCOUNT):: random
REAL(8) :: false_margin
INTEGER :: errors = 0
INTEGER :: temp
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(random)
false_margin = exp(log(.5) / n)
DO x = 0, 9
DO y = 1, LOOPCOUNT
DO z = 1, 16
IF (random(x * 16 * LOOPCOUNT + (y - 1) * 16 + z - 1) < false_margin) THEN
temp = 1
DO i = 1, z
temp = temp * 2
END DO
a(x * LOOPCOUNT + y) = a(x * LOOPCOUNT + y) + temp
END IF
END DO
END DO
END DO
!$acc data copyin(a(1:10*LOOPCOUNT)), copy(b(1:10))
!$acc kernels loop private(c)
DO x = 0, 9
c = a(x * LOOPCOUNT + 1)
!$acc loop vector reduction(iand:c)
DO y = 1, LOOPCOUNT
c = iand(c, a(x * LOOPCOUNT + y))
END DO
b(x + 1) = c
END DO
!$acc end data
DO x = 0, 9
temp = a(x * LOOPCOUNT + 1)
DO y = 2, LOOPCOUNT
temp = iand(temp, a(x * LOOPCOUNT + y))
END DO
IF (b(x + 1) .ne. temp) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/parallel_loop_auto.F90 | #ifndef T1
!T1:parallel,combined-constructs,loop,auto,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, a_copy, b !Data
REAL(8) :: temp
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
a_copy = a
b = 0
!$acc data copyin(a(1:LOOPCOUNT)) copyout(b(1:LOOPCOUNT))
!$acc parallel loop auto
DO x = 1, LOOPCOUNT
b(x) = a(x)
END DO
!$acc end data
DO x = 1, LOOPCOUNT
IF (abs(a(x) - b(x)) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
!$acc data copy(a(1:LOOPCOUNT))
!$acc parallel loop auto
DO x = 2, LOOPCOUNT
a(x) = a(x - 1) + a(x)
END DO
!$acc end data
temp = 0
DO x = 1, LOOPCOUNT
temp = temp + a_copy(x)
IF (abs(temp - a(x)) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_update_expr_divided_x_end.F90 | RECURSIVE FUNCTION IS_POSSIBLE(subset, destination, length, init) RESULT(POSSIBLE)
INTEGER, INTENT(IN) :: length
REAL(8),DIMENSION(length), INTENT(IN) :: subset
REAL(8), INTENT(IN) :: destination
REAL(8), INTENT(IN) :: init
REAL(8),ALLOCATABLE :: passed(:)
LOGICAL :: POSSIBLE
INTEGER :: x, y
IF (length .gt. 0) THEN
ALLOCATE(passed(length - 1))
ELSE
IF (abs(init - destination) .gt. PRECISION) THEN
POSSIBLE = .TRUE.
ELSE
POSSIBLE = .FALSE.
END IF
RETURN
END IF
POSSIBLE = .FALSE.
DO x = 1, length
DO y = 1, x - 1
passed(y) = subset(y)
END DO
DO y = x + 1, length
passed(y - 1) = subset(y)
END DO
IF (IS_POSSIBLE(passed, destination, length - 1, subset(x) / init)) THEN
POSSIBLE = .TRUE.
RETURN
END IF
END DO
END FUNCTION IS_POSSIBLE
#ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: a !Data
REAL(8),DIMENSION(LOOPCOUNT):: totals
REAL(8),DIMENSION(10):: passed
INTEGER :: errors = 0
LOGICAL IS_POSSIBLE
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
totals = 1
!$acc data copyin(a(1:LOOPCOUNT, 1:10)) copy(totals(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic update
totals(x) = a(x, y) / totals(x)
!$acc end atomic
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
passed(y) = a(x, y)
END DO
IF (IS_POSSIBLE(passed, totals(x), 10, 1) .eqv. .FALSE.) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/parallel_scalar_default_firstprivate.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,data,data-region,default-mapping,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t scalar = rand() / (real_t)(RAND_MAX / 10);
real_t scalar_copy = scalar;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0.0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x] + scalar;
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(b[x] - (a[x] + scalar_copy)) > PRECISION){
err += 1;
}
}
if (fabs(scalar_copy - scalar) > PRECISION){
err += 1;
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_capture_x_times_expr_assign.F90 | RECURSIVE FUNCTION IS_POSSIBLE(a, b, length, init) RESULT(POSSIBLE)
INTEGER, INTENT(IN) :: length
REAL(8), INTENT(IN) :: init
REAL(8),DIMENSION(length), INTENT(IN) :: a
REAL(8),DIMENSION(length), INTENT(IN) :: b
REAL(8),DIMENSION(length - 1) :: passed_a
REAL(8),DIMENSION(length - 1) :: passed_b
REAL(8) :: holder
LOGICAL :: POSSIBLE
INTEGER :: x, y
IF (length .eq. 0) THEN
POSSIBLE = .TRUE.
RETURN
END IF
POSSIBLE = .FALSE.
DO x = 1, length
IF (abs(b(x) - (init * a(x))) .GT. ((10 - length) * PRECISION)) THEN
DO y = 1, x - 1
passed_a(y) = a(y)
passed_b(y) = b(y)
END DO
DO y = x + 1, length
passed_a(y - 1) = a(y)
passed_b(y - 1) = b(y)
END DO
holder = b(x)
IF (IS_POSSIBLE(passed_a, passed_b, length - 1, holder)) THEN
POSSIBLE = .TRUE.
RETURN
END IF
END IF
END DO
END FUNCTION IS_POSSIBLE
#ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: a, b !Data
REAL(8),DIMENSION(LOOPCOUNT):: totals, totals_comparison
REAL(8),DIMENSION(10):: passed_a, passed_b
REAL(8):: init
LOGICAL IS_POSSIBLE
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
totals = 1
totals_comparison = 1
!$acc data copyin(a(1:LOOPCOUNT, 1:10)) copy(totals(1:LOOPCOUNT)) copyout(b(1:LOOPCOUNT,1:10))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic capture
totals(x) = totals(x) * a(x, y)
b(x, y) = totals(x)
!$acc end atomic
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
totals_comparison(x) = totals_comparison(x) * a(x, y)
END DO
END DO
DO x = 1, LOOPCOUNT
IF (totals_comparison(x) .NE. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
DO x = 1, LOOPCOUNT
DO y = 1, 10
passed_a(y) = a(x, y)
passed_b(y) = b(x, y)
END DO
init = 1
IF (IS_POSSIBLE(passed_a, passed_b, 10, init) .eqv. .TRUE.) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./SPEChpc/benchspec/HPC/613.soma_s/src/polymer.c | /* Copyright (C) 2016-2017 Ludwig Schneider
This file is part of SOMA.
SOMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SOMA 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 SOMA. If not, see <http://www.gnu.org/licenses/>.
*/
//! \file polymer.c
//! \brief Implementation of polymer.h
#include "polymer.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef SPEC_OPENACC
#include <openacc.h>
#endif//SPEC_OPENACC
#include "phase.h"
#include "allocator.h"
int free_polymer(const struct Phase*const p, Polymer*const poly)
{
deallocate_rng_state(&(poly->poly_state), p->args.pseudo_random_number_generator_arg);
if( poly->set_states != NULL)
{
for(unsigned int j=0; j < p->max_set_members; j++)
{
deallocate_rng_state(poly->set_states+j, p->args.pseudo_random_number_generator_arg);
free(poly->set_states[j].mt_state);
free(poly->set_states[j].tt800_state);
}
free(poly->set_states);
free(poly->set_permutation);
}
return 0;
}
int copyin_polymer(struct Phase*const p, Polymer*const poly)
{
const unsigned int N = p->poly_arch[ p->poly_type_offset[ poly->type ] ];
copyin_rng_state( &(poly->poly_state), p->args.pseudo_random_number_generator_arg);
if(poly->set_permutation !=NULL)
{
#ifdef SPEC_OPENACC
#pragma acc enter data attach(poly->set_permutation)
#endif
#ifdef SPEC_OPENMP_TARGET
#pragma omp target enter data map (to:poly->set_permutation[0:p->max_n_sets])
#endif
}
if(poly->set_states !=NULL)
{
#ifdef SPEC_OPENACC
#pragma acc enter data attach(poly->set_states)
#endif
#ifdef SPEC_OPENMP_TARGET
#pragma omp target enter data map (to:poly->set_states[0:p->max_set_members])
#endif
for(unsigned int j=0; j < p->max_set_members; j++)
{
copyin_rng_state(poly->set_states +j, p->args.pseudo_random_number_generator_arg);
}
}
return 0 + 1*N*0;
}
int copyout_polymer(struct Phase*const p, Polymer*const poly)
{
const unsigned int N = p->poly_arch[ p->poly_type_offset[poly->type] ];
copyout_rng_state(&(poly->poly_state), p->args.pseudo_random_number_generator_arg);
if(poly->set_permutation !=NULL)
{
#ifdef SPEC_OPENMP_TARGET
#pragma omp target exit data map(from:poly->set_permutation[0:p->max_n_sets])
#endif
}
if(poly->set_states !=NULL)
{
for(unsigned int j=0; j < p->max_set_members; j++)
{
copyout_rng_state(poly->set_states+j, p->args.pseudo_random_number_generator_arg);
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp target exit data map(from:poly->set_states[0:p->max_set_members])
#endif
}
return 0*N;
}
int reallocate_polymer_mem(struct Phase*const p)
{
const uint64_t new_storage = p->n_polymers_storage * 1.05 + 1;
printf("INFO: @t=%d rank %d is reallocating space for polymers %ld %ld.\n",
p->time,p->info_MPI.current_core,new_storage,p->n_polymers_storage);
struct Polymer*const tmp_poly = (struct Polymer*const)malloc(new_storage*sizeof(struct Polymer));
if( tmp_poly == NULL)
{
fprintf(stderr,"ERROR: %s:%d reallocate malloc %ld\n",__FILE__,__LINE__,new_storage);
return -1;
}
memcpy( tmp_poly, p->polymers, p->n_polymers_storage*sizeof(Polymer));
// RESUME port here
#ifdef SPEC_OPENACC
#ifdef SPEC_OPENACC
#pragma acc enter data copyin (tmp_poly[0:new_storage])
#endif
Polymer* tmp_dev = (Polymer*)acc_deviceptr((Polymer*)tmp_poly);
Polymer*const poly_dev = (Polymer*)acc_deviceptr((Polymer*const)p->polymers);
acc_memcpy_device( tmp_dev , poly_dev, p->n_polymers_storage*sizeof(Polymer) );
#endif//SPEC_OPENACC
#ifdef SPEC_OPENACC
#pragma acc exit data delete(p->polymers[0:p->n_polymers_storage])
#endif
free( p->polymers );
p->n_polymers_storage = new_storage;
p->polymers = tmp_poly;
#ifdef SPEC_OPENACC
struct Phase*const p_dev = acc_deviceptr(p);
acc_memcpy_to_device( &(p_dev->polymers), &tmp_dev, sizeof(Polymer*));
#endif//SPEC_OPENACC
return 0;
}
int push_polymer(struct Phase*const p,const Polymer*const poly)
{
assert(false);
assert(poly);
if(p->n_polymers >= p->n_polymers_storage)
reallocate_polymer_mem(p);
assert( p->n_polymers < p->n_polymers_storage);
p->polymers[p->n_polymers] = *poly;
#ifdef SPEC_OPENACC
const unsigned int pos = p->n_polymers;
Polymer*const polymers_dev = acc_deviceptr( p->polymers);
acc_memcpy_to_device( polymers_dev + pos, p->polymers + pos, sizeof(Polymer));
#endif//SPEC_OPENACC
copyin_polymer(p,&(p->polymers[p->n_polymers]));
//Update struct
p->n_polymers += 1;
#ifdef SPEC_OPENACC
#pragma acc update device(p->n_polymers)
#elif defined(SPEC_OPENMP_TARGET)
#pragma omp target update to(p->n_polymers)
#endif
const unsigned int N = p->poly_arch[ p->poly_type_offset[poly->type] ];
for (unsigned int k = 0; k < N; k++)
{
const unsigned int type = get_particle_type(
p->poly_arch[ p->poly_type_offset[poly->type]+1+k]);
p->num_bead_type_local[type] += 1;
p->num_all_beads_local += 1;
}
#ifdef SPEC_OPENACC
#pragma acc update device(p->num_bead_type_local[0:p->n_types])
#pragma acc update device(p->num_all_beads_local)
#elif defined(SPEC_OPENMP_TARGET)
#pragma omp target update to(p->num_bead_type_local[0:p->n_types])
#pragma omp target update to(p->num_all_beads_local)
#endif
return 0;
}
int pop_polymer(struct Phase*const p,const uint64_t poly_id,Polymer*const poly)
{
if( poly_id >= p->n_polymers)
{
fprintf(stderr,"WARNING: Invalid pop attempt of polymer. rank: %d poly_id %ld n_polymers %ld.\n"
,p->info_MPI.current_core,poly_id,p->n_polymers);
return -1;
}
// Copy out the polymer host
memcpy( poly, p->polymers+poly_id, sizeof(Polymer) );
p->n_polymers -= 1;
#ifdef SPEC_OPENACC
#pragma acc update device(p->n_polymers)
#endif
//Fill the gap in vector
memcpy( p->polymers + poly_id, p->polymers + p->n_polymers, sizeof(Polymer));
#ifdef SPEC_OPENACC
Polymer*const polymers_dev = acc_deviceptr(p->polymers);
acc_memcpy_device( polymers_dev + poly_id, polymers_dev + p->n_polymers, sizeof(Polymer) );
#endif//SPEC_OPENACC
const unsigned int N = p->poly_arch[ p->poly_type_offset[poly->type] ];
for (unsigned int k = 0; k < N; k++)
{
const unsigned int type = get_particle_type(
p->poly_arch[ p->poly_type_offset[poly->type]+1+k]);
p->num_bead_type_local[type] -= 1;
p->num_all_beads_local -= 1;
}
#ifdef SPEC_OPENACC
#pragma acc update device(p->num_bead_type_local[0:p->n_types])
#pragma acc update device(p->num_all_beads_local)
#endif
copyout_polymer(p, poly);
return 0;
}
unsigned int poly_serial_length(const struct Phase*const p,const Polymer*const poly)
{
const unsigned int N =p->poly_arch[p->poly_type_offset[poly->type]];
unsigned int length = 0;
//Buffer length
length += sizeof(unsigned int);
//Type data
length += sizeof(unsigned int);
//Beads data
length += N*sizeof( Monomer );
//msd data
length += N*sizeof( Monomer );
//poly RNG state
length += rng_state_serial_length(p);
if( poly->set_permutation != NULL)
length += p->max_n_sets * sizeof(unsigned int);
if( poly->set_states != NULL)
length += p->max_set_members*rng_state_serial_length(p);
return length;
}
int serialize_polymer(const struct Phase*const p,const Polymer*const poly,unsigned char*const buffer)
{
const unsigned int N =p->poly_arch[p->poly_type_offset[poly->type]];
unsigned int position = 0;
//Buffer length
const unsigned int length = poly_serial_length(p, poly);
memcpy( buffer + position, &length, sizeof(unsigned int));
position += sizeof(unsigned int);
//Type data
memcpy(buffer + position, &(poly->type), sizeof(unsigned int));
position += sizeof(unsigned int);
//Beads data
memcpy(buffer + position, global_allocator->all_Monomer.buf + poly->beads, N*sizeof(Monomer) );
position += N*sizeof(Monomer);
//MSD data
memcpy(buffer + position , global_allocator->all_Monomer_msd.buf + poly->msd_beads, N*sizeof(Monomer) );
position += N*sizeof(Monomer);
// Poly state
position += serialize_rng_state(p, &(poly->poly_state), buffer +position);
// Set permutation
if( poly->set_permutation != NULL)
{
memcpy(buffer + position, poly->set_permutation, p->max_n_sets * sizeof(unsigned int));
position += p->max_n_sets * sizeof(unsigned int);
}
if( poly->set_states != NULL)
for(unsigned int i=0; i < p->max_set_members; i++)
position += serialize_rng_state(p, poly->set_states+i, buffer+position);
return position;
}
int deserialize_polymer(const struct Phase*const p, Polymer*const poly,unsigned char*const buffer)
{
unsigned int position = 0;
//Buffer length
unsigned int length;
memcpy( &length,buffer + position, sizeof(unsigned int));
position += sizeof(unsigned int);
//Type data
memcpy(&(poly->type),buffer + position, sizeof(unsigned int));
position += sizeof(unsigned int);
const unsigned int N =p->poly_arch[p->poly_type_offset[poly->type]];
//Beads data
/* poly->beads = (Monomer*)malloc( N*sizeof(Monomer) ); */
poly->beads = alloc_Monomer( N );
/* MALLOC_ERROR_CHECK(poly->beads, N*sizeof(Monomer) ); */
memcpy(global_allocator->all_Monomer.buf + poly->beads,buffer + position, N*sizeof(Monomer) );
position += N*sizeof(Monomer);
//MSD data
/* poly->msd_beads = (Monomer*)malloc( N*sizeof(Monomer)); */
poly->msd_beads = alloc_Monomer( N );
/* MALLOC_ERROR_CHECK(poly->msd_beads, N*sizeof(Monomer)); */
memcpy(global_allocator->all_Monomer_msd.buf + poly->msd_beads, buffer + position, N*sizeof(Monomer) );
position += N*sizeof(Monomer);
// Poly state
position += deserialize_rng_state(p, &(poly->poly_state), buffer +position);
poly->set_permutation = NULL;
poly->set_states = NULL;
// If there is more data in the buffer, this polymer carries set information.
if( length > position)
{
poly->set_permutation = (unsigned int*)malloc( p->max_n_sets * sizeof(unsigned int));
MALLOC_ERROR_CHECK(poly->set_permutation, p->max_n_sets*sizeof(unsigned int));
memcpy(poly->set_permutation,buffer + position, p->max_n_sets * sizeof(unsigned int));
position += p->max_n_sets * sizeof(unsigned int);
}
if( length > position)
{
poly->set_states = (RNG_STATE*) malloc( p->max_set_members * sizeof(RNG_STATE));
MALLOC_ERROR_CHECK(poly->set_states, p->max_set_members*sizeof(RNG_STATE));
for(unsigned int i=0; i < p->max_set_members; i++)
position += deserialize_rng_state(p, poly->set_states+i, buffer+position);
}
else
{
assert(poly->set_permutation == NULL);
}
if( position != length )
{
fprintf(stderr,"ERROR: %s:%d Deserialization of polymer. "
" The read buffer size %d, does not coincide with length %d "
" claimed by the buffer content.\n",
__FILE__, __LINE__,position,length);
return -2;
}
return position;
}
int update_self_polymer(const struct Phase*const p,Polymer*const poly)
{
const unsigned int N= p->poly_arch[ p->poly_type_offset[poly->type] ];
update_self_rng_state(&(poly->poly_state), p->args.pseudo_random_number_generator_arg);
if(poly->set_permutation !=NULL)
{
#ifdef SPEC_OPENACC
#pragma acc update self(poly->set_permutation[0:p->max_n_sets])
#elif defined(SPEC_OPENMP_TARGET)
#pragma omp target update from(poly->set_permutation[0:p->max_n_sets])
#endif
}
if(poly->set_states !=NULL)
{
#ifdef SPEC_OPENACC
#pragma acc update self(poly->set_states[0:p->max_set_members])
#elif defined(SPEC_OPENMP_TARGET)
#pragma omp target update from(poly->set_states[0:p->max_set_members])
#endif
for(unsigned int j=0; j < p->max_set_members; j++)
{
update_self_rng_state(poly->set_states +j, p->args.pseudo_random_number_generator_arg);
}
}
#ifdef SPEC_OPENACC
#pragma acc update self(poly->type)
#elif defined(SPEC_OPENMP_TARGET)
#pragma omp target update from(poly->type)
#endif
return 0 + 1*N*0;
}
|
./SPECaccel/benchspec/ACCEL/551.ppalm/src/modules.F90 | MODULE advection
!--------------------------------------------------------------------------------!
! This file is part of PALM.
!
! PALM is free software: you can redistribute it and/or modify it under the terms
! of the GNU General Public License as published by the Free Software Foundation,
! either version 3 of the License, or (at your option) any later version.
!
! PALM is distributed in the hope that it will be useful, but WITHOUT ANY
! WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
! A PARTICULAR PURPOSE. See the GNU General Public License for more details.
!
! You should have received a copy of the GNU General Public License along with
! PALM. If not, see <http://www.gnu.org/licenses/>.
!
! Copyright 1997-2012 Leibniz University Hannover
!--------------------------------------------------------------------------------!
!
! Current revisions:
! ------------------
!
!
! Former revisions:
! -----------------
! $Id: modules.f90 1222 2013-09-10 14:48:09Z raasch $
!
! 1221 2013-09-10 08:59:13Z raasch
! wall_flags_0 changed to 32bit int, +wall_flags_00,
! +rflags_s_inner, rflags_invers
!
! 1216 2013-08-26 09:31:42Z raasch
! +transpose_compute_overlap,
! several variables are now defined in the serial (non-parallel) case also
!
! 1212 2013-08-15 08:46:27Z raasch
! +tri
!
! 1179 2013-06-14 05:57:58Z raasch
! +reference_state, ref_state, use_initial_profile_as_reference, vpt_reference,
! use_reference renamed use_single_reference_value
!
! 1159 2013-05-21 11:58:22Z fricke
! -bc_lr_dirneu, bc_lr_neudir, bc_ns_dirneu, bc_ns_neudir
! +use_cmax
!
! 1128 2013-04-12 06:19:32Z raasch
! +background_communication, i_left, i_right, j_north, j_south, req, req_count,
! send_receive, sendrecv_in_background, wait_stat
!
! 1115 2013-03-26 18:16:16Z hoffmann
! unused variables removed
!
! 1113 2013-03-10 02:48:14Z raasch
! +on_device
!
! 1111 2013-03-08 23:54:10Z raasch
! +tric, nr_timesteps_this_run
!
! 1106 2013-03-04 05:31:38Z raasch
! array_kind renamed precision_kind, pdims defined in serial code
! bugfix: default value assigned to coupling_start_time
!
! 1095 2013-02-03 02:21:01Z raasch
! FORTRAN error in r1092 removed
!
! 1092 2013-02-02 11:24:22Z raasch
! character length in some derived type changed for better alignment
!
! 1065 2012-11-22 17:42:36Z hoffmann
! + c_sedimentation, limiter_sedimentation, turbulence, a_1, a_2, a_3, b_1, b_2,
! + b_3, c_1, c_2, c_3, beta_cc
!
! bottom boundary condition of qr, nr changed from Dirichlet to Neumann
!
! 1053 2012-11-13 17:11:03Z hoffmann
! necessary expansions according to the two new prognostic equations (nr, qr)
! of the two-moment cloud physics scheme:
! +*_init, flux_l_*, diss_l_*, flux_s_*, diss_s_*, *sws, *swst, tend_*, *, *_p
! +t*_m, *_1, *_2, *_3, *_av, bc_*_b, bc_*_t, ibc_*_b, ibc_*_t, bc_*_t_val,
! +*_vertical_gradient, *_surface_initial_change, *_vertical_gradient_level,
! +*_vertical_gradient_level_ind, *_surface, constant_waterflux_*,
! +cloud_scheme, icloud_scheme, surface_waterflux_*, sums_ws*s_ws_l, wall_*flux
!
! constants for the two-moment scheme:
! +a_vent, a_term, b_vent, b_term, c_evap, c_term, cof, eps_sb, k_cc, k_cr, k_rr,
! +k_br, kappa_rr, kin_vis_air, mu_constant_value, nc, pirho_l, dpirho_l, rho_1,
! +schmidt, schmidt_p_1d3, stp, x0, xmin, xmax, dt_precipitation, w_precipitation
!
! steering parameters for the two_moment scheme:
! +mu_constant, ventilation_effect
!
! 1036 2012-10-22 13:43:42Z raasch
! code put under GPL (PALM 3.9)
!
! 1031 2012-10-19 14:35:30Z raasch
! +output_format_netcdf
!
! 1015 2012-09-27 09:23:24Z raasch
! +acc_rank, num_acc_per_node,
! -adjust_mixing_length
!
! 1010 2012-09-20 07:59:54Z raasch
! pointer free version can be generated with cpp switch __nopointer
!
! 1003 2012-09-14 14:35:53Z raasch
! -grid_matching, nxa, nya, etc., nnx_pe, nny_pe, spl_*
!
! 1001 2012-09-13 14:08:46Z raasch
! -asselin_filter_factor, cut_spline_overshoot, dt_changed, last_dt_change,
! last_dt_change_1d, long_filter_factor, overshoot_limit_*, ups_limit_*
! several pointer/target arrays converted to normal ones
!
! 996 2012-09-07 10:41:47Z raasch
! -use_prior_plot1d_parameters
!
! 978 2012-08-09 08:28:32Z fricke
! +c_u_m, c_u_m_l, c_v_m, c_v_m_l, c_w_m, c_w_m_l,
! +bc_lr_dirneu, bc_lr_neudir, bc_ns_dirneu, bc_ns_neudir
! -km_damp_x, km_damp_y, km_damp_max, outflow_damping_width
! +z0h, z0h_av, z0h_factor, z0h1d
! +ptdf_x, ptdf_y, pt_damping_width, pt_damping_factor
!
! 964 2012-07-26 09:14:24Z raasch
! -cross_linecolors, cross_linestyles, cross_normalized_x, cross_normx_factor,
! cross_normalized_y, cross_normy_factor, cross_pnc_local,
! cross_profile_numbers, cross_profile_number_counter, cross_uxmax,
! cross_uxmax_computed, cross_uxmax_normalized,
! cross_uxmax_normalized_computed, cross_uxmin, cross_uxmin_computed,
! cross_uxmin_normalized, cross_uxmin_normalized_computed, cross_uymax,
! cross_uymin, cross_xtext, dopr_crossindex, dopr_label, linecolors, linestyles,
! nz_do1d, profil_output, z_max_do1d, z_max_do1d_normalized
!
! 951 2012-07-19 14:22:52Z hoffmann
! changing profile_columns and profile_rows
!
! 940 2012-07-09 14:31:00Z raasch
! +neutral
!
! 927 2012-06-06 19:15:04Z raasch
! +masking_method
!
! 880 2012-04-13 06:28:59Z raasch
! gathered_size, subdomain_size moved to control_parameters
!
! 866 2012-03-28 06:44:41Z raasch
! interface for global_min_max changed
!
! 861 2012-03-26 14:18:34Z suehring
! +wall_flags_0
! -boundary_flags
! +nzb_max
! +adv_sca_1, +adv_mom_1
!
! 849 2012-03-15 10:35:09Z raasch
! +deleted_particles, deleted_tails, tr.._count_sum, tr.._count_recv_sum in
! particle_attributes,
! +de_dx, de_dy, de_dz in arrays_3d,
! first_call_advec_particles renamed first_call_lpm
!
! 828 2012-02-21 12:00:36Z raasch
! +dissipation_classes, radius_classes, use_kernel_tables,
! particle feature color renamed class
!
! 825 2012-02-19 03:03:44Z raasch
! +bfactor, curvature_solution_effects, eps_ros, molecular_weight_of_water,
! vanthoff, -b_cond in cloud_parameters,
! dopts_num increased to 29, particle attributes speed_x|y|z_sgs renamed
! rvar1|2|3
! wang_collision_kernel and turbulence_effects_on_collision replaced by
! collision_kernel, hall_kernel, palm_kernel, wang_kernel
!
! 809 2012-01-30 13:32:58Z marongas
! Bugfix: replaced .AND. and .NOT. with && and ! in the preprocessor directives
!
! 807 2012-01-25 11:53:51Z maronga
! New cpp directive "__check" implemented which is used by check_namelist_files.
! New parameter check_restart has been defined which is needed by
! check_namelist_files only.
!
! 805 2012-01-17 15:53:28Z franke
! Bugfix collective_wait must be out of parallel branch for runs in serial mode
!
! 801 2012-01-10 17:30:36Z suehring
! Dimesion of sums_wsus_ws_l, ! sums_wsvs_ws_l, sums_us2_ws_l, sums_vs2_ws_l,
! sums_ws2_ws_l, sums_wspts_ws_l, sums_wsqs_ws_l, sums_wssas_ws_l increased.
! for thread-safe summation in advec_ws.
!
! 792 2011-12-01 01:23:23Z raasch
! particle arrays (particles, parrticles_temp) implemented as pointers,
! +particles_1, particles_2, sort_count
!
! 790 2011-11-29 03:11:20Z raasch
! +turbulence_effects_on_collision, wang_collision_kernel
!
! 785 2011-11-28 09:47:19Z raasch
! +scalar_rayleigh_damping, rdf_sc
!
! 778 2011-11-07 14:18:25Z fricke
! +gathered_size, subdomain_size
!
! 771 2011-10-27 10:56:21Z heinze
! +lpt_av
!
! 767 2011-10-14 06:39:12Z raasch
! +u_profile, v_profile, uv_heights, use_prescribed_profile_data
!
! 759 2011-09-15 13:58:31Z raasch
! +io_blocks, io_group, maximum_parallel_io_streams,
! synchronous_exchange moved to control_parameters
!
! 743 2011-08-18 16:10:16Z suehring
! Dimension of sums_wsus_ws_l, sums_wsvs_ws_l, sums_us2_ws_l, sums_vs2_ws_l,
! sums_ws2_ws_l, sums_wspts_ws_l, sums_wssas_ws_l,sums_wsqs_ws_l needed for
! statistical evaluation of turbulent fluxes in WS-scheme decreased.
! 736 2011-08-17 14:13:26Z suehring
! Dimension of fluxes needed for WS-scheme increased.
!
! 722 2011-04-11 06:21:09Z raasch
! Bugfix: default value for south_border_pe changed to .F.
!
! 707 2011-03-29 11:39:40Z raasch
! +bc_lr_dirrad, bc_lr_raddir, bc_ns_dirrad, bc_ns_raddir, left_border_pe,
! north_border_pe, right_border_pe, south_border_pe
! p_sub renamed p_loc
!
! 683 2011-02-09 14:25:15Z raasch
! +synchronous_exchange
!
! 673 2011-01-18 16:19:48Z suehring
! +weight_pres to weight the respective contribution of the Runge-Kutta
! substeps. +p_sub to buffer the intermediate contributions for Multigrid and
! SOR.
!
! 667 2010-12-23 12:06:00Z suehring/gryschka
! Removed u_nzb_p1_for_vfc and v_nzb_p1_for_vfc
! For coupling with different resolution in ocean and atmophere:
! +nx_a, +nx_o, ny_a, +ny_o, ngp_a, ngp_o, +total_2d_o, +total_2d_a,
! +coupling_topology
! Buffer arrays for the left sided advective fluxes added in arrays_3d.
! +flux_s_u, +flux_s_v, +flux_s_w, +diss_s_u, +diss_s_v, +diss_s_w,
! +flux_s_pt, +diss_s_pt, +flux_s_e, +diss_s_e, +flux_s_q, +diss_s_q,
! +flux_s_sa, +diss_s_sa
! 3d arrays for dissipation control added. (only necessary for vector arch.)
! +var_x, +var_y, +var_z, +gamma_x, +gamma_y, +gamma_z
! Default of momentum_advec and scalar_advec changed to 'ws-scheme' .
! +exchange_mg added in control_parameters to steer the data exchange.
! Parameters +nbgp, +nxlg, +nxrg, +nysg, +nyng added in indices.
! flag array +boundary_flags added in indices to steer the degradation of order
! of the advective fluxes when non-cyclic boundaries are used.
! MPI-datatypes +type_y, +type_y_int and +type_yz for data_exchange added in
! pegrid.
! +sums_wsus_ws_l, +sums_wsvs_ws_l, +sums_us2_ws_l, +sums_vs2_ws_l,
! +sums_ws2_ws_l, +sums_wspts_ws_l, +sums_wssas_ws_l, +sums_wsqs_ws_l
! and +weight_substep added in statistics to steer the statistical evaluation
! of turbulent fluxes in the advection routines.
! LOGICALS +ws_scheme_sca and +ws_scheme_mom added to get a better performance
! in prognostic_equations.
! LOGICAL +dissipation_control control added to steer numerical dissipation
! in ws-scheme.
! Changed length of string run_description_header
!
! 622 2010-12-10 08:08:13Z raasch
! +collective_wait in pegrid
!
! 600 2010-11-24 16:10:51Z raasch
! default values of surface_scalarflux and surface_waterflux changed
! to 9999999.9
!
! 580 2010-10-05 13:59:11Z heinze
! Renaming of ws_vertical_gradient to subs_vertical_gradient,
! ws_vertical_gradient_level to subs_vertical_gradient_level and
! ws_vertical_gradient_level_ind to subs_vertical_gradient_level_i
!
! 564 2010-09-30 13:18:59Z helmke
! nc_precision and netcdf_precision dimension changed to 11, all default
! values of mask_xyz_loop changed to -1.0, dimension of openfile changed to
! 200+2*max_masks, max_masks changed to 50
!
! 553 2010-09-01 14:09:06Z weinreis
! parameters for masked output are replaced by arrays
!
! 531 2010-04-21 06:47:21Z heinze
! character length of dopr_unit enlarged
!
! 519 2010-03-19 05:30:02Z raasch
! -replace_char, replace_by
!
! 493 2010-03-01 08:30:24Z raasch
! +netcdf_data_format, -netcdf_64bit, -netcdf_64bit_3d, -netcdf_format_mask*,
! -nc_format_mask, -format_parallel_io
!
! 485 2010-02-05 10:57:51Z raasch
! ngp_3d, ngp_3d_inner changed to 64 bit
!
! 449 2010-02-02 11:23:59Z raasch
! -var_ts: replaced by dots_max,
! initial data assignments to some dvrp arrays changed due to error messages
! from gfortran compiler
! +large_scale_subsidence, ws_vertical_gradient, ws_vertical_gradient_level,
! ws_vertical_gradient_level_ind, w_subs
!
! 388 2009-09-23 09:40:33Z raasch
! +prho, prho_1
! +bc_lr_cyc, bc_ns_cyc
! +output_for_t0
! translation error of actual -> current revisions fixed
! +q* in dots_label, dots_unit. increased dots_num respectively
! typographical error in dots_unit fixed
! +clip_dvrp_*, cluster_size, color_interval, dvrpsize_interval, dvrp_overlap,
! dvrp_total_overlap, groundplate_color, local_dvrserver_running, n*_dvrp,
! interval_*_dvrp_prt, isosurface_color, particle_color, particle_dvrpsize,
! topography color in dvrp_variables,
! vertical_particle_advection is a 1d-array,
! +canyon_height, canyon_width_x, canyon_width_y, canyon_wall_left,
! canyon_wall_south, conserve_volume_flow_mode, coupling_start_time,
! dp_external, dp_level_b, dp_level_ind_b, dp_smooth, dp_smooth_factor, dpdxy,
! run_coupled, time_since_reference_point, u_bulk, v_bulk in control_parameters,
! default value of grid_matching changed to strict
! +shf_av, qsws_av
!
! 217 2008-12-09 18:00:48Z letzel
! +topography_grid_convention
! some dvrp-variables changed to single precision, variables for dvrp-mode
! pathlines added, +target_id, abort_mode, message_string
!
! 197 2008-09-16 15:29:03Z raasch
! allow 100 spectra levels instead of 10 for consistency with
! define_netcdf_header, +canopy_heat_flux, cthf, lai,
! +leaf_surface_concentration, scalar_exchange_coefficient, sec, sls
! +hor_index_bounds, hor_index_bounds_previous_run, id_inflow, id_recycling,
! inflow_damping_*, mean_inflow_profiles, numprocs_previous_run, nx_on_file,
! ny_on_file, offset_ocean_*, recycling_plane, recycling_width, turbulent_inflow
! -myid_char_14
!
! 138 2007-11-28 10:03:58Z letzel
! +drag_coefficient, pch_index, lad_surface, lad_vertical_gradient,
! lad_vertical_gradient_level, plant_canopy, lad, lad_s, lad_u, lad_v,
! lad_w, cdc, lad_vertical_gradient_level_ind, canopy_mode
! +dt_sort_particles, ngp_2dh_s_inner, time_sort_particles, flags,
! wall_flags_1..10, wall_humidityflux(0:4), wall_qflux(0:4),
! wall_salinityflux(0:4), wall_scalarflux(0:4)
!
! 108 2007-08-24 15:10:38Z letzel
! +comm_inter, constant_top_momentumflux, coupling_char, coupling_mode,
! coupling_mode_remote, c_u, c_v, c_w, dt_coupling, e_init, humidity_remote,
! ngp_xy, nxlu, nysv, port_name, qswst_remote, terminate_coupled,
! terminate_coupled_remote, time_coupling, top_momentumflux_u|v, type_xy,
! uswst*, vswst*
!
! 97 2007-06-21 08:23:15Z raasch
! +atmos_ocean_sign, ocean, r, + salinity variables
! defaults of .._vertical_gradient_levels changed from -1.0 to -9999999.9
! hydro_press renamed hyp, use_pt_reference renamed use_reference
!
! 89 2007-05-25 12:08:31Z raasch
! +data_output_pr_user, max_pr_user, size of data_output_pr, dopr_index,
! dopr_initial_index and dopr_unit enlarged,
! var_hom and var_sum renamed pr_palm
!
! 82 2007-04-16 15:40:52Z raasch
! +return_addres, return_username
! Cpp-directive lcmuk renamed lc
!
! 75 2007-03-22 09:54:05Z raasch
! +arrays precipitation_amount, precipitation_rate, precipitation_rate_av,
! rif_wall, z0_av, +arrays u_m_l, u_m_r, etc. for radiation boundary conditions,
! +loop_optimization, netcdf_64bit_3d, zu_s_inner, zw_w_inner, id_var_zusi_*,
! id_var_zwwi_*, ts_value, u_nzb_p1_for_vfc, v_nzb_p1_for_vfc, pt_reference,
! use_pt_reference, precipitation_amount_interval, revision
! +age_m in particle_type, moisture renamed humidity,
! -data_output_ts, dots_n, uvmean_outflow, uxrp, vynp,
! arrays dots_label and dots_unit now dimensioned with dots_max,
! setting of palm version moved to main program
!
! 37 2007-03-01 08:33:54Z raasch
! +constant_top_heatflux, top_heatflux, use_top_fluxes, +arrays for top fluxes,
! +nzt_diff, default of bc_pt_t renamed "initial_gradient"
! Bugfix: p is not a pointer
!
! RCS Log replace by Id keyword, revision history cleaned up
!
! Revision 1.95 2007/02/11 13:18:30 raasch
! version 3.1b (last under RCS control)
!
! Revision 1.1 1997/07/24 11:21:26 raasch
! Initial revision
!
!
! Description:
! ------------
! Definition of variables for special advection schemes
!------------------------------------------------------------------------------!
REAL, DIMENSION(:), ALLOCATABLE :: aex, bex, dex, eex
SAVE
END MODULE advection
MODULE precision_kind
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of type parameters (used for the definition of single or double
! precision variables)
!------------------------------------------------------------------------------!
INTEGER, PARAMETER :: dpk = SELECTED_REAL_KIND( 12 ), &
spk = SELECTED_REAL_KIND( 6 )
SAVE
END MODULE precision_kind
MODULE arrays_3d
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of all arrays defined on the computational grid
!------------------------------------------------------------------------------!
USE precision_kind
REAL, DIMENSION(:), ALLOCATABLE :: &
c_u_m, c_u_m_l, c_v_m, c_v_m_l, c_w_m, c_w_m_l, ddzu, ddzu_pres, &
dd2zu, dzu, ddzw, dzw, hyp, inflow_damping_factor, lad, l_grid, &
nc_1d, nr_1d, ptdf_x, ptdf_y, pt_1d, pt_init, q_1d, q_init, qc_1d, &
qr_1d, rdf, rdf_sc, ref_state, sa_init, ug, u_init, &
u_nzb_p1_for_vfc, vg, v_init, v_nzb_p1_for_vfc, w_subs, zu, zw
REAL, DIMENSION(:,:), ALLOCATABLE :: &
c_u, c_v, c_w, diss_s_e, diss_s_nr, diss_s_pt, diss_s_q, &
diss_s_qr, diss_s_sa, diss_s_u, diss_s_v, diss_s_w, dzu_mg, dzw_mg, &
flux_s_e, flux_s_nr, flux_s_pt, flux_s_q, flux_s_qr, flux_s_sa, &
flux_s_u, flux_s_v, flux_s_w, f1_mg, f2_mg, f3_mg, &
mean_inflow_profiles, nrs, nrsws, nrswst, pt_slope_ref, qs, qsws, &
qswst, qswst_remote, qrs, qrsws, qrswst, rif, saswsb, saswst, shf, &
total_2d_a, total_2d_o, ts, tswst, us, usws, uswst, vsws, vswst, z0, &
z0h
REAL, DIMENSION(:,:,:), ALLOCATABLE :: &
canopy_heat_flux, cdc, d, de_dx, de_dy, de_dz, diss, diss_l_e, &
diss_l_nr, diss_l_pt, diss_l_q, diss_l_qr, diss_l_sa, diss_l_u, &
diss_l_v, diss_l_w, flux_l_e, flux_l_nr, flux_l_pt, flux_l_q, &
flux_l_qr, flux_l_sa, flux_l_u, flux_l_v, flux_l_w, kh, km, lad_s, &
lad_u, lad_v, lad_w, lai, l_wall, p_loc, sec, sls, tend, tend_pt, &
tend_nr, tend_q, tend_qr, tric, u_m_l, u_m_n, u_m_r, u_m_s, v_m_l, &
v_m_n, v_m_r, v_m_s, w_m_l, w_m_n, w_m_r, w_m_s
#if defined( __nopointer )
REAL, DIMENSION(:,:,:), ALLOCATABLE, TARGET :: &
e, e_p, nr, nr_p, p, prho, pt, pt_p, q, q_p, qc, ql, ql_c, ql_v, &
ql_vp, qr, qr_p, rho, sa, sa_p, te_m, tnr_m, tpt_m, tq_m, tqr_m, &
tsa_m, tu_m, tv_m, tw_m, u, u_p, v, v_p, vpt, w, w_p
#else
REAL, DIMENSION(:,:,:), ALLOCATABLE, TARGET :: &
e_1, e_2, e_3, p, prho_1, nr_1, nr_2, nr_3, pt_1, pt_2, pt_3, q_1, &
q_2, q_3, qc_1, ql_v, ql_vp, ql_1, ql_2, qr_1, qr_2, qr_3, rho_1, &
sa_1, sa_2, sa_3, u_1, u_2, u_3, v_1, v_2, v_3, vpt_1, w_1, w_2, w_3
REAL, DIMENSION(:,:,:), POINTER :: &
e, e_p, nr, nr_p, prho, pt, pt_p, q, q_p, qc, ql, ql_c, qr, qr_p, &
rho, sa, sa_p, te_m, tnr_m, tpt_m, tq_m, tqr_m, tsa_m, tu_m, tv_m, &
tw_m, u, u_p, v, v_p, vpt, w, w_p
#endif
REAL, DIMENSION(:,:,:,:), ALLOCATABLE :: rif_wall, tri
REAL, DIMENSION(:,:,:), ALLOCATABLE :: var_x, var_y, var_z, gamma_x, &
gamma_y, gamma_z
!$omp declare target(d,dd2zu,ddzu,ddzw,diss,dzu,e,e_p,kh,km,l_grid,l_wall, &
!$omp nr,p,prho,pt,pt_init,pt_p,ptdf_x,ptdf_y,q,qc,ql,qr,qs,qsws,qswst,rdf,rdf_sc, &
!$omp ref_state,rho,rif,rif_wall,sa,saswsb,saswst,shf,te_m,tend,tpt_m,ts,tswst, &
!$omp tri,tric,tu_m,tv_m,tw_m,u_init,u,ug,us,usws,uswst,u_p, &
!$omp v_init,v,vg,vpt,vsws,vswst,v_p,w,w_p,z0,z0h,zu,zw)
SAVE
END MODULE arrays_3d
MODULE averaging
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables needed for time-averaging of 2d/3d data
!------------------------------------------------------------------------------!
REAL, DIMENSION(:,:), ALLOCATABLE :: lwp_av, precipitation_rate_av, &
qsws_av, shf_av,ts_av, us_av, z0_av, &
z0h_av
REAL, DIMENSION(:,:,:), ALLOCATABLE, TARGET :: &
e_av, lpt_av, nr_av, p_av, pc_av, pr_av, prr_av, pt_av, q_av, qc_av, &
ql_av, ql_c_av, ql_v_av, ql_vp_av, qr_av, qv_av, rho_av, s_av, sa_av,&
u_av, v_av, vpt_av, w_av
END MODULE averaging
MODULE cloud_parameters
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables and constants for cloud physics
!------------------------------------------------------------------------------!
LOGICAL :: curvature_solution_effects = .FALSE., &
limiter_sedimentation = .TRUE., &
ventilation_effect = .FALSE.
REAL :: a_1 = 8.69E-4, & ! coef. in turb. parametrization (cm-2 s3)
a_2 = -7.38E-5, & ! coef. in turb. parametrization (cm-2 s3)
a_3 = -1.40E-2, & ! coef. in turb. parametrization
a_term = 9.65, & ! coef. for terminal velocity (m s-1)
a_vent = 0.78, & ! coef. for ventilation effect
b_1 = 11.45E-6, & ! coef. in turb. parametrization (m)
b_2 = 9.68E-6, & ! coef. in turb. parametrization (m)
b_3 = 0.62, & ! coef. in turb. parametrization
b_term = 9.8, & ! coef. for terminal velocity (m s-1)
b_vent = 0.308, & ! coef. for ventilation effect
beta_cc = 3.09E-4, & ! coef. in turb. parametrization (cm-2 s3)
bfactor, &
c_1 = 4.82E-6, & ! coef. in turb. parametrization (m)
c_2 = 4.8E-6, & ! coef. in turb. parametrization (m)
c_3 = 0.76, & ! coef. in turb. parametrization
c_const = 0.93, & ! const. in Taylor-microscale Reynolds number
c_evap = 0.7, & ! constant in evaporation
c_sedimentation = 2.0, & ! Courant number of sedimentation process
c_term = 600.0, & ! coef. for terminal velocity (m-1)
cof(6) = (/ 76.18009172947146, & ! coefficients in the
-86.50532032941677, & ! numerical
24.01409824083091, & ! calculation of the
-1.231739572450155, & ! gamma function
0.1208650973866179E-2, &
-0.5395239384953E-5 /), &
cp = 1005.0, & ! heat capacity of dry air (J kg-1 K-1)
diff_coeff_l = 0.23E-4, & ! diffusivity of water vapor (m2 s-1)
effective_coll_efficiency, &
eps_ros = 1.0E-4, & ! accuracy of Rosenbrock method
eps_sb = 1.0E-20, & ! threshold in two-moments scheme
k_cc = 9.44E09, & ! const. cloud-cloud kernel (m3 kg-2 s-1)
k_cr0 = 4.33, & ! const. cloud-rain kernel (m3 kg-1 s-1)
k_rr = 7.12, & ! const. rain-rain kernel (m3 kg-1 s-1)
k_br = 1000., & ! const. in breakup parametrization (m-1)
k_st = 1.2E8, & ! const. in drizzle parametrization (m-1 s-1)
kappa_rr = 60.7, & ! const. in collision kernel (kg-1/3)
kin_vis_air = 1.4086E-5, & ! kin. viscosity of air (m2 s-1)
l_v = 2.5E+06, & ! latent heat of vaporization (J kg-1)
l_d_cp, l_d_r, l_d_rv, & ! l_v / cp, l_v / r_d, l_v / r_v
mass_of_solute = 1.0E-17, & ! soluted NaCl (kg)
molecular_weight_of_solute = 0.05844, & ! mol. m. NaCl (kg mol-1)
molecular_weight_of_water = 0.01801528, & ! mol. m. H2O (kg mol-1)
nc_const = 70.0E6, & ! cloud droplet concentration
prec_time_const = 0.001, & !coef. in Kessler scheme
pirho_l, dpirho_l, & ! pi * rho_l / 6.0; 6.0 / ( pi * rho_l )
rho_l = 1.0E3, & ! density of water (kg m-3)
ql_crit = 0.0005, & ! coef. in Kessler scheme
r_d = 287.0, & ! sp. gas const. dry air (J kg-1 K-1)
r_v = 461.51, & ! sp. gas const. water vapor (J kg-1 K-1)
schmidt = 0.71, & ! Schmidt number
schmidt_p_1d3, & ! schmidt**( 1.0 / 3.0 )
sigma_gc = 1.3, & ! log-normal geometric standard deviation
stp = 2.5066282746310005, & ! parameter in gamma function
thermal_conductivity_l = 2.43E-2, & ! therm. cond. air (J m-1 s-1 K-1)
vanthoff = 2.0, & ! van't Hoff factor for NaCl
x0 = 2.6E-10, & ! separating drop mass (kg)
xrmin = 2.6E-10, & ! minimum rain drop size (kg)
xrmax = 5.0E-6, & ! maximum rain drop site (kg)
dt_precipitation = 100.0, & ! timestep precipitation (s)
w_precipitation = 9.65 ! maximum terminal velocity (m s-1)
REAL, DIMENSION(:), ALLOCATABLE :: hyrho, pt_d_t, t_d_pt
REAL, DIMENSION(:,:), ALLOCATABLE :: precipitation_amount, &
precipitation_rate
!
!-- 3D array of precipitation rate
REAL, DIMENSION(:,:,:), ALLOCATABLE :: prr
!$omp declare target(l_d_cp,prr,pt_d_t)
SAVE
END MODULE cloud_parameters
MODULE constants
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of general constants
!------------------------------------------------------------------------------!
REAL :: pi = 3.141592654
REAL :: adv_mom_1, adv_mom_3, adv_mom_5, adv_sca_1, adv_sca_3, adv_sca_5
!$omp declare target(pi,adv_mom_1,adv_mom_3,adv_mom_5,adv_sca_1,adv_sca_3,adv_sca_5)
SAVE
END MODULE constants
MODULE control_parameters
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of parameters for program control
!------------------------------------------------------------------------------!
TYPE plot_precision
CHARACTER (LEN=8) :: variable
INTEGER :: precision
END TYPE plot_precision
TYPE(plot_precision), DIMENSION(100) :: plot_3d_precision = &
(/ plot_precision( 'u', 2 ), plot_precision( 'v', 2 ), &
plot_precision( 'w', 2 ), plot_precision( 'p', 5 ), &
plot_precision( 'pt', 2 ), &
( plot_precision( ' ', 1 ), i9 = 1,95 ) /)
TYPE file_status
LOGICAL :: opened, opened_before
END TYPE file_status
INTEGER, PARAMETER :: mask_xyz_dimension = 100, max_masks = 50
TYPE(file_status), DIMENSION(200+2*max_masks) :: &
openfile = file_status(.FALSE.,.FALSE.)
CHARACTER (LEN=1) :: cycle_mg = 'w', timestep_reason = ' '
CHARACTER (LEN=2) :: coupling_char = ''
CHARACTER (LEN=5) :: write_binary = 'false'
CHARACTER (LEN=8) :: run_date, run_time
CHARACTER (LEN=9) :: simulated_time_chr
CHARACTER (LEN=11) :: topography_grid_convention = ' '
CHARACTER (LEN=12) :: version = ' ', revision = ' '
CHARACTER (LEN=16) :: conserve_volume_flow_mode = 'default', &
loop_optimization = 'default', &
momentum_advec = 'ws-scheme', &
psolver = 'poisfft', &
scalar_advec = 'ws-scheme'
CHARACTER (LEN=20) :: bc_e_b = 'neumann', bc_lr = 'cyclic', &
bc_ns = 'cyclic', bc_p_b = 'neumann', &
bc_p_t = 'dirichlet', bc_pt_b = 'dirichlet', &
bc_pt_t = 'initial_gradient', &
bc_q_b = 'dirichlet', bc_q_t = 'neumann', &
bc_s_b = 'dirichlet', bc_s_t = 'neumann', &
bc_sa_t = 'neumann', &
bc_uv_b = 'dirichlet', bc_uv_t = 'dirichlet', &
canopy_mode = 'block', &
cloud_scheme = 'seifert_beheng', &
coupling_mode = 'uncoupled', &
coupling_mode_remote = 'uncoupled', &
dissipation_1d = 'as_in_3d_model', &
fft_method = 'system-specific', &
mixing_length_1d = 'as_in_3d_model', &
random_generator = 'numerical-recipes', &
reference_state = 'initial_profile', &
return_addres, return_username, &
timestep_scheme = 'runge-kutta-3'
CHARACTER (LEN=40) :: avs_data_file, output_format_netcdf, &
topography = 'flat'
CHARACTER (LEN=64) :: host = ' '
CHARACTER (LEN=80) :: log_message, run_identifier
CHARACTER (LEN=100) :: initializing_actions = ' '
CHARACTER (LEN=110) :: run_description_header
CHARACTER (LEN=1000) :: message_string = ' '
CHARACTER (LEN=7), DIMENSION(100) :: do3d_comp_prec = ' '
CHARACTER (LEN=10), DIMENSION(10) :: data_output_format = ' '
CHARACTER (LEN=11), DIMENSION(100) :: data_output = ' ', &
data_output_user = ' ', doav = ' '
CHARACTER (LEN=10), DIMENSION(max_masks,100) :: &
data_output_masks = ' ', data_output_masks_user = ' '
CHARACTER (LEN=10), DIMENSION(300) :: data_output_pr = ' '
CHARACTER (LEN=10), DIMENSION(200) :: data_output_pr_user = ' '
CHARACTER (LEN=20), DIMENSION(11) :: netcdf_precision = ' '
CHARACTER (LEN=10), DIMENSION(max_masks,0:1,100) :: domask = ' '
CHARACTER (LEN=10), DIMENSION(0:1,100) :: do2d = ' ', do3d = ' '
INTEGER :: abort_mode = 1, average_count_pr = 0, average_count_sp = 0, &
average_count_3d = 0, current_timestep_number = 0, &
coupling_topology = 0, &
dist_range = 0, disturbance_level_ind_b, &
disturbance_level_ind_t, doav_n = 0, dopr_n = 0, &
dopr_time_count = 0, dopts_time_count = 0, &
dosp_time_count = 0, dots_time_count = 0, &
do2d_xy_n = 0, do2d_xz_n = 0, do2d_yz_n = 0, do3d_avs_n = 0, &
dp_level_ind_b = 0, dvrp_filecount = 0, &
dz_stretch_level_index, gamma_mg, gathered_size, &
grid_level, ibc_e_b, ibc_p_b, ibc_p_t, &
ibc_pt_b, ibc_pt_t, ibc_q_b, ibc_q_t, &
ibc_sa_t, ibc_uv_b, ibc_uv_t, icloud_scheme, &
inflow_disturbance_begin = -1, inflow_disturbance_end = -1, &
intermediate_timestep_count, intermediate_timestep_count_max, &
io_group = 0, io_blocks = 1, iran = -1234567, &
masks = 0, maximum_grid_level, &
maximum_parallel_io_streams = -1, max_pr_user = 0, &
mgcycles = 0, mg_cycles = -1, mg_switch_to_pe0_level = 0, mid, &
netcdf_data_format = 2, ngsrb = 2, nr_timesteps_this_run = 0, &
nsor = 20, nsor_ini = 100, n_sor, normalizing_region = 0, &
nz_do3d = -9999, pch_index = 0, prt_time_count = 0, &
recycling_plane, runnr = 0, &
skip_do_avs = 0, subdomain_size, terminate_coupled = 0, &
terminate_coupled_remote = 0, timestep_count = 0
INTEGER :: dist_nxl(0:1), dist_nxr(0:1), dist_nyn(0:1), dist_nys(0:1), &
do2d_no(0:1) = 0, do2d_xy_time_count(0:1), &
do2d_xz_time_count(0:1), do2d_yz_time_count(0:1), &
do3d_no(0:1) = 0, do3d_time_count(0:1), &
domask_no(max_masks,0:1) = 0, domask_time_count(max_masks,0:1),&
lad_vertical_gradient_level_ind(10) = -9999, &
mask_size(max_masks,3) = -1, mask_size_l(max_masks,3) = -1, &
mask_start_l(max_masks,3) = -1, &
pt_vertical_gradient_level_ind(10) = -9999, &
q_vertical_gradient_level_ind(10) = -9999, &
sa_vertical_gradient_level_ind(10) = -9999, &
section(100,3), section_xy(100) = -9999, &
section_xz(100) = -9999, section_yz(100) = -9999, &
ug_vertical_gradient_level_ind(10) = -9999, &
vg_vertical_gradient_level_ind(10) = -9999, &
subs_vertical_gradient_level_i(10) = -9999
#if defined ( __check )
INTEGER :: check_restart = 0
#endif
INTEGER, DIMENSION(:), ALLOCATABLE :: grid_level_count
INTEGER, DIMENSION(:,:), ALLOCATABLE :: mask_i, mask_j, mask_k
INTEGER, DIMENSION(:,:), ALLOCATABLE :: &
mask_i_global, mask_j_global, mask_k_global
LOGICAL :: avs_output = .FALSE., &
bc_lr_cyc =.TRUE., bc_lr_dirrad = .FALSE., &
bc_lr_raddir = .FALSE., bc_ns_cyc = .TRUE., &
bc_ns_dirrad = .FALSE., bc_ns_raddir = .FALSE.,&
call_psolver_at_all_substeps = .TRUE., &
cloud_droplets = .FALSE., cloud_physics = .FALSE., &
conserve_volume_flow = .FALSE., constant_diffusion = .FALSE., &
constant_heatflux = .TRUE., constant_top_heatflux = .TRUE., &
constant_top_momentumflux = .FALSE., &
constant_top_salinityflux = .TRUE., &
constant_waterflux = .TRUE., create_disturbances = .TRUE., &
data_output_2d_on_each_pe = .TRUE., &
dissipation_control = .FALSE., disturbance_created = .FALSE., &
do2d_at_begin = .FALSE., do3d_at_begin = .FALSE., &
do3d_compress = .FALSE., do_sum = .FALSE., &
dp_external = .FALSE., dp_smooth = .FALSE., &
drizzle = .FALSE., dt_fixed = .FALSE., &
dt_3d_reached, dt_3d_reached_l, exchange_mg = .FALSE., &
first_call_lpm = .TRUE., &
force_print_header = .FALSE., galilei_transformation = .FALSE.,&
humidity = .FALSE., humidity_remote = .FALSE., &
inflow_l = .FALSE., inflow_n = .FALSE., &
inflow_r = .FALSE., inflow_s = .FALSE., &
iso2d_output = .FALSE., large_scale_subsidence = .FALSE., &
masking_method = .FALSE., mg_switch_to_pe0 = .FALSE., &
netcdf_output = .FALSE., neutral = .FALSE., ocean = .FALSE., &
on_device = .FALSE., &
outflow_l = .FALSE., outflow_n = .FALSE., outflow_r = .FALSE., &
outflow_s = .FALSE., passive_scalar = .FALSE., &
plant_canopy = .FALSE., prandtl_layer = .TRUE., &
precipitation = .FALSE., &
radiation = .FALSE., random_heatflux = .FALSE., &
run_control_header = .FALSE., run_coupled = .TRUE., &
scalar_rayleigh_damping = .TRUE., sloping_surface = .FALSE., &
stop_dt = .FALSE., synchronous_exchange = .FALSE., &
terminate_run = .FALSE., transpose_compute_overlap = .FALSE., &
turbulence = .FALSE., turbulent_inflow = .FALSE., &
use_cmax = .TRUE., use_initial_profile_as_reference = .FALSE., &
use_prescribed_profile_data = .FALSE., &
use_single_reference_value = .FALSE., &
use_surface_fluxes = .FALSE., use_top_fluxes = .FALSE., &
use_ug_for_galilei_tr = .TRUE., use_upstream_for_tke = .FALSE.,&
wall_adjustment = .TRUE., ws_scheme_sca = .FALSE., &
ws_scheme_mom = .FALSE.
LOGICAL :: data_output_xy(0:1) = .FALSE., data_output_xz(0:1) = .FALSE., &
data_output_yz(0:1) = .FALSE.
REAL :: advected_distance_x = 0.0, advected_distance_y = 0.0, &
alpha_surface = 0.0, atmos_ocean_sign = 1.0, &
averaging_interval = 0.0, averaging_interval_pr = 9999999.9, &
averaging_interval_sp = 9999999.9, bc_pt_t_val, bc_q_t_val, &
bottom_salinityflux = 0.0, &
building_height = 50.0, building_length_x = 50.0, &
building_length_y = 50.0, building_wall_left = 9999999.9, &
building_wall_south = 9999999.9, canyon_height = 50.0, &
canyon_width_x = 9999999.9, canyon_width_y = 9999999.9, &
canyon_wall_left = 9999999.9, canyon_wall_south = 9999999.9, &
cthf = 0.0, cfl_factor = -1.0, cos_alpha_surface, &
coupling_start_time = 0.0, disturbance_amplitude = 0.25, &
disturbance_energy_limit = 0.01, &
disturbance_level_b = -9999999.9, &
disturbance_level_t = -9999999.9, &
dp_level_b = 0.0, drag_coefficient = 0.0, &
dt = -1.0, dt_averaging_input = 0.0, &
dt_averaging_input_pr = 9999999.9, dt_coupling = 9999999.9, &
dt_data_output = 9999999.9, &
dt_data_output_av = 9999999.9, dt_disturb = 9999999.9, &
dt_dopr = 9999999.9, dt_dopr_listing = 9999999.9, &
dt_dopts = 9999999.9, dt_dosp = 9999999.9, dt_dots = 9999999.9, &
dt_do2d_xy = 9999999.9, dt_do2d_xz = 9999999.9, &
dt_do2d_yz = 9999999.9, dt_do3d = 9999999.9, dt_dvrp = 9999999.9, &
dt_max = 20.0, dt_micro = -1.0, dt_restart = 9999999.9, &
dt_run_control = 60.0, dt_3d = -1.0, dz = -1.0, &
dz_max = 9999999.9, dz_stretch_factor = 1.08, &
dz_stretch_level = 100000.0, e_init = 0.0, e_min = 0.0, &
end_time = 0.0, &
f = 0.0, fs = 0.0, g = 9.81, inflow_damping_height = 9999999.9, &
inflow_damping_width = 9999999.9, kappa = 0.4, km_constant = -1.0,&
lad_surface = 0.0, leaf_surface_concentration = 0.0, &
mask_scale_x = 1.0, mask_scale_y = 1.0, mask_scale_z = 1.0, &
maximum_cpu_time_allowed = 0.0, &
molecular_viscosity = 1.461E-5, &
old_dt = 1.0E-10, omega = 7.29212E-5, omega_sor = 1.8, &
particle_maximum_age = 9999999.9, &
phi = 55.0, prandtl_number = 1.0, &
precipitation_amount_interval = 9999999.9, prho_reference, &
pt_damping_factor = 0.0, pt_damping_width = 0.0, &
pt_reference = 9999999.9, pt_slope_offset = 0.0, &
pt_surface = 300.0, pt_surface_initial_change = 0.0, &
q_surface = 0.0, q_surface_initial_change = 0.0, &
rayleigh_damping_factor = -1.0, rayleigh_damping_height = -1.0, &
recycling_width = 9999999.9, residual_limit = 1.0E-4, &
restart_time = 9999999.9, rho_reference, rho_surface, &
rif_max = 1.0, rif_min = -5.0, roughness_length = 0.1, &
sa_surface = 35.0, scalar_exchange_coefficient = 0.0, &
simulated_time = 0.0, simulated_time_at_begin, sin_alpha_surface, &
skip_time_data_output = 0.0, skip_time_data_output_av = 9999999.9,&
skip_time_dopr = 9999999.9, skip_time_dosp = 9999999.9, &
skip_time_do2d_xy = 9999999.9, skip_time_do2d_xz = 9999999.9, &
skip_time_do2d_yz = 9999999.9, skip_time_do3d = 9999999.9, &
surface_heatflux = 9999999.9, surface_pressure = 1013.25, &
surface_scalarflux = 9999999.9, surface_waterflux = 9999999.9, &
s_surface = 0.0, s_surface_initial_change = 0.0, &
termination_time_needed = -1.0, time_coupling = 0.0, &
time_disturb = 0.0, time_dopr = 0.0, time_dopr_av = 0.0, &
time_dopr_listing = 0.0, time_dopts = 0.0, time_dosp = 0.0, &
time_dosp_av = 0.0, time_dots = 0.0, time_do2d_xy = 0.0, &
time_do2d_xz = 0.0, time_do2d_yz = 0.0, time_do3d = 0.0, &
time_do_av = 0.0, time_do_sla = 0.0, time_dvrp = 0.0, &
time_restart = 9999999.9, time_run_control = 0.0,&
time_since_reference_point, top_heatflux = 9999999.9, &
top_momentumflux_u = 9999999.9, &
top_momentumflux_v = 9999999.9, top_salinityflux = 9999999.9, &
ug_surface = 0.0, u_bulk = 0.0, u_gtrans = 0.0, &
vg_surface = 0.0, vpt_reference = 9999999.9, &
v_bulk = 0.0, v_gtrans = 0.0, wall_adjustment_factor = 1.8, &
z_max_do2d = -1.0, z0h_factor = 1.0
REAL :: do2d_xy_last_time(0:1) = -1.0, do2d_xz_last_time(0:1) = -1.0, &
do2d_yz_last_time(0:1) = -1.0, dpdxy(1:2) = 0.0, &
dt_domask(max_masks) = 9999999.9, lad_vertical_gradient(10) = 0.0,&
lad_vertical_gradient_level(10) = -9999999.9, &
mask_scale(3), &
pt_vertical_gradient(10) = 0.0, &
pt_vertical_gradient_level(10) = -9999999.9, &
q_vertical_gradient(10) = 0.0, &
q_vertical_gradient_level(10) = -1.0, &
s_vertical_gradient(10) = 0.0, &
s_vertical_gradient_level(10) = -1.0, &
sa_vertical_gradient(10) = 0.0, &
sa_vertical_gradient_level(10) = -9999999.9, &
skip_time_domask(max_masks) = 9999999.9, threshold(20) = 0.0, &
time_domask(max_masks) = 0.0, &
tsc(10) = (/ 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 /), &
u_profile(100) = 9999999.9, uv_heights(100) = 9999999.9, &
v_profile(100) = 9999999.9, &
ug_vertical_gradient(10) = 0.0, &
ug_vertical_gradient_level(10) = -9999999.9, &
vg_vertical_gradient(10) = 0.0, &
vg_vertical_gradient_level(10) = -9999999.9, &
volume_flow(1:2) = 0.0, volume_flow_area(1:2) = 0.0, &
volume_flow_initial(1:2) = 0.0, wall_heatflux(0:4) = 0.0, &
wall_humidityflux(0:4) = 0.0, wall_nrflux(0:4) = 0.0, &
wall_qflux(0:4) = 0.0, wall_qrflux(0:4) = 0.0, &
wall_salinityflux(0:4) = 0.0, wall_scalarflux(0:4) = 0.0, &
subs_vertical_gradient(10) = 0.0, &
subs_vertical_gradient_level(10) = -9999999.9
REAL, DIMENSION(:), ALLOCATABLE :: dp_smooth_factor
REAL, DIMENSION(max_masks,mask_xyz_dimension) :: &
mask_x = -1.0, mask_y = -1.0, mask_z = -1.0
REAL, DIMENSION(max_masks,3) :: &
mask_x_loop = -1.0, mask_y_loop = -1.0, mask_z_loop = -1.0
!
!-- internal mask arrays ("mask,dimension,selection")
REAL, DIMENSION(:,:,:), ALLOCATABLE :: mask, mask_loop
!$omp declare target(atmos_ocean_sign,bc_pt_t_val,constant_top_momentumflux, &
!$omp dt_3d,e_min,f,fs,g,humidity,ibc_p_b,ibc_p_t,intermediate_timestep_count,kappa,neutral, &
!$omp ocean, outflow_l,outflow_n,outflow_r,outflow_s,prandtl_layer, pt_reference, &
!$omp rho_reference, rif_min,rif_max,surface_pressure,tsc,turbulence, &
!$omp use_single_reference_value,use_surface_fluxes,use_top_fluxes,&
!$omp u_gtrans,v_gtrans,wall_adjustment,wall_adjustment_factor,wall_heatflux,max_pr_user)
SAVE
END MODULE control_parameters
MODULE cpulog
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables for cpu-time measurements
!------------------------------------------------------------------------------!
REAL :: initial_wallclock_time
TYPE logpoint
REAL :: isum, ivect, mean, mtime, mtimevec, sum, vector
INTEGER :: counts
CHARACTER (LEN=20) :: place
END TYPE logpoint
TYPE(logpoint), DIMENSION(100) :: log_point = logpoint( 0.0, 0.0, 0.0, &
0.0, 0.0, 0.0, 0.0, 0, ' ' ), &
log_point_s = logpoint( 0.0, 0.0, 0.0, &
0.0, 0.0, 0.0, 0.0, 0, ' ' )
SAVE
END MODULE cpulog
MODULE dvrp_variables
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables used with dvrp-software
!------------------------------------------------------------------------------!
CHARACTER (LEN=10) :: dvrp_output = 'rtsp', particle_color = 'none', &
particle_dvrpsize = 'none'
CHARACTER (LEN=20), DIMENSION(10) :: mode_dvrp = &
(/ ( ' ', i9 = 1,10 ) /)
CHARACTER (LEN=80) :: dvrp_directory = 'default', &
dvrp_file = 'default', &
dvrp_host = 'origin.rvs.uni-hannover.de', &
dvrp_password = '********', &
dvrp_username = ' '
INTEGER :: cluster_size = 1, dvrp_colortable_entries = 4, &
dvrp_colortable_entries_prt = 22, islice_dvrp, &
nx_dvrp, nxl_dvrp, nxr_dvrp, ny_dvrp, nyn_dvrp, nys_dvrp, &
nz_dvrp, pathlines_fadeintime = 5, pathlines_fadeouttime = 5, &
pathlines_linecount = 1000, pathlines_maxhistory = 40, &
pathlines_wavecount = 10, pathlines_wavetime = 50, &
vc_gradient_normals = 0, vc_mode = 0, vc_size_x = 2, &
vc_size_y = 2, vc_size_z = 2
INTEGER, DIMENSION(10) :: slicer_position_dvrp
LOGICAL :: cyclic_dvrp = .FALSE., dvrp_overlap, dvrp_total_overlap, &
local_dvrserver_running, lock_steering_update = .FALSE., &
use_seperate_pe_for_dvrp_output = .FALSE.
REAL :: clip_dvrp_l = 9999999.9, clip_dvrp_n = 9999999.9, &
clip_dvrp_r = 9999999.9, clip_dvrp_s = 9999999.9, &
superelevation = 1.0, superelevation_x = 1.0, &
superelevation_y = 1.0, vc_alpha = 38.0
REAL, DIMENSION(2) :: color_interval = (/ 0.0, 1.0 /), &
dvrpsize_interval = (/ 0.0, 1.0 /)
REAL, DIMENSION(3) :: groundplate_color = (/ 0.0, 0.6, 0.0 /), &
topography_color = (/ 0.8, 0.7, 0.6 /)
#if defined( __decalpha )
REAL, DIMENSION(2,10) :: slicer_range_limits_dvrp = RESHAPE( (/ &
-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, &
-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, &
-1.0, 1.0, -1.0, 1.0 /), (/ 2, 10 /) )
REAL, DIMENSION(3,10) :: isosurface_color = RESHAPE( (/ &
0.9, 0.9, 0.9, 0.8, 0.1, 0.1, 0.1, 0.1, 0.8, &
0.1, 0.8, 0.1, 0.6, 0.1, 0.1, 0.1, 0.1, 0.6, &
0.1, 0.6, 0.1, 0.4, 0.1, 0.1, 0.1, 0.1, 0.4, &
0.1, 0.4, 0.1 /), (/ 3, 10 /) )
REAL(4), DIMENSION(2,100) :: interval_values_dvrp, interval_h_dvrp = &
RESHAPE( (/ 270.0, 225.0, 225.0, 180.0, &
70.0, 25.0, 25.0, -25.0, &
( 0.0, i9 = 1, 192 ) /), &
(/ 2, 100 /) ), &
interval_l_dvrp = 0.5, interval_s_dvrp = 1.0,&
interval_a_dvrp = 0.0, &
interval_values_dvrp_prt, &
interval_h_dvrp_prt = RESHAPE( &
(/ 270.0, 225.0, 225.0, 180.0, 70.0, 25.0, &
25.0, -25.0, ( 0.0, i9 = 1, 192 ) /), &
(/ 2, 100 /) ), &
interval_l_dvrp_prt = 0.5, &
interval_s_dvrp_prt = 1.0, &
interval_a_dvrp_prt = 0.0
#else
REAL, DIMENSION(2,10) :: slicer_range_limits_dvrp
REAL, DIMENSION(3,10) :: isosurface_color
REAL(4), DIMENSION(2,100) :: interval_values_dvrp, &
interval_values_dvrp_prt, interval_h_dvrp, &
interval_h_dvrp_prt, interval_l_dvrp = 0.5, &
interval_l_dvrp_prt = 0.5, interval_s_dvrp = 1.0, &
interval_s_dvrp_prt = 1.0, interval_a_dvrp = 0.0, &
interval_a_dvrp_prt = 0.0
DATA slicer_range_limits_dvrp / -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, &
-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, &
-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, &
-1.0, 1.0 /
DATA isosurface_color / 0.9, 0.9, 0.9, 0.8, 0.1, 0.1, 0.1, 0.1, 0.8, &
0.1, 0.8, 0.1, 0.6, 0.1, 0.1, 0.1, 0.1, 0.6, &
0.1, 0.6, 0.1, 0.4, 0.1, 0.1, 0.1, 0.1, 0.4, &
0.1, 0.4, 0.1 /
DATA interval_h_dvrp / 270.0, 225.0, 225.0, 180.0, 70.0, 25.0, &
25.0, -25.0, 192 * 0.0 /
DATA interval_h_dvrp_prt / 270.0, 225.0, 225.0, 180.0, 70.0, 25.0, &
25.0, -25.0, 192 * 0.0 /
#endif
REAL(4), DIMENSION(:), ALLOCATABLE :: xcoor_dvrp, ycoor_dvrp, zcoor_dvrp
TYPE steering
CHARACTER (LEN=24) :: name
REAL(4) :: min, max
INTEGER :: imin, imax
END TYPE steering
TYPE(steering), DIMENSION(:), ALLOCATABLE :: steering_dvrp
SAVE
END MODULE dvrp_variables
MODULE grid_variables
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of grid spacings
!------------------------------------------------------------------------------!
REAL :: ddx, ddx2, dx = 1.0, dx2, ddy, ddy2, dy = 1.0, dy2
REAL, DIMENSION(:), ALLOCATABLE :: ddx2_mg, ddy2_mg
REAL, DIMENSION(:,:), ALLOCATABLE :: fwxm, fwxp, fwym, fwyp, fxm, fxp, &
fym, fyp, wall_e_x, wall_e_y, &
wall_u, wall_v, wall_w_x, wall_w_y, &
zu_s_inner, zw_w_inner
!$omp declare target(dx,ddx,ddx2,dy,ddy,ddy2,fxm,fxp, &
!$omp fym,fyp,fwxm,fwxp,fwym,fwyp,wall_e_x,wall_e_y,wall_u,wall_v,wall_w_x,wall_w_y)
SAVE
END MODULE grid_variables
MODULE indices
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of array bounds, number of gridpoints, and wall flag arrays
!------------------------------------------------------------------------------!
INTEGER :: i_left, i_right, j_north, j_south, nbgp = 3, ngp_sums, nnx, &
nx = 0, nx_a, nx_o, nxl, nxlg, nxlu, nxr, nxrg, nx_on_file, &
nny, ny = 0, ny_a, ny_o, nyn, nyng, nys, nysg, nysv, &
ny_on_file, nnz, nz = 0, nzb, nzb_diff, nzb_max, nzt, nzt_diff
INTEGER( KIND = SELECTED_INT_KIND(18) ), DIMENSION(:), ALLOCATABLE :: &
ngp_3d, ngp_3d_inner ! need to have 64 bit for grids > 2E9
INTEGER, DIMENSION(:), ALLOCATABLE :: &
ngp_2dh, nxl_mg, nxr_mg, nyn_mg, nys_mg, nzt_mg
INTEGER, DIMENSION(:,:), ALLOCATABLE :: ngp_2dh_outer, ngp_2dh_s_inner, &
mg_loc_ind, nzb_diff_s_inner, nzb_diff_s_outer, nzb_diff_u, &
nzb_diff_v, nzb_inner, nzb_outer, nzb_s_inner, nzb_s_outer, &
nzb_u_inner, nzb_u_outer, nzb_v_inner, nzb_v_outer, &
nzb_w_inner, nzb_w_outer, nzb_2d
INTEGER, DIMENSION(:,:,:), POINTER :: flags
INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: wall_flags_0, wall_flags_00
INTEGER, DIMENSION(:,:,:), ALLOCATABLE, TARGET :: &
wall_flags_1, wall_flags_2, wall_flags_3, wall_flags_4, &
wall_flags_5, wall_flags_6, wall_flags_7, wall_flags_8, &
wall_flags_9, wall_flags_10
REAL, DIMENSION(:,:,:), ALLOCATABLE :: rflags_s_inner, rflags_invers
!Scalars
!$omp declare target(i_left, i_right, j_north, j_south, nzb,&
!$omp nx,nxl,nxr,nxlg,ny,nyn,nyng,nxrg,nys,nysg,nz,nzt,nzt_diff)
!arrays
!$omp declare target(ngp_2dh,ngp_2dh_s_inner,nzb_diff_s_inner,nzb_diff_s_outer, &
!$omp nzb_diff_u,nzb_diff_v,nzb_s_inner,nzb_s_outer,nzb_u_inner,nzb_u_outer, &
!$omp nzb_v_inner,nzb_v_outer,nzb_w_inner,nzb_w_outer,rflags_invers,rflags_s_inner,wall_flags_0,wall_flags_00)
SAVE
END MODULE indices
MODULE interfaces
!------------------------------------------------------------------------------!
! Description:
! ------------
! Interfaces for special subroutines which use optional parameters
!------------------------------------------------------------------------------!
INTERFACE
SUBROUTINE cpu_log( log_event, place, modus, barrierwait )
USE cpulog
CHARACTER (LEN=*) :: modus, place
CHARACTER (LEN=*), OPTIONAL :: barrierwait
TYPE(logpoint) :: log_event
END SUBROUTINE cpu_log
END INTERFACE
INTERFACE
SUBROUTINE global_min_max ( i1, i2, j1, j2, k1, k2, feld, mode, offset, &
wert, wert_ijk, wert1, wert1_ijk )
CHARACTER (LEN=*), INTENT(IN) :: mode
INTEGER, INTENT(IN) :: i1, i2, j1, j2, k1, k2
INTEGER :: wert_ijk(3)
INTEGER, OPTIONAL :: wert1_ijk(3)
REAL :: offset, wert
REAL, OPTIONAL :: wert1
REAL, INTENT(IN) :: feld(i1:i2,j1:j2,k1:k2)
END SUBROUTINE global_min_max
END INTERFACE
SAVE
END MODULE interfaces
MODULE pointer_interfaces
!------------------------------------------------------------------------------!
! Description:
! ------------
! Interfaces for subroutines with pointer arguments called in
! prognostic_equations
!------------------------------------------------------------------------------!
INTERFACE
SUBROUTINE advec_s_bc( sk, sk_char )
CHARACTER (LEN=*), INTENT(IN) :: sk_char
#if defined( __nopointer )
REAL, DIMENSION(:,:,:) :: sk
#else
REAL, DIMENSION(:,:,:), POINTER :: sk
#endif
END SUBROUTINE advec_s_bc
END INTERFACE
SAVE
END MODULE pointer_interfaces
MODULE model_1d
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables for the 1D-model
!------------------------------------------------------------------------------!
INTEGER :: current_timestep_number_1d = 0, damp_level_ind_1d
LOGICAL :: run_control_header_1d = .FALSE., stop_dt_1d = .FALSE.
REAL :: damp_level_1d = -1.0, dt_1d = 60.0, dt_max_1d = 300.0, &
dt_pr_1d = 9999999.9, dt_run_control_1d = 60.0, &
end_time_1d = 864000.0, old_dt_1d = 1.0E-10, &
qs1d, simulated_time_1d = 0.0, time_pr_1d = 0.0, &
time_run_control_1d = 0.0, ts1d, us1d, usws1d, &
vsws1d, z01d, z0h1d
REAL, DIMENSION(:), ALLOCATABLE :: e1d, e1d_p, kh1d, km1d, l_black, l1d, &
rif1d, te_e, te_em, te_u, te_um, te_v, &
te_vm, u1d, u1d_p, v1d, v1d_p
SAVE
END MODULE model_1d
MODULE netcdf_control
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of parameters and variables for netcdf control.
!------------------------------------------------------------------------------!
USE control_parameters
#if defined( __netcdf )
USE netcdf
#endif
INTEGER, PARAMETER :: dopr_norm_num = 7, dopts_num = 29, dots_max = 100
INTEGER :: dots_num = 23
CHARACTER (LEN=6), DIMENSION(dopr_norm_num) :: dopr_norm_names = &
(/ 'wpt0 ', 'ws2 ', 'tsw2 ', 'ws3 ', 'ws2tsw', 'wstsw2', &
'z_i ' /)
CHARACTER (LEN=6), DIMENSION(dopr_norm_num) :: dopr_norm_longnames = &
(/ 'wpt0 ', 'w*2 ', 't*w2 ', 'w*3 ', 'w*2t*w', 'w*t*w2', &
'z_i ' /)
CHARACTER (LEN=7), DIMENSION(dopts_num) :: dopts_label = &
(/ 'tnpt ', 'x_ ', 'y_ ', 'z_ ', 'z_abs ', 'u ', &
'v ', 'w ', 'u" ', 'v" ', 'w" ', 'npt_up ', &
'w_up ', 'w_down ', 'radius ', 'r_min ', 'r_max ', 'npt_max', &
'npt_min', 'x*2 ', 'y*2 ', 'z*2 ', 'u*2 ', 'v*2 ', &
'w*2 ', 'u"2 ', 'v"2 ', 'w"2 ', 'npt*2 ' /)
CHARACTER (LEN=7), DIMENSION(dopts_num) :: dopts_unit = &
(/ 'number ', 'm ', 'm ', 'm ', 'm ', 'm/s ', &
'm/s ', 'm/s ', 'm/s ', 'm/s ', 'm/s ', 'number ', &
'm/s ', 'm/s ', 'm ', 'm ', 'm ', 'number ', &
'number ', 'm2 ', 'm2 ', 'm2 ', 'm2/s2 ', 'm2/s2 ', &
'm2/s2 ', 'm2/s2 ', 'm2/s2 ', 'm2/s2 ', 'number2' /)
CHARACTER (LEN=7), DIMENSION(dots_max) :: dots_label = &
(/ 'E ', 'E* ', 'dt ', 'u* ', 'th* ', 'umax ', &
'vmax ', 'wmax ', 'div_new', 'div_old', 'z_i_wpt', 'z_i_pt ', &
'w* ', 'w"pt"0 ', 'w"pt" ', 'wpt ', 'pt(0) ', 'pt(zp) ', &
'w"u"0 ', 'w"v"0 ', 'w"q"0 ', 'mo_L ', 'q* ', &
( 'unknown', i9 = 1, dots_max-23 ) /)
CHARACTER (LEN=7), DIMENSION(dots_max) :: dots_unit = &
(/ 'm2/s2 ', 'm2/s2 ', 's ', 'm/s ', 'K ', 'm/s ', &
'm/s ', 'm/s ', 's-1 ', 's-1 ', 'm ', 'm ', &
'm/s ', 'K m/s ', 'K m/s ', 'K m/s ', 'K ', 'K ', &
'm2/s2 ', 'm2/s2 ', 'kg m/s ', 'm ', 'kg/kg ', &
( 'unknown', i9 = 1, dots_max-23 ) /)
CHARACTER (LEN=9), DIMENSION(300) :: dopr_unit = 'unknown'
CHARACTER (LEN=7), DIMENSION(0:1,100) :: do2d_unit, do3d_unit
CHARACTER (LEN=16), DIMENSION(25) :: prt_var_names = &
(/ 'pt_age ', 'pt_dvrp_size ', 'pt_origin_x ', &
'pt_origin_y ', 'pt_origin_z ', 'pt_radius ', &
'pt_speed_x ', 'pt_speed_y ', 'pt_speed_z ', &
'pt_weight_factor', 'pt_x ', 'pt_y ', &
'pt_z ', 'pt_color ', 'pt_group ', &
'pt_tailpoints ', 'pt_tail_id ', 'pt_density_ratio', &
'pt_exp_arg ', 'pt_exp_term ', 'not_used ', &
'not_used ', 'not_used ', 'not_used ', &
'not_used ' /)
CHARACTER (LEN=16), DIMENSION(25) :: prt_var_units = &
(/ 'seconds ', 'meters ', 'meters ', &
'meters ', 'meters ', 'meters ', &
'm/s ', 'm/s ', 'm/s ', &
'factor ', 'meters ', 'meters ', &
'meters ', 'none ', 'none ', &
'none ', 'none ', 'ratio ', &
'none ', 'none ', 'not_used ', &
'not_used ', 'not_used ', 'not_used ', &
'not_used ' /)
INTEGER :: id_dim_prtnum, id_dim_time_pr, id_dim_time_prt, &
id_dim_time_pts, id_dim_time_sp, id_dim_time_ts, id_dim_x_sp, &
id_dim_y_sp, id_dim_zu_sp, id_dim_zw_sp, id_set_pr, &
id_set_prt, id_set_pts, id_set_sp, id_set_ts, id_var_prtnum, &
id_var_rnop_prt, id_var_time_pr, id_var_time_prt, &
id_var_time_pts, id_var_time_sp, id_var_time_ts, id_var_x_sp, &
id_var_y_sp, id_var_zu_sp, id_var_zw_sp, nc_stat
INTEGER, DIMENSION(0:1) :: id_dim_time_xy, id_dim_time_xz, &
id_dim_time_yz, id_dim_time_3d, id_dim_x_xy, id_dim_xu_xy, &
id_dim_x_xz, id_dim_xu_xz, id_dim_x_yz, id_dim_xu_yz, &
id_dim_x_3d, id_dim_xu_3d, id_dim_y_xy, id_dim_yv_xy, &
id_dim_y_xz, id_dim_yv_xz, id_dim_y_yz, id_dim_yv_yz, &
id_dim_y_3d, id_dim_yv_3d, id_dim_zu_xy, id_dim_zu1_xy, &
id_dim_zu_xz, id_dim_zu_yz, id_dim_zu_3d, id_dim_zw_xy, &
id_dim_zw_xz, id_dim_zw_yz, id_dim_zw_3d, id_set_xy, &
id_set_xz, id_set_yz, id_set_3d, id_var_ind_x_yz, &
id_var_ind_y_xz, id_var_ind_z_xy, id_var_time_xy, &
id_var_time_xz, id_var_time_yz, id_var_time_3d, id_var_x_xy, &
id_var_xu_xy, id_var_x_xz, id_var_xu_xz, id_var_x_yz, &
id_var_xu_yz, id_var_x_3d, id_var_xu_3d, id_var_y_xy, &
id_var_yv_xy, id_var_y_xz, id_var_yv_xz, id_var_y_yz, &
id_var_yv_yz, id_var_y_3d, id_var_yv_3d, id_var_zusi_xy, &
id_var_zusi_3d, id_var_zu_xy, id_var_zu1_xy, id_var_zu_xz, &
id_var_zu_yz, id_var_zu_3d, id_var_zwwi_xy, id_var_zwwi_3d, &
id_var_zw_xy, id_var_zw_xz, id_var_zw_yz, id_var_zw_3d
INTEGER, DIMENSION(10) :: id_var_dospx, id_var_dospy
INTEGER, DIMENSION(20) :: id_var_prt
INTEGER, DIMENSION(11) :: nc_precision
INTEGER, DIMENSION(dopr_norm_num) :: id_var_norm_dopr
INTEGER, DIMENSION(dopts_num,0:10) :: id_var_dopts
INTEGER, DIMENSION(0:1,100) :: id_var_do2d, id_var_do3d
INTEGER, DIMENSION(100,0:9) :: id_dim_z_pr, id_var_dopr, &
id_var_z_pr
INTEGER, DIMENSION(dots_max,0:9) :: id_var_dots
!
!-- masked output
CHARACTER (LEN=7), DIMENSION(max_masks,0:1,100) :: domask_unit
LOGICAL :: output_for_t0 = .FALSE.
INTEGER, DIMENSION(1:max_masks,0:1) :: id_dim_time_mask, id_dim_x_mask, &
id_dim_xu_mask, id_dim_y_mask, id_dim_yv_mask, id_dim_zu_mask, &
id_dim_zw_mask, &
id_set_mask, &
id_var_time_mask, id_var_x_mask, id_var_xu_mask, &
id_var_y_mask, id_var_yv_mask, id_var_zu_mask, id_var_zw_mask, &
id_var_zusi_mask, id_var_zwwi_mask
INTEGER, DIMENSION(1:max_masks,0:1,100) :: id_var_domask
SAVE
END MODULE netcdf_control
MODULE particle_attributes
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables used to compute particle transport
!------------------------------------------------------------------------------!
USE precision_kind
CHARACTER (LEN=15) :: bc_par_lr = 'cyclic', bc_par_ns = 'cyclic', &
bc_par_b = 'reflect', bc_par_t = 'absorb', &
collision_kernel = 'none'
#if defined( __parallel )
INTEGER :: mpi_particle_type
#endif
INTEGER :: deleted_particles = 0, deleted_tails = 0, &
dissipation_classes = 10, ibc_par_lr, &
ibc_par_ns, ibc_par_b, ibc_par_t, iran_part = -1234567, &
maximum_number_of_particles = 1000, &
maximum_number_of_tailpoints = 100, &
maximum_number_of_tails = 0, &
number_of_initial_particles = 0, number_of_particles = 0, &
number_of_particle_groups = 1, number_of_tails = 0, &
number_of_initial_tails = 0, offset_ocean_nzt = 0, &
offset_ocean_nzt_m1 = 0, particles_per_point = 1, &
particle_file_count = 0, radius_classes = 20, &
skip_particles_for_tail = 100, sort_count = 0, &
total_number_of_particles, total_number_of_tails = 0, &
trlp_count_sum, trlp_count_recv_sum, trrp_count_sum, &
trrp_count_recv_sum, trsp_count_sum, trsp_count_recv_sum, &
trnp_count_sum, trnp_count_recv_sum
INTEGER, PARAMETER :: max_number_of_particle_groups = 10
INTEGER, DIMENSION(:), ALLOCATABLE :: new_tail_id
INTEGER, DIMENSION(:,:,:), ALLOCATABLE :: prt_count, prt_start_index
LOGICAL :: hall_kernel = .FALSE., palm_kernel = .FALSE., &
particle_advection = .FALSE., random_start_position = .FALSE., &
read_particles_from_restartfile = .TRUE., &
uniform_particles = .TRUE., use_kernel_tables = .FALSE., &
use_particle_tails = .FALSE., use_sgs_for_particles = .FALSE., &
wang_kernel = .FALSE., write_particle_statistics = .FALSE.
LOGICAL, DIMENSION(max_number_of_particle_groups) :: &
vertical_particle_advection = .TRUE.
LOGICAL, DIMENSION(:), ALLOCATABLE :: particle_mask, tail_mask
REAL :: c_0 = 3.0, dt_min_part = 0.0002, dt_prel = 9999999.9, &
dt_sort_particles = 0.0, dt_write_particle_data = 9999999.9, &
dvrp_psize = 9999999.9, end_time_prel = 9999999.9, &
initial_weighting_factor = 1.0, &
maximum_tailpoint_age = 100000.0, &
minimum_tailpoint_distance = 0.0, &
particle_advection_start = 0.0, sgs_wfu_part = 0.3333333, &
sgs_wfv_part = 0.3333333, sgs_wfw_part = 0.3333333, &
time_prel = 0.0, time_sort_particles = 0.0, &
time_write_particle_data = 0.0
REAL, DIMENSION(max_number_of_particle_groups) :: &
density_ratio = 9999999.9, pdx = 9999999.9, pdy = 9999999.9, &
pdz = 9999999.9, psb = 9999999.9, psl = 9999999.9, &
psn = 9999999.9, psr = 9999999.9, pss = 9999999.9, &
pst = 9999999.9, radius = 9999999.9
REAL, DIMENSION(:,:,:), ALLOCATABLE :: particle_tail_coordinates
TYPE particle_type
SEQUENCE
REAL :: age, age_m, dt_sum, dvrp_psize, e_m, origin_x, origin_y, &
origin_z, radius, rvar1, rvar2, rvar3, speed_x, speed_y, &
speed_z, weight_factor, x, y, z
INTEGER :: class, group, tailpoints, tail_id
END TYPE particle_type
TYPE(particle_type), DIMENSION(:), ALLOCATABLE :: initial_particles
TYPE(particle_type), DIMENSION(:), ALLOCATABLE, TARGET :: part_1, part_2
TYPE(particle_type), DIMENSION(:), POINTER :: particles
TYPE particle_groups_type
SEQUENCE
REAL :: density_ratio, radius, exp_arg, exp_term
END TYPE particle_groups_type
TYPE(particle_groups_type), DIMENSION(max_number_of_particle_groups) ::&
particle_groups
!$omp declare target(use_sgs_for_particles,wang_kernel)
SAVE
END MODULE particle_attributes
MODULE pegrid
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables which define processor topology and the exchange of
! ghost point layers. This modules must be placed in all routines which contain
! MPI-calls.
!------------------------------------------------------------------------------!
#if defined( __parallel ) && ! defined ( __check )
#if defined( __lc )
USE MPI
#else
INCLUDE "mpif.h"
#endif
#endif
CHARACTER(LEN=2) :: send_receive = 'al'
CHARACTER(LEN=5) :: myid_char = ''
INTEGER :: acc_rank, comm1dx, comm1dy, comm2d, comm_inter, &
comm_palm, id_inflow = 0, id_recycling = 0, ierr, &
myid = 0, myidx = 0, myidy = 0, ndim = 2, ngp_a, &
ngp_o, ngp_xy, ngp_y, npex = -1, npey = -1, &
numprocs = 1, numprocs_previous_run = -1, &
num_acc_per_node = 0, pleft, pnorth, pright, psouth, &
req_count = 0, sendrecvcount_xy, sendrecvcount_yz, &
sendrecvcount_zx, sendrecvcount_zyd, &
sendrecvcount_yxd, target_id, tasks_per_node = -9999, &
threads_per_task = 1, type_x, type_x_int, type_xy, &
type_y, type_y_int
INTEGER :: pdims(2) = 1, req(100)
INTEGER, DIMENSION(:,:), ALLOCATABLE :: hor_index_bounds, &
hor_index_bounds_previous_run
LOGICAL :: background_communication =.FALSE., collective_wait = .FALSE., &
sendrecv_in_background = .FALSE.
#if defined( __parallel )
#if defined( __mpi2 )
CHARACTER (LEN=MPI_MAX_PORT_NAME) :: port_name
#endif
INTEGER :: ibuf(12), pcoord(2)
#if ! defined ( __check )
INTEGER :: status(MPI_STATUS_SIZE)
INTEGER, DIMENSION(MPI_STATUS_SIZE,100) :: wait_stat
#endif
INTEGER, DIMENSION(:), ALLOCATABLE :: ngp_yz, type_xz, type_yz
LOGICAL :: left_border_pe = .FALSE., north_border_pe = .FALSE., &
reorder = .TRUE., right_border_pe = .FALSE., &
south_border_pe = .FALSE.
LOGICAL, DIMENSION(2) :: cyclic = (/ .TRUE. , .TRUE. /), &
remain_dims
#endif
!$omp declare target(threads_per_task)
SAVE
END MODULE pegrid
MODULE profil_parameter
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of variables which control PROFIL-output
!------------------------------------------------------------------------------!
INTEGER, PARAMETER :: crmax = 100
CHARACTER (LEN=20), DIMENSION(20) :: cross_ts_profiles = &
(/ ' E E* ', ' dt ', &
' u* w* ', ' th* ', &
' umax vmax wmax ', ' div_old div_new ', &
' z_i_wpt z_i_pt ', ' w"pt"0 w"pt" wpt ', &
' pt(0) pt(zp) ', ' splux spluy spluz ', &
' L ', &
( ' ', i9 = 1, 9 ) /)
CHARACTER (LEN=100), DIMENSION(crmax) :: cross_profiles = &
(/ ' u v ', &
' pt ', &
' w"pt" w*pt* w*pt*BC wpt wptBC ', &
' w"u" w*u* wu w"v" w*v* wv ', &
' km kh ', &
' l ', &
( ' ', i9 = 1, 94 ) /)
INTEGER :: profile_columns = 2, profile_rows = 3, profile_number = 0
INTEGER :: cross_ts_numbers(crmax,crmax) = 0, &
cross_ts_number_count(crmax) = 0, &
dopr_index(300) = 0, dopr_initial_index(300) = 0, &
dots_crossindex(100) = 0, dots_index(100) = 0
REAL :: cross_ts_uymax(20) = &
(/ 999.999, 999.999, 999.999, 999.999, 999.999, &
999.999, 999.999, 999.999, 999.999, 999.999, &
999.999, 999.999, 999.999, 999.999, 999.999, &
999.999, 999.999, 999.999, 999.999, 999.999 /),&
cross_ts_uymax_computed(20) = 999.999, &
cross_ts_uymin(20) = &
(/ 999.999, 999.999, 999.999, -5.000, 999.999, &
999.999, 0.000, 999.999, 999.999, 999.999, &
999.999, 999.999, 999.999, 999.999, 999.999, &
999.999, 999.999, 999.999, 999.999, 999.999 /),&
cross_ts_uymin_computed(20) = 999.999
SAVE
END MODULE profil_parameter
MODULE spectrum
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of quantities used for computing spectra
!------------------------------------------------------------------------------!
CHARACTER (LEN=6), DIMENSION(1:5) :: header_char = (/ 'PS(u) ', 'PS(v) ',&
'PS(w) ', 'PS(pt)', 'PS(q) ' /)
CHARACTER (LEN=2), DIMENSION(10) :: spectra_direction = 'x'
CHARACTER (LEN=10), DIMENSION(10) :: data_output_sp = ' '
CHARACTER (LEN=25), DIMENSION(1:5) :: utext_char = &
(/ '-power spectrum of u ', &
'-power spectrum of v ', &
'-power spectrum of w ', &
'-power spectrum of ^1185 ', &
'-power spectrum of q ' /)
CHARACTER (LEN=39), DIMENSION(1:5) :: ytext_char = &
(/ 'k ^2236 ^2566^2569<u(k) in m>2s>->2 ', &
'k ^2236 ^2566^2569<v(k) in m>2s>->2 ', &
'k ^2236 ^2566^2569<w(k) in m>2s>->2 ', &
'k ^2236 ^2566^2569<^1185(k) in m>2s>->2', &
'k ^2236 ^2566^2569<q(k) in m>2s>->2 ' /)
INTEGER :: klist_x = 0, klist_y = 0, n_sp_x = 0, n_sp_y = 0
INTEGER :: comp_spectra_level(100) = 999999, &
lstyles(100) = (/ 0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8, &
0, 7, 3, 10, 1, 4, 9, 2, 6, 8 /), &
plot_spectra_level(100) = 999999
REAL :: time_to_start_sp = 0.0
SAVE
END MODULE spectrum
MODULE statistics
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of statistical quantities, e.g. global sums
!------------------------------------------------------------------------------!
CHARACTER (LEN=40) :: region(0:9)
INTEGER :: pr_palm = 80, statistic_regions = 0
INTEGER :: u_max_ijk(3), v_max_ijk(3), w_max_ijk(3)
LOGICAL :: flow_statistics_called = .FALSE.
REAL :: u_max, v_max, w_max
REAL, DIMENSION(:), ALLOCATABLE :: sums_divnew_l, sums_divold_l, &
weight_substep, weight_pres
REAL, DIMENSION(:,:), ALLOCATABLE :: sums, sums_wsts_bc_l, ts_value, &
sums_wsus_ws_l, sums_wsvs_ws_l, &
sums_us2_ws_l, sums_vs2_ws_l, &
sums_ws2_ws_l, &
sums_wsnrs_ws_l, &
sums_wspts_ws_l, &
sums_wssas_ws_l, &
sums_wsqs_ws_l, &
sums_wsqrs_ws_l
REAL, DIMENSION(:,:,:), ALLOCATABLE :: hom_sum, rmask, spectrum_x, &
spectrum_y, sums_l, sums_l_l, &
sums_up_fraction_l
REAL, DIMENSION(:,:,:,:), ALLOCATABLE :: hom
!$omp declare target(hom,pr_palm,rmask,sums, sums_l,weight_substep, weight_pres)
SAVE
END MODULE statistics
MODULE transpose_indices
!------------------------------------------------------------------------------!
! Description:
! ------------
! Definition of indices for transposed arrays
!------------------------------------------------------------------------------!
INTEGER :: nxl_y, nxl_yd, nxl_z, nxr_y, nxr_yd, nxr_z, nyn_x, nyn_z, &
nys_x, nys_z, nzb_x, nzb_y, nzb_yd, nzt_x, nzt_y, nzt_yd
!$omp declare target(nxl_y,nxl_z,nxr_y,nxr_z,nyn_x,nyn_z,nys_x,nys_z,nzb_x,nzb_y,nzt_x,nzt_y)
SAVE
END MODULE transpose_indices
|
./SPEChpc/benchspec/HPC/613.soma_s/src/rng.c | /* Copyright (C) 2016 Ludwig Schneider
Copyright (C) 2016 Ulrich Welling
Copyright (C) 2016 Marcel Langenberg
Copyright (C) 2016 Fabien Leonforte
Copyright (C) 2016 Juan Orozco
Copyright (C) 2016 Yongzhi Ren
This file is part of SOMA.
SOMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SOMA 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 SOMA. If not, see <http://www.gnu.org/licenses/>.
*/
//! \file rng.c
//! \brief Implementation of rng.h
#include "rng.h"
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "phase.h"
#include "allocator.h"
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
/*! Random number generator PCG32
\param rng State for PRNG
\return PRN
*/
uint32_t pcg32_random(PCG_STATE * rng)
{
const uint64_t old = rng->state;
// Advance internal state
rng->state = ((uint64_t) rng->state) * 0X5851F42D4C957F2DULL;
rng->state += (rng->inc | 1);
const uint32_t xorshifted = ((old >> 18u) ^ old) >> 27u;
const uint32_t rot = old >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
int soma_seed_rng(PCG_STATE * rng, uint64_t seed, uint64_t stream)
{
rng->inc = stream*2 + 1;
rng->state = 0;
pcg32_random(rng);
rng->state += seed;
pcg32_random(rng);
//Improve quality of first random numbers
pcg32_random(rng);
return 0;
}
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
unsigned int soma_rng_uint_max()
{
return 4294967295U;
}
/*Random number generator Mersenne-Twister*/
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
int soma_seed_rng_mt(PCG_STATE *rng, MERSENNE_TWISTER_STATE *mt_rng)
{
mt_rng->internal_index = MTMAX_num_int_state +1;
mt_rng->A[0] = 0;
mt_rng->A[1] = 0x9908b0df;
for (int i=0;i< MTMAX_num_int_state;i++){
mt_rng->internal_state[i] = pcg32_random(rng);
}
return 0;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
unsigned int soma_mersenne_twister(MERSENNE_TWISTER_STATE *mt_rng)
{
unsigned int M = 397;
uint32_t HI = 0x80000000;
uint32_t LO = 0x7fffffff;
uint32_t e;
/* The Mersenne-Twister stete of 624 is seeded with soma_seed_rng_mt()
* which is called in the init.c by function init_values()
*/
if (M>MTMAX_num_int_state) M= MTMAX_num_int_state/2;
if (mt_rng->internal_index >= MTMAX_num_int_state) {
/* Berechne neuen Zustandsvektor */
uint32_t h;
for (unsigned int i=0; i<MTMAX_num_int_state-M; ++i) {
h = (mt_rng->internal_state[i] & HI) | (mt_rng->internal_state[i+1] & LO); // Crashes HERE!!!
mt_rng->internal_state[i] = mt_rng->internal_state[i+M] ^ (h >> 1) ^ mt_rng->A[h & 1];
}
for (unsigned int i=MTMAX_num_int_state-M; i<MTMAX_num_int_state-1; ++i) {
h = (mt_rng->internal_state[i] & HI) | (mt_rng->internal_state[i+1] & LO);
mt_rng->internal_state[i] = mt_rng->internal_state[ i + (M-MTMAX_num_int_state) ] ^ (h >> 1) ^ mt_rng->A[h & 1];
}
h = (mt_rng->internal_state[MTMAX_num_int_state-1] & HI) | (mt_rng->internal_state[0] & LO);
mt_rng->internal_state[MTMAX_num_int_state-1] = mt_rng->internal_state[M-1] ^ (h >> 1) ^ mt_rng->A[h & 1];
mt_rng->internal_index = 0;
}
e = mt_rng->internal_state[mt_rng->internal_index++];
/* Tempering */
e ^= (e >> 11);
e ^= (e << 7) & 0x9d2c5680;
e ^= (e << 15) & 0xefc60000;
e ^= (e >> 18);
return e;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
unsigned int soma_rng_uint_max_mt()
{
return 0x80000000;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
unsigned int soma_rng_uint(RNG_STATE * state, enum enum_pseudo_random_number_generator rng_type)
{
switch(rng_type){
case pseudo_random_number_generator__NULL : return (unsigned int) pcg32_random(&(state->default_state));
case pseudo_random_number_generator_arg_PCG32 : return (unsigned int) pcg32_random(&(state->default_state));
case pseudo_random_number_generator_arg_MT : return (unsigned int) soma_mersenne_twister(state->mt_state);
case pseudo_random_number_generator_arg_TT800 : return (unsigned int) soma_rng_tt800(state->tt800_state);
}
return (unsigned)-1;
}
soma_scalar_t soma_rng_soma_scalar(RNG_STATE * rng, enum enum_pseudo_random_number_generator rng_type)
{
return ldexp(soma_rng_uint(rng, rng_type), -32);
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
/*! generate 3D vector, 2 times Box-Mueller Transform, discards one value
\param rng RNG State
\param rng_type Type of the PRNG
\param x result for X
\param y result for Y
\param z result for Z
*/
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
void soma_normal_vector(RNG_STATE * rng, enum enum_pseudo_random_number_generator rng_type, soma_scalar_t *x, soma_scalar_t *y, soma_scalar_t *z)
{
soma_scalar_t u1, u2, u3, u4, r1, r2;
u1 = 2*soma_rng_soma_scalar(rng, rng_type )-1.;
u2 = 2*soma_rng_soma_scalar(rng, rng_type )-1.;
u3 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
u4 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
r1 = u1*u1+u2*u2;
r2 = u3*u3+u4*u4;
while(r1>1){
u1 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
u2 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
r1 = u1*u1+u2*u2;
}
while(r2>1){
u3 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
u4 = 2*soma_rng_soma_scalar(rng, rng_type)-1.;
r2 = u3*u3+u4*u4;
}
const soma_scalar_t root1 = sqrt( -2.0 * log(r1) / r1 );
const soma_scalar_t root2 = sqrt( -2.0 * log(r2) / r2 );
*x = root1 * u1;
*y = root1 * u2;
*z = root2 * u3;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
/*! generate 3D vector, with a distribution that just has the 2nd and 4th moment of a gaussian
\param rng RNG State
\param rng_type Type of the PRNG
\param x result for X
\param y result for Y
\param z result for Z
*/
void soma_normal_vector2(RNG_STATE * rng, enum enum_pseudo_random_number_generator rng_type, soma_scalar_t *x, soma_scalar_t *y, soma_scalar_t *z)
{
// the two factors are connected to ensure a 2nd moment of 1:
// sfactor = (3-3*qfactor**2/7.0)**0.5
soma_scalar_t u1 = 2.0*soma_rng_soma_scalar(rng, rng_type )-1.;
soma_scalar_t u2 = 2.0*soma_rng_soma_scalar(rng, rng_type )-1.;
soma_scalar_t u3 = 2.0*soma_rng_soma_scalar(rng, rng_type )-1.;
soma_scalar_t u4 = 2.0*soma_rng_soma_scalar(rng, rng_type )-1.;
soma_scalar_t u5 = 2.0*soma_rng_soma_scalar(rng, rng_type)-1.;
soma_scalar_t u6 = 2.0*soma_rng_soma_scalar(rng, rng_type )-1.;
*x = 1.97212*u1*u1*u1 + 1.1553052583624814 * u2;
*y = 1.97212*u3*u3*u3 + 1.1553052583624814 * u4;
*z = 1.97212*u5*u5*u5 + 1.1553052583624814 * u6;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
int soma_seed_rng_tt800(PCG_STATE *rng, MTTSTATE *tt800_rng){
tt800_rng->internal_index = MTMAX_num_int_state +1;
tt800_rng->A[0] = 0;
tt800_rng->A[1] = 0x8ebfd028;
for (int k=0;k<TT_num_int_state;k++){
tt800_rng->internal_state[k] = (uint32_t) pcg32_random(rng);
}
return 0;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
unsigned int soma_rng_tt800(MTTSTATE *itt800_rng){
uint32_t M=7;
uint32_t e;
uint32_t k=0;
if (itt800_rng->internal_index >= TT_num_int_state) {
if (itt800_rng->internal_index > TT_num_int_state) {
uint32_t r = 9;
uint32_t s = 3402;
for (k=0; k<TT_num_int_state; ++k) {
r = 509845221 * r + 3;
s *= s + 1;
itt800_rng->internal_state[k] = s + (r >> 10);
}
}
for (k=0; k<TT_num_int_state-M; ++k){
itt800_rng->internal_state[k] = itt800_rng->internal_state[k+M] ^ (itt800_rng->internal_state[k] >> 1) ^ itt800_rng->A[itt800_rng->internal_state[k] & 1];
}
for (k=TT_num_int_state-M; k<TT_num_int_state; ++k){
itt800_rng->internal_state[k] = itt800_rng->internal_state[k+(M-TT_num_int_state)] ^ (itt800_rng->internal_state[k] >> 1) ^ itt800_rng->A[itt800_rng->internal_state[k] & 1];
}
itt800_rng->internal_index = 0;
}
e = itt800_rng->internal_state[itt800_rng->internal_index++];
/* Tempering */
e ^= (e << 7) & 0x2b5b2500;
e ^= (e << 15) & 0xdb8b0000;
e ^= (e >> 16);
return e;
}
unsigned int rng_state_serial_length(const struct Phase*const p)
{
unsigned int length = 0;
length += sizeof(PCG_STATE);
if( p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_MT )
length += sizeof(MERSENNE_TWISTER_STATE);
if( p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_TT800 )
length += sizeof(MTTSTATE);
return length;
}
int serialize_rng_state(const struct Phase*const p,const RNG_STATE*const state, unsigned char*const buffer)
{
unsigned int position = 0;
//default state
memcpy( buffer +position , &(state->default_state), sizeof(PCG_STATE) );
position += sizeof(PCG_STATE);
if( p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_MT)
{
memcpy( buffer+position , state->mt_state, sizeof(MERSENNE_TWISTER_STATE) );
position += sizeof(MERSENNE_TWISTER_STATE);
}
if(p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_TT800)
{
memcpy(buffer + position , state->tt800_state, sizeof(MTTSTATE));
position += sizeof(MTTSTATE);
}
return position;
}
int deserialize_rng_state(const struct Phase*const p,RNG_STATE*const state, const unsigned char*const buffer)
{
unsigned int position = 0;
//default state
memcpy( &(state->default_state),buffer +position , sizeof(PCG_STATE) );
position += sizeof(PCG_STATE);
state->mt_state = NULL;
state->tt800_state = NULL;
if( p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_MT)
{
/* state->mt_state = (MERSENNE_TWISTER_STATE*) malloc(sizeof(MERSENNE_TWISTER_STATE)); */
state->mt_state = alloc_MERSENNE_TWISTER_STATE_ptr(1);
MALLOC_ERROR_CHECK(state->mt_state, sizeof(MERSENNE_TWISTER_STATE));
memcpy( state->mt_state, buffer+position , sizeof(MERSENNE_TWISTER_STATE) );
position += sizeof(MERSENNE_TWISTER_STATE);
}
if(p->args.pseudo_random_number_generator_arg == pseudo_random_number_generator_arg_TT800)
{
/* state->tt800_state = (MTTSTATE*)malloc(sizeof(MTTSTATE)); */
state->tt800_state = alloc_MTTSTATE_ptr(1);
MALLOC_ERROR_CHECK(state->tt800_state, sizeof(MTTSTATE));
memcpy(state->tt800_state,buffer + position , sizeof(MTTSTATE));
position += sizeof(MTTSTATE);
}
return position;
}
int init_rng_state(struct RNG_STATE*const state,const unsigned int seed, const unsigned int stream,const enum enum_pseudo_random_number_generator rng_type)
{
allocate_rng_state(state, rng_type);
seed_rng_state(state, seed, stream, rng_type);
copyin_rng_state(state, rng_type);
return 0;
}
int allocate_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
state->mt_state = NULL;
state->tt800_state = NULL;
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT:
{
/* MERSENNE_TWISTER_STATE *mt_state_tmp = (MERSENNE_TWISTER_STATE*)malloc(sizeof(MERSENNE_TWISTER_STATE)); */
MERSENNE_TWISTER_STATE *mt_state_tmp = alloc_MERSENNE_TWISTER_STATE_ptr(1);
if(mt_state_tmp == NULL){
fprintf(stderr, "ERROR: By malloc MERSENNE_TWISTER_STATE , %s %d ",
__FILE__, __LINE__ );
return -1;
}
state->mt_state = mt_state_tmp;
}
break;
case pseudo_random_number_generator_arg_TT800:
{
/* MTTSTATE *tt800_state_tmp = (MTTSTATE*)malloc(sizeof(MTTSTATE)); */
MTTSTATE *tt800_state_tmp = alloc_MTTSTATE_ptr(1);
if(tt800_state_tmp == NULL){
fprintf(stderr, "ERROR: By malloc TT800 %s %d",__FILE__, __LINE__ );
return -1;
}
state->tt800_state = tt800_state_tmp;
}
break;
}//end switch
return 0;
}
int deallocate_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
/* free(state->mt_state); */
break;
case pseudo_random_number_generator_arg_TT800: ;
/* free(state->tt800_state); */
break;
}//end switch
return 0;
}
int copyin_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
#ifdef SPEC_OPENACC
#pragma acc enter data copyin(state->mt_state[0:1])
#endif
break;
case pseudo_random_number_generator_arg_TT800: ;
#ifdef SPEC_OPENACC
#pragma acc enter data copyin(state->tt800_state[0:1])
#endif
break;
}//end switch
return 0*state->default_state.state;
}
int copyout_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
#ifdef SPEC_OPENACC
#pragma acc exit data copyout(state->mt_state[0:1])
#endif
break;
case pseudo_random_number_generator_arg_TT800: ;
#ifdef SPEC_OPENACC
#pragma acc exit data copyout(state->tt800_state[0:1])
#endif
break;
}//end switch
return 0*state->default_state.state;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
#ifdef SPEC_OPENACC
#pragma acc routine seq
#endif
int seed_rng_state(struct RNG_STATE*const state,const unsigned int seed, const unsigned int stream,const enum enum_pseudo_random_number_generator rng_type)
{
soma_seed_rng(&(state->default_state),seed,stream);
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
//! pseudo_random_number_generator_arg_MT is not implementented (mssing offload data-handling)
/* soma_seed_rng_mt(&(state->default_state),state->mt_state); */
break;
case pseudo_random_number_generator_arg_TT800: ;
//! pseudo_random_number_generator_arg_TT800 is not implementented (mssing offload data-handling)
/* soma_seed_rng_tt800(&(state->default_state),state->tt800_state); */
}//end switch
return 0;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
//! TODO: OMP TGT
int update_device_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
#ifdef SPEC_OPENACC
#pragma acc update device(state->default_state[0:1])
#endif
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
#ifdef SPEC_OPENACC
#pragma acc update device(state->mt_state[0:1])
#endif
break;
case pseudo_random_number_generator_arg_TT800: ;
#ifdef SPEC_OPENACC
#pragma acc update device(state->tt800_state)
#endif
break;
}//end switch
return 0*state->default_state.state;
}
//! TODO: OMP TGT
int update_self_rng_state(struct RNG_STATE*const state,const enum enum_pseudo_random_number_generator rng_type)
{
#ifdef SPEC_OPENACC
#pragma acc update self(state->default_state[0:1])
#endif
switch( rng_type )
{
case pseudo_random_number_generator__NULL: break;
case pseudo_random_number_generator_arg_PCG32: break;
case pseudo_random_number_generator_arg_MT: ;
#ifdef SPEC_OPENACC
#pragma acc update self(state->mt_state[0:1])
#endif
break;
case pseudo_random_number_generator_arg_TT800: ;
#ifdef SPEC_OPENACC
#pragma acc update self(state->tt800_state)
#endif
break;
}//end switch
return 0*state->default_state.state;
}
|
./openacc-vv/kernels_loop_reduction_and_general.F90 | #ifndef T1
!T1:kernels,reduction,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: randoms
LOGICAL,DIMENSION(LOOPCOUNT):: a !Data
LOGICAL :: results = .TRUE.
LOGICAL :: host_results = .TRUE.
REAL(8) :: false_margin
INTEGER :: errors = 0
false_margin = exp(log(.5) / LOOPCOUNT)
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(randoms)
DO x = 1, LOOPCOUNT
IF (randoms(x) .lt. false_margin) THEN
a(x) = .TRUE.
ELSE
a(x) = .FALSE.
END IF
END DO
!$acc data copyin(a(1:LOOPCOUNT))
!$acc kernels loop reduction(.and.:results)
DO x = 1, LOOPCOUNT
results = results .and. a(x)
END DO
!$acc end data
DO x = 1, LOOPCOUNT
host_results = host_results .and. a(x)
END DO
IF (host_results .neqv. results) THEN
errors = 1
END IF
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/serial.c | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,V:2.6-2.7
int test1(){
int err = 0;
srand(SEED);
real_t* a = (real_t *) malloc(1024 * sizeof(real_t));
real_t* b = (real_t *) malloc(1024 * sizeof(real_t));
real_t* c = (real_t *) malloc(1024 * sizeof(real_t));
for(int x = 0; x < 1024; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
}
#pragma acc data copyin(a[0:1024], b[0:1024]) copy(c[0:1024])
{
#pragma acc serial
{
#pragma acc loop
for (int _0 = 0; _0 < 2; ++_0){
#pragma acc loop
for (int _1 = 0; _1 < 2; ++_1){
#pragma acc loop
for (int _2 = 0; _2 < 2; ++_2){
#pragma acc loop
for (int _3 = 0; _3 < 2; ++_3){
#pragma acc loop
for (int _4 = 0; _4 < 2; ++_4){
#pragma acc loop
for (int _5 = 0; _5 < 2; ++_5){
#pragma acc loop
for (int _6 = 0; _6 < 2; ++_6){
#pragma acc loop
for (int _7 = 0; _7 < 2; ++_7){
#pragma acc loop
for (int _8 = 0; _8 < 2; ++_8){
#pragma acc loop
for (int _9 = 0; _9 < 2; ++_9){
c[_0*512 + _1*256 + _2*128 + _3*64 + _4*32 + _5*16 + _6*8+ _7*4 + _8*2 + _9] =
a[_0*512 + _1*256 + _2*128 + _3*64 + _4*32 + _5*16 + _6*8+ _7*4 + _8*2 + _9] +
b[_0*512 + _1*256 + _2*128 + _3*64 + _4*32 + _5*16 + _6*8+ _7*4 + _8*2 + _9];
}
}
}
}
}
}
}
}
}
}
}
}
for (int x = 0; x < 1024; ++x){
if(fabs(c[x] - (a[x] +b[x])) > PRECISION){
err = 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_structured_assign_x_bitand_expr.cpp | #include "acc_testsuite.h"
bool is_possible(int* a, int* b, int length, int prev){
if (length == 0){
return true;
}
int *passed_a = new int[(length - 1)];
int *passed_b = new int[(length - 1)];
for (int x = 0; x < length; ++x){
if (b[x] == prev){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, prev & a[x])){
delete[] passed_a;
delete[] passed_b;
return true;
}
}
}
delete[] passed_a;
delete[] passed_b;
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
int *a = new int[n];
int *b = new int[n];
int *totals = new int[(n/10 + 1)];
int *totals_comparison = new int[(n/10 + 1)];
int *temp_a = new int[10];
int *temp_b = new int[10];
int temp_iterator;
int ab_iterator;
for (int x = 0; x < n; ++x){
for (int y = 0; y < 8; ++y){
if (rand()/(real_t)(RAND_MAX) < .933){ //.933 gets close to a 50/50 distribution for a collescence of 10 values
a[x] += 1<<y;
}
}
}
for (int x = 0; x < n/10 + 1; ++x){
totals[x] = 0;
totals_comparison[x] = 0;
for (int y = 0; y < 8; ++y){
totals[x] += 1<<y;
totals_comparison[x] += 1<<y;
}
}
for (int x = 0; x < n; ++x){
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:n/10 + 1]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
b[x] = totals[x/10];
totals[x/10] = totals[x/10] & a[x];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x/10] &= a[x];
}
for (int x = 0; x < (n/10 + 1); ++x){
if (totals_comparison[x] != totals[x]){
err += 1;
break;
}
}
for (int x = 0; x < n; x = x + 10){
temp_iterator = 0;
for (ab_iterator = x; ab_iterator < n && ab_iterator < x + 10; ab_iterator+= 1){
temp_a[temp_iterator] = a[ab_iterator];
temp_b[temp_iterator] = b[ab_iterator];
}
if (!is_possible(temp_a, temp_b, temp_iterator, 1)){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/parallel_copy.c | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,data,data-region,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * a_host = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
a_host[x] = a[x];
}
#pragma acc parallel copy(a[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
a[x] = 2 * a[x];
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (2 * a_host[x])) > PRECISION){
err = 1;
}
}
return err;
}
#endif
#ifndef T2
//T2:parallel,data,data-region,V:1.0-2.7
int test2(){
int err = 0;
srand(SEED);
real_t device = rand() / (real_t)(RAND_MAX / 10);
real_t host = device;
#pragma acc parallel loop copy(device) reduction(+:device)
for(int x = 0; x < n; ++x){
device += 1.0;
}
if(fabs(host - (device - n) ) > PRECISION){
err++;
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test1();
}
if(failed){
failcode += (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed += test2();
}
if(failed){
failcode += (1 << 1);
}
#endif
return failcode;
} |
./openacc-vv/parallel_loop_reduction_max_loop.F90 | #ifndef T1
!T1:parallel,private,reduction,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(10 * LOOPCOUNT):: a, b, c !Data
REAL(8),DIMENSION(10):: maximum
REAL(8) :: temp
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc data copyin(a(1:10*LOOPCOUNT), b(1:10*LOOPCOUNT)) copy(c(1:10*LOOPCOUNT))
!$acc parallel loop gang private(temp)
DO x = 0, 9
temp = 0
!$acc loop worker reduction(max:temp)
DO y = 1, LOOPCOUNT
temp = max(temp, a(x * LOOPCOUNT + y) * b(x * LOOPCOUNT + y))
END DO
maximum(x + 1) = temp
!$acc loop worker
DO y = 1, LOOPCOUNT
c(x * LOOPCOUNT + y) = (a(x * LOOPCOUNT + y) * b(x * LOOPCOUNT + y)) / maximum(x + 1)
END DO
END DO
!$acc end data
DO x = 0, 9
DO y = 1, LOOPCOUNT
IF (a(x * LOOPCOUNT + y) * b(x * LOOPCOUNT + y) - maximum(x + 1) .gt. PRECISION) THEN
errors = errors + 1
ELSE IF ((c(x * LOOPCOUNT + y) - 1) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_structured_postdecrement_assign.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
int *c = new int[n];
int *distribution = new int[10];
int *distribution_comparison = new int[10];
bool found = false;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < 10; ++x){
distribution[x] = 0;
distribution_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(distribution[0:10]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
(distribution[(int) (a[x]*b[x]/10)])--;
c[x] = distribution[(int) (a[x]*b[x]/10)];
}
}
}
}
for (int x = 0; x < n; ++x){
distribution_comparison[(int) (a[x]*b[x]/10)]--;
}
for (int x = 0; x < 10; ++x){
if (distribution_comparison[x] != distribution[x]){
err += 1;
break;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y > -distribution_comparison[x]; --y){
for (int z = 0; z < n; ++z){
if (y - 1 == c[z] && x == (int) (a[x] * b[x] / 10)){
found = true;
break;
}
}
if (!found){
err++;
}
found = false;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_structured_assign_expr_bitxor_x.c | #include "acc_testsuite.h"
bool is_possible(int* a, int* b, int length, int prev){
if (length == 0){
return true;
}
int *passed_a = (int *)malloc((length - 1) * sizeof(int));
int *passed_b = (int *)malloc((length - 1) * sizeof(int));
for (int x = 0; x < length; ++x){
if (b[x] == prev){
for (int y = 0; y < x; ++y){
passed_a[y] = a[y];
passed_b[y] = b[y];
}
for (int y = x + 1; y < length; ++y){
passed_a[y - 1] = a[y];
passed_b[y - 1] = b[y];
}
if (is_possible(passed_a, passed_b, length - 1, prev ^ a[x])){
free(passed_a);
free(passed_b);
return true;
}
}
}
free(passed_a);
free(passed_b);
return false;
}
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
int *a = (int *)malloc(n * sizeof(int));
int *b = (int *)malloc(n * sizeof(int));
int *totals = (int *)malloc((n/10 + 1) * sizeof(int));
int *totals_comparison = (int *)malloc((n/10 + 1) * sizeof(int));
int *temp_a = (int *)malloc(10 * sizeof(int));
int *temp_b = (int *)malloc(10 * sizeof(int));
int temp_iterator;
int ab_iterator;
for (int x = 0; x < n; ++x){
for (int y = 0; y < 8; ++y){
if (rand()/(real_t)(RAND_MAX) < .933){ //.933 gets close to a 50/50 distribution for a collescence of 10 values
a[x] += 1<<y;
}
}
}
for (int x = 0; x < n/10 + 1; ++x){
for (int y = 0; y < 8; ++y){
totals[x] = 1<<y;
totals_comparison[x] = 1<<y;
}
}
for (int x = 0; x < n; ++x){
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copy(totals[0:n/10 + 1]) copyout(b[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
b[x] = totals[x/10];
totals[x/10] = a[x] ^ totals[x/10];
}
}
}
}
for (int x = 0; x < n; ++x){
totals_comparison[x/10] ^= a[x];
}
for (int x = 0; x < (n/10 + 1); ++x){
if (totals_comparison[x] != totals[x]){
err += 1;
break;
}
}
for (int x = 0; x < n; x = x + 10){
temp_iterator = 0;
for (ab_iterator = x; ab_iterator < n && ab_iterator < x + 10; ab_iterator+= 1){
temp_a[temp_iterator] = a[ab_iterator];
temp_b[temp_iterator] = b[ab_iterator];
}
if (!is_possible(temp_a, temp_b, temp_iterator, 1)){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/acc_delete_finalize.F90 | #ifndef T1
!T1:runtime,data,executable-data,construct-independent,V:2.5-2.7
LOGICAL FUNCTION test1()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc enter data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
!$acc enter data copyin(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
!$acc data copyout(c(1:LOOPCOUNT))
!$acc parallel present(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = a(x) + b(x)
END DO
!$acc end parallel
!$acc end data
CALL acc_delete_finalize(a(1:LOOPCOUNT))
CALL acc_delete_finalize(b(1:LOOPCOUNT))
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (a(x) + b(x))) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
#ifndef T2
!T2:runtime,data,executable-data,construct-independent,V:2.5-2.7
LOGICAL FUNCTION test2()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
CALL acc_copyin(a(1:LOOPCOUNT))
CALL acc_copyin(a(1:LOOPCOUNT))
CALL acc_copyin(b(1:LOOPCOUNT))
CALL acc_copyin(b(1:LOOPCOUNT))
!$acc data copyout(c(1:LOOPCOUNT))
!$acc parallel present(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = a(x) + b(x)
END DO
!$acc end parallel
!$acc end data
CALL acc_delete_finalize(a(1:LOOPCOUNT))
CALL acc_delete_finalize(b(1:LOOPCOUNT))
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (a(x) + b(x))) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test2 = .FALSE.
ELSE
test2 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
!Conditionally define test functions
#ifndef T1
LOGICAL :: test1
#endif
#ifndef T2
LOGICAL :: test2
#endif
failcode = 0
failed = .FALSE.
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
#ifndef T2
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test2()
END DO
IF (failed) THEN
failcode = failcode + 2**1
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/acc_memcpy_from_device_async.c | #include "acc_testsuite.h"
#ifndef T1
//T1:runtime,data,executable-data,async,construct-independent,V:2.5-2.7
int test1(){
int err = 0;
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
real_t *c = (real_t *)malloc(n * sizeof(real_t));
real_t *d = (real_t *)malloc(n * sizeof(real_t));
real_t *e = (real_t *)malloc(n * sizeof(real_t));
real_t *f = (real_t *)malloc(n * sizeof(real_t));
real_t *hostdata = (real_t *)malloc(6 * n * sizeof(real_t));
real_t *hostdata_copy = (real_t *)malloc(6 * n * sizeof(real_t));
real_t *devdata;
for (int x = 0; x < n; ++x){
hostdata[x] = rand() / (real_t)(RAND_MAX / 10);
hostdata[n + x] = rand() / (real_t)(RAND_MAX / 10);
hostdata[2*n + x] = 1;
hostdata[3*n + x] = rand() / (real_t)(RAND_MAX / 10);
hostdata[4*n + x] = rand() / (real_t)(RAND_MAX / 10);
hostdata[5*n + x] = 2;
}
for (int x = 0; x < 6*n; ++x){
hostdata_copy[x] = hostdata[x];
}
devdata = acc_copyin(hostdata, 6 * n * sizeof(real_t));
#pragma acc data deviceptr(devdata)
{
#pragma acc parallel async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[x] = devdata[x] * devdata[x];
}
}
acc_memcpy_from_device_async(a, devdata, n * sizeof(real_t), 1);
#pragma acc parallel async(2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[n + x] = devdata[n + x] * devdata[n + x];
}
}
acc_memcpy_from_device_async(b, &(devdata[n]), n * sizeof(real_t), 2);
#pragma acc parallel async(4)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[3*n + x] = devdata[3*n + x] * devdata[3*n + x];
}
}
acc_memcpy_from_device_async(d, &(devdata[3*n]), n * sizeof(real_t), 4);
#pragma acc parallel async(5)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[4*n + x] = devdata[4*n + x] * devdata[4*n + x];
}
}
acc_memcpy_from_device_async(e, &(devdata[4*n]), n * sizeof(real_t), 5);
#pragma acc parallel async(3) wait(1, 2)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[2*n + x] += devdata[x] + devdata[n + x];
}
}
acc_memcpy_from_device_async(c, &(devdata[2*n]), n * sizeof(real_t), 3);
#pragma acc parallel async(6) wait(4, 5)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
devdata[5*n + x] += devdata[3*n + x] + devdata[4*n + x];
}
}
acc_memcpy_from_device_async(f, &(devdata[5*n]), n * sizeof(real_t), 6);
}
#pragma acc wait(1)
for (int x = 0; x < n; ++x){
if (fabs(a[x] - hostdata_copy[x] * hostdata_copy[x]) > PRECISION){
err += 1;
}
}
#pragma acc wait(2)
for (int x = 0; x < n; ++x){
if (fabs(b[x] - hostdata_copy[n + x] * hostdata_copy[n + x]) > PRECISION){
err += 1;
}
}
#pragma acc wait(4)
for (int x = 0; x < n; ++x){
if (fabs(d[x] - hostdata_copy[3*n + x] * hostdata_copy[3*n + x]) > PRECISION){
err += 1;
}
}
#pragma acc wait(5)
for (int x = 0; x < n; ++x){
if (fabs(e[x] - hostdata_copy[4*n + x] * hostdata_copy[4*n + x]) > PRECISION){
err += 1;
}
}
#pragma acc wait(3)
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (1 + a[x] + b[x])) > PRECISION){
err += 1;
}
}
#pragma acc wait(6)
for (int x = 0; x < n; ++x){
if (fabs(f[x] - (2 + d[x] + e[x])) > PRECISION){
err += 1;
}
}
#pragma acc exit data delete(hostdata[0:6*n])
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/serial_present.c | #include "acc_testsuite.h"
#ifndef T1
//T1:serial,present,V:2.6-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = (real_t *)malloc(n * sizeof(real_t));
real_t * b = (real_t *)malloc(n * sizeof(real_t));
real_t * c = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0.0;
}
#pragma acc enter data copyin(a[0:n], b[0:n])
#pragma acc serial present(a[0:n], b[0:n]) copy(c[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc exit data delete(a[0:n], b[0:n])
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (a[x] + b[x])) > PRECISION){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./SPECaccel/bin/runspec | #!/spec/accel/bin/specperl
#!/spec/accel/bin/specperl -d
#!/usr/bin/perl
#
# runspec - a tool for running SPEC benchmarks.
# Copyright 1995-2015 Standard Performance Evaluation Corporation
#
# Authors: Christopher Chan-Nui
# Cloyce D. Spradling
#
# $Id: runspec 2989 2015-03-03 18:59:03Z CloyceS $
# Note the start time
$::runspec_time = time - 1;
if (exists $ENV{'SPECDB_PWD'}) {
chdir($ENV{'SPECDB_PWD'});
} else {
$ENV{'SPECDB_PWD'} = $ENV{'PWD'};
}
BEGIN {
foreach my $var qw(SPEC SPECPERLLIB) {
next if (exists($ENV{$var}) && ($var ne 'SPEC' || -d $ENV{$var}));
my $msg = "\nThe $var environment variable is not set.\n";
if ($^O =~ /mswin/i) {
$msg .= "Please run shrc.bat before executing $0.\n\n";
} else {
$msg .= "Please source the shrc or cshrc as appropriate before executing $0.\n\n";
}
die $msg;
}
shift @ARGV if (defined($ARGV[0]) && $ARGV[0] eq '--');
unshift @ARGV, '--configpp' if ($0 =~ /configpp$/i);
}
use strict;
our ($global_config, $runconfig, $version, $suite_version, $nonvolatile_config,
%file_md5, %file_size, %tools_versions, $toolset_name, $cl_opts,
$debug, $cl_pp_macros);
use IO::Dir; # To help do fast -V
use Config; # Also for the sake of -V
use File::Spec; # Also for the sake of -V
use POSIX qw(WNOHANG);
if ($^O =~ /MSWin/) {
# The POSIX module on Windows lacks definitions for WEXITSTATUS and WTERMSIG
eval '
sub POSIX::WEXITSTATUS { return ($_[0] & 0x7f00) >> 8 }
sub POSIX::WTERMSIG { return ($_[0] & 0x7f) }
';
die "$@" if $@;
} else {
import POSIX qw(:sys_wait_h);
}
# This will keep -w quiet
{ my $trash = $DB::signal = $DB::single; $trash = $Data::Dumper::Indent; }
use Time::localtime;
use Data::Dumper;
# Set up Data::Dumper a little bit
$Data::Dumper::Indent = 1;
$Data::Dumper::SortKeys = 1;
##############################################################################
# Load in remainder of program
##############################################################################
## here is when things get big and ugly sucking up a hunk of memory
print "Loading runspec modules" unless ($::quiet || $::from_runspec);
for my $module (qw( listfile.pm vars.pl os.pl log.pl flagutils.pl parse.pl
locate.pl benchmark.pm benchset.pm format.pm util.pl
config.pl compare.pl monitor.pl
ConfigDumper.pm )) {
load_module($module, $::quiet || $::from_runspec);
}
# The raw file output format module is a little special, since it needs to go
# into a package that it doesn't know about.
load_module('format_raw.pl', $::quiet || $::from_runspec,
'package Spec::Format::raw; @Spec::Format::raw::ISA = qw(Spec::Format);');
print "\n" unless ($::quiet || $::from_runspec);
# Stop the debugger so that breakpoints, etc can be set
$DB::single = $DB::signal = 1;
# Disable screen logging early when runspec is calling itself
$::log_to_screen = ($::from_runspec == 0);
# Set today as the test date. The user will probably override this in
# a config file.
$::default_config->{'test_date'} = timeformat(localtime, 3);
# Initialize Config state, load config file, add command line options
my $config = new Spec::Config;
$cl_opts = new Spec::Config;
$global_config = $config;
# Setup defaults and then parse the command line
initialize_variables($config);
usage(1) unless (parse_commandline($config, $cl_opts));
my $hostname = qx(hostname);
chomp($hostname);
if (!$::from_runspec) {
Log(130, "runspec v$version started at ", ctime($::runspec_time), " on \"$hostname\"\n");
Log(130, "runspec is: $0\n");
Log(130, "runspec: ".basename($0).' ', join(' ', @{$config->orig_argv}), "\n");
Log(130, "toolset: $::toolset_name\n\n");
} else {
# Run invoked from runspec; dump log buffer to log file (provided
# on the command line) and then exit. This ensures that the user
# will see errors and warnings produced by config file reads, etc.
open_log($config, undef, $cl_opts->{'logfile'});
}
# Now is a good time to find all the benchmarks
Log(0, "Locating benchmarks...") unless ($::quiet || $::from_runspec);
# ...but first, do the mandatory flags setup
my $mandatory_flags = '';
$mandatory_flags = jp($ENV{'SPEC'}, 'benchspec', 'flags-mandatory.xml');
if (!-e $mandatory_flags) {
Log(0, "\nERROR: The mandatory flags file ($mandatory_flags) is not present.\n");
do_exit(1);
}
(undef, $global_config->{'flaginfo'}->{'suite'}) =
get_flags_file($mandatory_flags, 'suite');
if (!defined($global_config->{'flaginfo'}->{'suite'})) {
Log(0, "\nERROR: The mandatory flags file ($mandatory_flags) could not be parsed.\n");
do_exit(1);
}
# Okay, now actually look for benchmarks
locate_benchmarks($config);
if (!$::quiet && !$::from_runspec) {
my ($numbm, $numbs, $numsa) = (
((keys %{$config->{'benchmarks'}})+0),
((keys %{$config->{'benchsets'}})+0),
0
);
foreach my $bm (keys %{$config->{'benchmarks'}}) {
$numsa += (keys %{$config->{'benchmarks'}->{$bm}->{'srcalts'}})+0;
}
Log(2, "found $numbm benchmarks ");
Log(2, "and $numsa src.alt".(($numsa != 1) ? 's ' : ' ')) if $numsa;
Log(2, "in $numbs benchset".(($numbs != 1) ? 's' : '').".\n");
}
# Prep the OS
initialize_os($config);
# Make sure the config directories actually exist
eval { mkpath([jp($config->top, $config->configdir)], 0, $config->dirprot) };
if ($@) {
Log(0, "ERROR: Could not make config directory: $@\n");
do_exit(1);
}
my $rc;
if ($cl_opts->{'bundleaction'} !~ /^(?:unpack|use)$/i) {
# Read the config file
my $configfile = $config->config;
$configfile = $cl_opts->{'config'} if exists $cl_opts->{'config'};
my $comment = exists $cl_opts->{'comment'} ? $cl_opts->{'comment'} : '';
my $pp_macros = deep_copy($cl_opts->{'pp_macros'});
$cl_pp_macros = deep_copy($cl_opts->{'pp_macros'});
delete $cl_opts->{'pp_macros'};
$config->{'ignore_errors'} = defined($cl_opts->{'ignore_errors'}) ? $cl_opts->{'ignore_errors'} : 0;
$rc = $config->merge($configfile, $comment, $pp_macros,
'missing_ok' => istrue($cl_opts->{'update-flags'})
|| istrue($cl_opts->{'check_version'})
|| is_clean($cl_opts->{'action'}));
do_exit(1) unless $rc;
}
# Do variable substitution for output_root and expid
my $s = undef;
foreach my $thing (qw(output_root expid)) {
($config->{$thing}, $s) = command_expand($config->{$thing}, [ $config, $cl_opts ], 'safe' => $s);
}
if ($config->{'output_root'} ne ''
&& $cl_opts->{'bundleaction'} !~ /^(?:unpack|unpack)$/i) {
# Decompose the config files, note the use of output_root, and recompose
# them.
foreach my $type (qw(pptxtconfig rawtxtconfig rawtxtconfigall)) {
my @tmp = split(/\n/, $config->{$type}, -1);
# Look through the config for the placeholder comment. I like this
# better than hard-coding indices.
for(my $i = 0; $i < @tmp; $i++) {
if ($tmp[$i] eq '# output_root was not used for this run') {
$tmp[$i] = "# output_root used was \"$config->{'output_root'}\"";
last;
}
}
$config->{$type} = join("\n", @tmp);
}
} else {
# Make sure the other directories necessary are present in $SPEC
initialize_specdirs($config);
}
if ($cl_opts->{'bundleaction'} =~ /^(?:unpack|use)$/i) {
use_bundle($cl_opts->{'bundleaction'}, $cl_opts->{'bundlename'}, $config);
# There is no return from this point
}
# Get the list of environment variables
my @pre_env = grep { /^preENV_\S+/ } sort keys %{$config};
# Fix up $config's preenv to make some tests below simpler...
$config->{'preenv'} = $cl_opts->{'preenv'} if exists($cl_opts->{'preenv'});
# NOW open the log. We used to do it before, but now there are config
# file settings that can influence its placement, etc.
# But don't bother for updates (nothing interesting in there anyway), or if
# runspec is about to be re-invoked.
if (!istrue($cl_opts->{'update-flags'}) &&
((@pre_env == 0) || !istrue($config->{'preenv'}))) {
open_log($config, undef, $::from_runspec ? $cl_opts->{'logfile'} : undef) || do_exit(1);
}
if (@pre_env && istrue($config->{'preenv'})) {
Log(3, "Setting up environment for runspec...\n");
foreach my $var (@pre_env) {
my $name = $var;
$name =~ s/^preENV_//;
my $val = $config->{$var};
Log(6, "Setting $name = \"$val\"\n");
$ENV{$name} = $val;
}
my @args = (jp($config->top, 'bin', 'specperl'));
# Arrange for debugging runs to continue being debugged
push @args, '-d' if (defined($DB::sub));
push @args, jp($config->top, 'bin', 'runspec'), @::original_ARGV;
Log(0, "About to re-exec runspec...\n");
Log(6, " ".join(' ', @args)."\n");
Log(0, ('-' x 78)."\n");
Log(0, ('-' x 78)."\n\n\n");
push @args, '--nopreenv', '--note-preenv';
exec @args;
Log(0, "ERROR: Exec of runspec failed: $!\n");
do_exit(1);
}
# Do this here because command-line options override config file settings
finalize_config($config, $cl_opts);
# If a flags update has been requested, do it now.
if (istrue($config->{'update-flags'})) {
if (update_flags($config, $global_config->http_timeout,
$global_config->http_proxy)) {
Log(0, "\nFlag and config file update successful!\n");
do_exit(0);
} else {
Log(0, "\nFlag and config file update failed.\n");
do_exit(1);
}
}
if ($global_config->action eq 'configpp') {
Log(100, "Pre-processed configuration file dump follows:\n");
Log(100, "--------------------------------------------------------------------\n");
Log(100, $global_config->{'pptxtconfig'}."\n");
Log(100, "--------------------------------------------------------------------\n");
do_exit(0);
}
my $choices_ok = resolve_choices ($config, $cl_opts);
validate_options ($config, $cl_opts) if $choices_ok;
if ((0 # CVT2DEV: || 1
) && istrue($global_config->reportable)) {
Log(100, "\nERROR: development tree -- can't do reportable runs\n");
do_exit(1);
}
print Data::Dumper->Dump([$config], qw(*config)),"\n" if ($debug > 20000);
if (istrue($cl_opts->{'check_version'}) ||
(istrue($global_config->check_version) &&
istrue($global_config->reportable))) {
check_version($global_config->version_url, $global_config->http_timeout, $global_config->http_proxy, $choices_ok);
}
do_exit(0) unless $choices_ok;
# Connect to the power analyzers & temperature meters if necessary. This is
# done early to minimize the amount of time that is wasted if the PTDs can't be
# contacted.
$global_config->{'powermeterlist'} = [ ];
$global_config->{'tempmeterlist'} = [ ];
if ( !$::from_runspec
&& istrue($global_config->power)
&& $global_config->action =~ /^(validate|run|onlyrun|only_run)$/) {
my ($isok, $timeout, @meters);
my $meterlistref = $global_config->accessor_nowarn('power_analyzer');
my $timeout = $global_config->accessor_nowarn('meter_connect_timeout');
if ( !defined($meterlistref)
|| (::ref_type($meterlistref) ne 'ARRAY')
|| @{$meterlistref} == 0) {
::Log(0, "\nERROR: Power measurement was requested, but no power analyzers are defined\n in the config file.\n");
do_exit(1);
} else {
::Log(0, "Connecting to power analyzers...\n");
# Fire up the power analyzers!
($isok, @meters) = meter_connect($meterlistref, $timeout);
if (!defined($isok) || $isok != 1) {
::Log(0, "Error connecting to power analyzers\n");
do_exit(1);
}
::Log(0, "Connected to ".(@meters+0)." power analyzers\n");
$global_config->{'powermeterlist'} = [ @meters ];
}
# Do temp meters too
$meterlistref = $global_config->accessor_nowarn('temp_meter');
if ( defined($meterlistref)
&& (::ref_type($meterlistref) eq 'ARRAY')
&& @{$meterlistref} > 0) {
# Fire up the temperature & humidity meters!
::Log(0, "Connecting to temperature meters...\n");
($isok, @meters) = meter_connect($meterlistref, $timeout);
if (!defined($isok) || $isok != 1) {
::Log(0, "Error connecting to temperature meters\n");
do_exit(1);
}
::Log(0, "Connected to ".(@meters+0)." temperature meters\n");
$global_config->{'tempmeterlist'} = [ @meters ];
} else {
::Log(0, "No temperature meters configured.\n");
}
}
# Shuffle the tunelist around a bit
my @tunelist = @{$global_config->tunelist};
# Order must be base[,peak] for reportable runs
if ($global_config->action =~ /^(validate|report)$/ &&
istrue($global_config->reportable)) {
my $seen = grep { /^peak$/io } @tunelist;
# Take out the peak
@tunelist = grep { !/^peak$/oi } @tunelist;
push @tunelist, 'peak' if (defined($seen) && $seen > 0);
# So at this point, peak is last (if it was present at all)
# Now make sure base exists, and is first in line
@tunelist = grep { !/^base$/oi } @tunelist;
unshift @tunelist, 'base';
$global_config->tunelist(@tunelist);
}
# For a reportable run, test and train must also be run (except for MPI2007).
# For a reportable fakereport, just ref should be fine.
if (istrue($global_config->reportable)) {
# We can pick the required size from the first benchset in the list
# because all of the selected benchsets will have the same set of
# classes.
my $one_benchset = $global_config->{'benchset_list'}->[0];
if ($global_config->action eq 'validate') {
my @sizes = ();
my @required = qw(ref);
unshift @required, qw(test train) unless $::lcsuite =~ /^(mpi2007|omp2001)$/;
for my $required_class (@required) {
my $required_size = $global_config->benchsets->{$one_benchset}->{$required_class};
push @sizes, $required_size;
if (!grep { $_ eq $required_size } @{$global_config->{'sizelist'}}) {
my $tmpsize = $required_size;
$tmpsize .= " ($required_class)" if $required_size ne $required_class;
Log(0, "Reportable runs must include a '$tmpsize' run; adding to run list\n");
$global_config->{$required_class."addedbytools$$"} = 1;
}
}
@{$global_config->{'sizelist'}} = @sizes;
} elsif ($global_config->action eq 'report') {
@{$global_config->{'sizelist'}} = ($global_config->benchsets->{$one_benchset}->{'ref'});
}
}
# Check to make sure that the extension mentioned exists
if (!istrue($global_config->allow_extension_override) &&
!is_clean($global_config->action)) {
foreach my $ext (@{$global_config->{'extlist'}}) {
if (!exists($global_config->seen_extensions->{$ext})) {
Log(0, "ERROR: The extension '$ext' defines no settings in the config file!\n");
Log(0, " If this is okay and you'd like to use the extension to just change\n");
Log(0, " the extension applied to executables, please put\n");
Log(0, " allow_extension_override = yes\n");
Log(0, " into the header section of your config file.\n");
do_exit(1);
}
}
}
# For fake runs, only do one iteration. Also set rebuild so that it's
# possible to see the build commands as well.
if (istrue($global_config->fake)) {
$global_config->{'iterlist'} = [ 1 ];
$global_config->{'rebuild'} = 1;
}
# Figure out what kind of runs to do
my @runconfiglist = ();
foreach my $iter (@{$global_config->{'iterlist'}}) {
foreach my $copies (@{$global_config->{'copylist'}}) {
foreach my $ext (@{$global_config->{'extlist'}}) {
my $count = 0;
foreach my $mach (@{$global_config->{'machlist'}}) {
my @sizes = @{$global_config->{'sizelist'}};
if ( $global_config->action eq 'build'
|| $global_config->action eq 'buildsetup') {
# No sense in doing multiple sizes for a build; they're
# all the same!
@sizes = ($sizes[0]);
}
foreach my $size (@sizes) {
push @runconfiglist, [ $copies, $ext, $mach, $size,
$iter, $count++ ];
}
}
}
}
}
# At this point the main config object should be fully populated.
# Debugging information
if (!$::quiet && !$::from_runspec && exists $ENV{'SPEC_PRINT_CONFIG'}) {
my @keys;
if ($ENV{'SPEC_PRINT_CONFIG'} ne '' && $ENV{'SPEC_PRINT_CONFIG'} ne 'all') {
@keys = (split(' ', $ENV{'SPEC_PRINT_CONFIG'}));
} else {
@keys = $config->list_keys;
}
for (sort @keys) {
print "$_: '", $config->accessor($_), "'\n";
}
}
my $flagsurls = $::from_runspec ? undef : $config->accessor_nowarn('flagsurl');
if (::ref_type($flagsurls) eq 'ARRAY') {
foreach my $flagsurl (grep { defined($_) && $_ ne '' } @{$flagsurls}) {
Log(2, "Retrieving flags file ($flagsurl)...\n") if $flagsurl ne 'noflags';
my ($flags, $flaginfo, $fname) = get_flags_file($flagsurl,
'user', 0,
$global_config->http_timeout,
$global_config->http_proxy);
if (!defined($flaginfo)) {
Log(0, "ERROR: No usable flag description found in $flagsurl.\n");
do_exit(1);
}
push @{$config->{'files_read'}}, $fname if defined($fname);
$global_config->{'flags'} = '' unless $global_config->{'flags'} ne '';
$global_config->{'flaginfo'}->{'user'} = {} unless (::ref_type($global_config->{'flaginfo'}->{'user'}) eq 'HASH');
my $rc = merge_flags($flags, \$global_config->{'flags'}, $flaginfo, $global_config->{'flaginfo'}->{'user'}, $flagsurl);
if (!$rc) {
Log(0, "ERROR: Flag descriptions in $flagsurl\n could not be merged with previously read flag descriptions.\n");
do_exit(1);
}
}
}
foreach my $runconf (@runconfiglist) {
# $runconfig will hold the information for this run
$runconfig = make_per_run_config($global_config, $runconf);
my $copies = $runconfig->{'copies'};
my $ext = $runconfig->{'ext'};
my $mach = $runconfig->{'mach'};
my $size = $runconfig->{'size'};
if (!$::from_runspec) {
log_header($runconfig);
Log(1, "Benchmarks selected: ", join (", ", map { $_->benchmark } @{$runconfig->runlist}), "\n");
}
if (istrue($runconfig->fake)) {
Log(0, "\n%% You have selected --fake: commands will be echoed but not actually\n");
Log(0, "%% executed. (You can search for \"%%\" to find the beginning and end\n");
Log(0, "%% of each command section.)\n\n");
}
my $error = 0;
# The levels of clean are
# clean - remove all work and build directories for this user and
# this extension
# realclean/trash - remove all work and build directories for all users
# and all extensions
# clobber - clean + remove all executables with this extension
# scrub - remove all run and build directories and all executables
my $action = $runconfig->action;
my $delete_binaries = 0;
my $delete_rundirs = 0;
if ($action eq 'clean') {
$delete_rundirs = 1;
} elsif ($action eq 'realclean' || $action eq 'trash') {
$delete_rundirs = 2;
} elsif ($action eq 'clobber') {
$delete_binaries = 1;
$delete_rundirs = 1;
} elsif ($action eq 'scrub') {
$delete_binaries = 2;
$delete_rundirs = 2;
}
if ( !$::from_runspec
&& $action =~ /^(?:only_?run|run|validate)$/i
&& !::check_list($runconfig->no_monitor, $size)) {
monitor_pre($runconfig);
}
$runconfig->{'basepeak'} = istrue($runconfig->{'basepeak'});
# First, scan through the list of selected benchmarks to make sure that
# the basepeak setting is sane. Also check to see if the number of copies
# or ranks/threads is the same for all (but different from the global setting).
# How basepeak works:
# If basepeak is set to 1 (which the user can do), the settings
# (if any) for every benchmark must also match. In that case, benchmarks
# are run once (base flags) and the result is reported for both base and
# peak tunes.
# If any of the settings *don't* match (i.e. basepeak = 0 and one or more
# components have basepeak set), then we set basepeak = 2 so that we know
# to set up benchmarks with basepeak set properly. Their *base* code will
# be run twice, either the base score or the lowest median will be
# selected (depends on the benchmark) and that will be reported for both
# base and peak. What a pain!
my $seen = {};
my $instance_failure = 0;
foreach my $tune (@tunelist) {
my %seenvals = ( 'copies' => defined($runconfig->{'clcopies'}) ? 0 : undef,
'ranks' => defined($runconfig->{'clranks'}) ? 0 : undef,
'threads' => defined($runconfig->{'clranks'}) ? 0 : undef );
for my $bench (@{$runconfig->runlist}) {
last if ($runconfig->{'basepeak'} == 2);
my $obj = $bench->instance($runconfig, $tune, $size, $ext, $mach, -1);
if (!defined($obj)) {
# Instance creation failed, and should've emitted some
# error messages. Note the failure and continue so that
# all the benchmarks can be tried.
$instance_failure++;
next;
}
foreach my $thing (qw(copies ranks threads)) {
my $objval = $obj->accessor_nowarn($thing);
if (defined($objval)) {
if (!defined($seenvals{$thing})) {
$seenvals{$thing} = $objval;
} elsif ($seenvals{$thing} > 0) {
$seenvals{$thing} = 0 if ($objval != $seenvals{$thing});
}
}
}
next if ($runconfig->{'basepeak'} == 1) &&
($seen->{$obj->benchmark}{$obj->ext}{$obj->mach}{$obj->smarttune}++);
next if ($runconfig->{'basepeak'} != 1) &&
($seen->{$obj->benchmark}{$obj->ext}{$obj->mach}{$obj->tune}++);
if ($obj->{'basepeak'} != $runconfig->{'basepeak'}) {
$runconfig->{'basepeak'} = 2;
}
}
if ($tune eq 'base') {
if (defined($seenvals{'copies'}) && $seenvals{'copies'} > 0) {
$copies = $runconfig->{'copies'} = $seenvals{'copies'};
}
if (defined($seenvals{'ranks'}) && $seenvals{'ranks'} > 0) {
$runconfig->{'ranks'} = $seenvals{'ranks'};
}
}
}
if ($instance_failure) {
Log(0, "\nFATAL: runspec was not able to create ".($instance_failure > 1 ? 'objects for some benchmarks' : 'a benchmark object')." and can not continue.\n");
do_exit(1);
}
my @benchobjs;
$seen = {};
my $seen_error = {};
for my $tune (@tunelist) {
for my $bench (@{$runconfig->runlist}) {
my $obj = $bench->instance($runconfig, $tune, $size, $ext, $mach);
if (!defined($obj)) {
# Instance creation failed, and should've emitted some
# error messages. Note the failure and continue so that
# all the benchmarks can be tried.
$instance_failure++;
next;
}
$copies = $obj->copylist->[0]; # Why [0]? It's guaranteed!
# If we're doing full-suite basepeak, exclude on smarttune
next if ($runconfig->{'basepeak'} == 1) &&
($seen->{$obj->benchmark}{$obj->ext}{$obj->mach}{$obj->smarttune}++);
# If we're doing per-benchmark or no basepeak, exclude on
# tune
next if ($runconfig->{'basepeak'} != 1) &&
($seen->{$obj->benchmark}{$obj->ext}{$obj->mach}{$obj->tune}++);
if (!$delete_binaries &&
!$delete_rundirs &&
!$obj->check_size) {
my $name = $bench->benchmark;
next if $seen_error->{$obj->ext}{$obj->mach}{$obj->smarttune}++;
Log(0, "Benchmark '$name' does not support size '$size'\n");
$instance_failure++;
next;
}
if (istrue($runconfig->rate)) {
# We got $copies from the object created above, so it's got to be
# correct. Just re-use the object.
push @benchobjs, $obj;
} else {
push @benchobjs, $bench->instance($runconfig, $tune, $size, $ext,
$mach, 1);
}
}
}
if ($instance_failure) {
Log(0, "\nFATAL: runspec was not able to create ".($instance_failure > 1 ? 'objects for some benchmarks' : 'a benchmark object')." and can not continue.\n");
do_exit(1);
}
if ($delete_binaries || $delete_rundirs) {
for my $bench (@benchobjs) {
$bench->delete_binaries($delete_binaries > 1) if ($delete_binaries);
$bench->delete_rundirs($delete_rundirs > 1) if ($delete_rundirs);
}
do_exit(0);
}
# Do some sanity checks and other things for reportable
$error = 0;
if ($runconfig->action =~ /^(?:validate|report)/ &&
istrue($runconfig->reportable)) {
if (istrue($runconfig->fake) && $runconfig->action ne 'report') {
Log(0, "Notice: \"reportable\" is set for a \"fake\" run; ignoring your\n");
Log(0, " \"reportable\" attribute (or did you perhaps mean to say\n");
Log(0, " \"--fakereportable\"?)\n");
$runconfig->{'reportable'} = 0;
}
my %reported = ();
for my $me (@benchobjs) {
if ($me->size_class ne 'ref') {
# It's only necessary to run 1 iteration to satisfy the
# requirement for automatically added test and train runs
$runconfig->{'iterations'} = 1;
$runconfig->{'clcopies'} = 1;
$me->{'copylist'} = [ 1 ];
$runconfig->{'formatlist'} = [ ]; # Raw is always done
$runconfig->{'power'} = 0; # No need to measure power for these
}
if (!istrue($me->strict_rundir_verify)) {
Log(0, "\nNotice: Run directories must be fully verified for a reportable run.\n Enabling 'strict_rundir_verify'.\n") unless $reported{'strict_verify'};
$me->{'strict_rundir_verify'} = 1;
$reported{'strict_verify'}++;
}
if (istrue($me->env_vars) && $::lcsuite =~ /^cpu2/) {
Log(0, "\nNotice: The run environment must remain constant during a run.\n Disabling 'env_vars'.\n") unless $reported{'env_vars'};
$me->{'env_vars'} = 0;
$reported{'env_vars'}++;
}
if (istrue($me->power) && $me->size_class eq 'ref') {
if ($me->idledelay > 10) {
Log(0, "\nNotice: The delay before idle power measurement may not be more than 10 seconds.\n Resetting to 10 seconds.\n") unless $reported{'idledelay'};
$me->{'idledelay'} = 10;
$reported{'idledelay'}++;
}
if ($me->idleduration < 60) {
Log(0, "\nNotice: The idle power measurement interval may not be less than 60 seconds.\n Resetting to 60 seconds.\n") unless $reported{'idleduration'};
$me->{'idleduration'} = 60;
$reported{'idleduration'}++;
}
if ($me->meter_errors_percentage > $::nonvolatile_config->{'meter_errors_default'}) {
Log(0, "\nNotice: The acceptable percentage of meter errors may not be set greater than $::nonvolatile_config->{'meter_errors_default'}%.\n Resetting to $::nonvolatile_config->{'meter_errors_default'}%.\n") unless $reported{'meter_errors'};
$me->{'meter_errors_percentage'} = $::nonvolatile_config->{'meter_errors_default'};
# This is necessary to catch the idle measurement...
$runconfig->{'meter_errors_percentage'} = $::nonvolatile_config->{'meter_errors_default'};
$reported{'meter_errors'}++;
}
}
# For SPEC CPU, ensure that train_with is always set to 'train'.
# This will ensure that binaries not trained with the train
# workload will need to be rebuilt.
if ($::lcsuite =~ /cpu(?:2006|v6)/) {
if ($me->smarttune eq 'peak' && $me->train_with ne 'train') {
Log(0, "Notice: For reportable runs, train_with must always be set to 'train'.\n");
Log(0, ' Ignoring train_with setting for '.$me->descmode('no_size' => 1, 'no_threads' => 1)."\n");
$me->{'train_with'} = 'train';
}
}
if ($me->size_class eq 'ref') {
# This is the section where the number of iterations for
# a reportable run is checked and adjusted if necessary.
if ($::lcsuite =~ /^(?:cpuv6)/) {
# For CPUv6, there are either 2 or 3 iterations in a
# reportable run. See minutes from the 25 Apr 2013
# meeting.
if ($me->iterations < $runconfig->min_report_runs) {
if ($reported{'iterations'} == 0) {
Log(0, "\nNotice: ". $me->benchmark . ' has ' .
pluralize($me->iterations, 'iteration') .
". This is not correct for a\n" .
' reportable run. Changing iterations to ' .
$me->min_report_runs .
" for ALL benchmarks.\n");
$reported{'iterations'}++;
}
$me->{'iterations'} = $runconfig->min_report_runs;
} elsif ($me->iterations > $runconfig->max_report_runs) {
if ($reported{'iterations'} == 0) {
Log(0, "\nNotice: ". $me->benchmark . ' has ' .
pluralize($me->iterations, 'iteration') .
". This is not correct for a\n" .
' reportable run. Changing iterations to ' .
$me->max_report_runs .
" for ALL benchmarks.\n");
$reported{'iterations'}++;
}
$me->{'iterations'} = $runconfig->max_report_runs;
}
} elsif ($::lcsuite =~ /^(?:cpu2006|omp2012)/) {
# For CPU2006 and OMP2012, there are exactly 3 iterations in a
# reportable run. See minutes from the 17 Nov 2005
# conference call.
if ($me->iterations != $runconfig->min_report_runs) {
if ($reported{'iterations'} == 0) {
Log(0, "\nNotice: ". $me->benchmark . ' has ' .
pluralize($me->iterations, 'iteration') .
". This is not correct for a\n" .
' reportable run. Changing iterations to ' .
$me->min_report_runs .
" for ALL benchmarks.\n");
$reported{'iterations'}++;
}
$me->{'iterations'} = $runconfig->min_report_runs;
}
} else {
# For others, the CPU2000 rules are in effect; at least the
# minimum number of runs, and the number must be odd.
if ($me->iterations < $runconfig->min_report_runs) {
if ($reported{'iterations'} == 0) {
Log(0, "\nNotice: ". $me->benchmark . " only has " .
pluralize($me->iterations, 'iteration') .
". This is insufficient for a\n" .
' reportable run. Increasing iterations to ' .
$me->min_report_runs .
" for ALL benchmarks.\n");
$reported{'iterations'}++;
}
$me->{'iterations'} = $me->min_report_runs;
}
# HPG benchmarks allow even numbers of runs
if ($::lcsuite !~ /^(mpi2007|omp2001)$/ &&
($me->iterations % 2) == 0) {
if ($reported{'iterbump'} == 0) {
Log(0, "\nNotice: ". $me->benchmark .
" has an even number of iterations (" .
$me->iterations . "). The number of\n" .
" iterations must be odd; increasing it by 1.\n");
$reported{'iterbump'}++;
}
$me->{'iterations'} = $me->iterations + 1;
}
}
}
}
if (istrue($runconfig->ignore_errors)) {
Log(0, "\nNotice: Errors may not be ignored for reportable runs.\n");
$runconfig->{'ignore_errors'} = 0;
}
if (istrue($runconfig->shrate)) {
Log(0, "\nERROR: The \"staggered homogenous\" rate method is not valid for reportable runs!\n");
$error++;
}
if (istrue($runconfig->minimize_builddirs)) {
Log(0, "\nNotice: You can't minimize build dirs in a reportable run.\n Ignoring your minimize_builddirs.\n");
$runconfig->{'minimize_builddirs'} = 0;
}
if (istrue($runconfig->minimize_rundirs)) {
Log(0, "\nNotice: You can't minimize run dirs in a reportable run.\n Ignoring your minimize_rundirs.\n");
$runconfig->{'minimize_rundirs'} = 0;
}
}
do_exit(1) if $error;
# Do parallel inter-run cleanup here
if ($runconfig->action eq 'interclean' && $::from_runspec == 3) {
foreach my $obj (@benchobjs) {
if ($obj->cleanup_rundirs(1, $cl_opts->{'rundir'})) {
Log(0, "\nInter-run cleanup for ".$obj->benchmark." FAILED\n");
do_exit(1);
}
}
do_exit(0);
}
$error = {}; # This is for the final summary
if ($runconfig->action ne 'report') {
if (!$::from_runspec || !istrue($runconfig->accessor_nowarn('nobuild'))) {
# Build benchmarks if needed
Log(2, "Compiling Binaries\n");
my $seen = {};
my $compile_error = {};
my @compile_error_list = ();
my @compile_success_list = ();
my $nodel = exists($ENV{"SPEC_${main::suite}_NO_RUNDIR_DEL"}) ? 1 : 0;
for (my $i = 0; $i < @benchobjs; $i++) {
my $obj = $benchobjs[$i];
my ($oname, $oext, $omach, $otune, $osmarttune) = ($obj->benchmark,
$obj->ext, $obj->mach,
$obj->tune,
$obj->smarttune);
# If we couldn't compile it before, we can't now, so remove it
# from the list
if ($compile_error->{$oname}{$oext}{$omach}{$osmarttune}) {
splice(@benchobjs, $i--, 1);
next;
}
next if $seen->{$oname}{$oext}{$omach}{$osmarttune}++;
Log(107, "\n------------------------------------------------------------------------\n");
# Call the benchmark's pre_build to fix up any variables that may
# need fixing up in order to pass check_exe.
$obj->pre_build('no path', 0);
if (istrue($runconfig->rebuild) || !$obj->check_exe(0) ||
$runconfig->action eq 'buildsetup') {
my $logstr = '';
if ($runconfig->action eq 'buildsetup') {
$logstr = ' Setting up build for ' . $obj->descmode('no_size' => 1, 'no_threads' => 1) . ': (';
} elsif (istrue($runconfig->accessor_nowarn('nobuild'))) {
Log(3, ' NOT Building '. $obj->descmode('no_size' => 1, 'no_threads' => 1) ."; nobuild is on\n");
if (!istrue($runconfig->fake)) {
$compile_error->{$oname}{$oext}{$omach}{$osmarttune}++;
push @compile_error_list, "${oname}(${osmarttune}; nobuild)";
$obj->{'compile_error'}=1;
$error->{$oname}++;
}
next;
} else {
$logstr = ' Building ' . $obj->descmode('no_size' => 1, 'no_threads' => 1) . ': (';
}
my ($directory) = $obj->reserve($nodel, 1, 'type'=>'build',
'username' => $runconfig->{'username'},
'ext'=>$oext,
'tune'=>$osmarttune );
$logstr .= File::Basename::basename($directory->path()). ') ['.ctime(time).']';
Log(3, "$logstr\n");
if ($obj->build($directory,
($runconfig->action eq 'buildsetup'))) {
if ($runconfig->action eq 'buildsetup') {
Log(0, "*** Error setting up build for $oname $osmarttune\n");
} else {
Log(0, "*** Error building $oname $osmarttune\n");
}
if (!istrue($runconfig->ignore_errors)) {
Log(0, "If you wish to ignore this error, please use '-I' or ignore errors.\n");
for my $obj (@benchobjs) {
$obj->release_rundirs();
}
update_config_md5($runconfig, $ext, $mach) if ($runconfig->action ne 'buildsetup');
do_exit(1);
} else {
$::keep_debug_log = 1;
}
$compile_error->{$oname}{$oext}{$omach}{$osmarttune}++;
my $tmpstr = "${oname}(${osmarttune}";
if ( exists $obj->{'result_list'}
&& (::ref_type($obj->{'result_list'}) eq 'ARRAY')) {
$tmpstr .= '; '.$obj->{'result_list'}->[0]->{'valid'};
}
push @compile_error_list, $tmpstr.')';
$obj->{'compile_error'}=1;
$error->{$obj->benchmark}++;
next;
} else {
push @compile_success_list, "${oname}(${osmarttune})";
update_config_md5($runconfig, $ext, $mach) if ($runconfig->action ne 'buildsetup');
}
if ($error->{$obj->benchmark} == 0 &&
istrue($runconfig->minimize_builddirs) &&
$runconfig->action ne 'buildsetup') {
Log(3, " Clearing directory '".($directory->path)."' after successful build of " . $obj->descmode('no_size' => 1, 'no_threads' => 1) . "\n");
$obj->remove_rundirs();
} else {
$obj->release_rundirs();
}
# If this is a fake run, make some vertical whitespace to
# separate these commands from others appearing later
if (istrue($runconfig->fake)) {
Log(0, "\n\n\n");
}
} else {
Log(3, ' Up to date ' . $obj->descmode('no_size' => 1, 'no_threads' => 1) . "\n");
}
}
if ($runconfig->action ne 'buildsetup') {
Log(0, "\n");
if (@compile_error_list+0 > 0) {
Log(0, "Build errors: ".join(', ', sort @compile_error_list)."\n");
}
if (@compile_success_list+0 > 0) {
Log(0, "Build successes: ".join(', ', sort @compile_success_list)."\n");
}
}
Log(0, "\n");
if ($runconfig->action eq 'build') {
Log(2, "Build Complete\n");
next;
} elsif ($runconfig->action eq 'buildsetup') {
Log(2, "Build Setup Complete\n");
next;
}
if (istrue($config->reportable) && @compile_error_list) {
# We know that ignore_errors is not in effect, so the only way
# to get _here_ in a reportable run is to specify --nobuild and
# have a benchmark that needs to be built.
# The run _would_ proceed just fine, but the end result would be
# invalid. Let's be merciful and end it here.
Log(0, "ERROR: Not all benchmarks available for reportable run!\n");
do_exit(1);
}
# Make a bundle
if ($runconfig->{'bundleaction'} eq 'make') {
if (@compile_error_list) {
Log(0, "ERROR: Not all benchmarks available for bundling!\n");
do_exit(1);
}
make_bundle($runconfig, \@benchobjs);
# There is no return from here
}
}
if (
$::lcsuite !~ /^(mpi2007|omp2001|omp2012)$/ &&
$^O !~ /MSWin/ &&
($runconfig->parallel_test > 1) &&
( istrue($runconfig->reportable) &&
$benchobjs[0]->size_class ne 'ref') ||
( !istrue($::from_runspec) &&
!istrue($runconfig->{reportable}) &&
$runconfig->{parallel_test_workloads} =~ /$benchobjs[0]->{size_class}/)
) {
Log(107, "\n-----------------------------------\n");
Log(0, "Running Benchmarks (up to ".$runconfig->parallel_test." concurrent processes)\n");
# run_parallel_tests will exit if there's an error
run_parallel_tests($runconfig, $cl_opts, @benchobjs);
next;
}
# If there's nothing to run (all have compile errors), then there are no rundirs
# to set up.
if (0 == grep { !istrue($_->compile_error) } @benchobjs) {
Log(2, "\nNOTICE: Nothing to run! No results will be generated.\n\n\n");
next;
}
# Setup Directories
# We can set up all the directories at once, or just before the run of
# each benchmark
Log(2, "Setting Up Run Directories\n") unless $::from_runspec;
if (!istrue($runconfig->minimize_rundirs) ||
$runconfig->action eq 'setup') {
my $seen = {};
my @setup_error_list = ();
for my $obj (@benchobjs) {
next if $obj->compile_error;
my ($oname, $oext, $omach, $otune, $osmarttune) = ($obj->benchmark,
$obj->ext, $obj->mach,
$obj->tune,
$obj->smarttune);
if (ref($seen->{$oname}{$oext}{$omach}{$otune}) eq '') {
# Figure out if the setup will be parallel
my $is_parallel_setup = $obj->is_parallel_setup($obj->max_copies);
if ($is_parallel_setup) {
Log(3, ' Setting up ', $obj->descmode('no_threads' => 1). "\n");
} else {
Log(3, ' Setting up ', $obj->descmode('no_threads' => 1). ': ');
}
my ($needed_setup, @dirnum) = $obj->setup_rundirs($obj->max_copies, $::from_runspec ? $cl_opts->{'rundir'} : undef);
$seen->{$oname}{$oext}{$omach}{$otune} = $obj;
if (!defined($needed_setup) || @dirnum+0 == 0) {
Log (0, "*** Error during benchmark setup for $oname\n");
ignore_or_exit();
$obj->{'setup_error'} = 1;
$error->{$obj->benchmark}++;
push @setup_error_list, "${oname}(${osmarttune})";
next;
}
if ($is_parallel_setup) {
Log(3, ' Finished setup: ');
}
Log(3, ($needed_setup ? "created" : "existing").' ('.join(', ', @dirnum).")\n");
# Do the post-setup action, if any
if ($::from_runspec == 0 || $::from_runspec == 1) {
my $postcmd = $runconfig->{'bench_post_setup'};
if ($postcmd ne '') {
my $rc = log_system($postcmd, undef, istrue($obj->accessor_nowarn('fake')), [ $obj ], 0);
if ($rc) {
Log(0, "\nERROR: bench_post_setup for ".$obj->descmode('no_threads' => 1)." returned non-zero exit code ($rc)\n");
ignore_or_exit();
$obj->{'setup_error'} = 1;
$error->{$obj->benchmark}++;
push @setup_error_list, "${oname}(${osmarttune})";
}
}
}
} else {
Log(3, ' Fixing up ', $obj->descmode('no_threads' => 1) . "\n");
$obj->link_rundirs($seen->{$oname}{$oext}{$omach}{$otune});
}
}
# Do the post-setup action, if any
if ($::from_runspec == 0) {
my $postcmd = $runconfig->{'post_setup'};
if ($postcmd ne '') {
my $rc = log_system($postcmd, undef, istrue($runconfig->accessor_nowarn('fake')), [ $runconfig ], 0);
if ($rc) {
Log(0, "\nERROR: post_setup returned non-zero exit code ($rc)\n");
ignore_or_exit();
}
}
}
if (@setup_error_list+0 > 0) {
Log(0, "\nSetup errors: ".join(', ', sort @setup_error_list)."\n\n");
}
}
} else {
# Make sure all benchmarks have options for flag parsing later on
my $logged = 0;
foreach my $obj (@benchobjs) {
my ($oname, $oext, $omach, $otune, $osmarttune) = ($obj->benchmark,
$obj->ext, $obj->mach,
$obj->tune,
$obj->smarttune);
my $ref = $runconfig->{$oname}{$otune}{$oext}{$omach};
$ref = {} unless (::ref_type($ref) eq 'HASH');
next if exists($ref->{'compile_options'});
# No stored compile options! Make them up now.
Log(2, "Generating Compile Options\n") unless $logged;
$logged++;
Log(3, ' Generating options for ' . $obj->descmode('no_size' => 1, 'no_threads' => 1) . "\n");
$ref->{'changedmd5'} = 1;
$ref->{'exemd5'} = 0; # Will cause rebuild when necessary
$ref->{'baggage'} = '' unless (defined($ref->{'baggage'}));
# Note use of all src.alts. For the purposes of the generated
# options, we assume that all src.alts are present and apply
# cleanly.
my $tmpstr = $obj->note_srcalts($ref, 1, $obj->get_srcalt_list());
Log(0, "$tmpstr\n") if $tmpstr ne '';
my $opts = $obj->get_options();
$ref->{'optmd5'} = $obj->option_md5($opts);
($ref->{'rawcompile_options'}, undef, $ref->{'compile_options'}) =
main::compress_encode($opts);
}
update_config_md5($runconfig, $ext, $mach);
}
my $success={};
if ($runconfig->action ne 'report' && !$::from_runspec) {
Log(107, "\n-----------------------------------\n");
if ($runconfig->action ne 'setup') {
Log(2, "Running Benchmarks\n");
} else {
Log(2, "Writing Command Files\n");
}
}
# Don't proceed if doing parallel setup
do_exit(0) if ($runconfig->action eq 'setup' && $::from_runspec);
# Run benchmarks, or just make the speccmds.cmd and compare.cmd files
# First, figure out who has the most iterations
my $max_iter = $runconfig->{'iterations'};
my $to_run = 0;
foreach my $bench (@benchobjs) {
if (($max_iter < $bench->iterations) &&
(!istrue($global_config->{'reportable'}) || $bench->size_class eq 'ref')) {
$max_iter = $bench->iterations;
}
$to_run++ unless $bench->compile_error || $bench->setup_error;
}
# If there's nothing to run (all have compile errors), then no rundirs
# will have been set up, and no results need be generated.
if ($to_run == 0) {
Log(2, "\nNOTICE: Nothing to run! No results will be generated.\n\n\n");
next;
}
foreach my $tune (sort bytune @{$runconfig->valid_tunes}) {
for (my $iter = 0; $iter < $max_iter; $iter++) {
for (my $i = 0; $i < @benchobjs; $i++) {
my $bench = $benchobjs[$i];
next if $bench->compile_error || $bench->setup_error;
next if $iter >= $bench->iterations;
next if ($runconfig->action eq 'setup' && $iter > 0);
next if ($bench->tune ne $tune);
Log(107, "\n-----------------------------------\n");
if ($runconfig->action ne 'setup') {
if (istrue($runconfig->minimize_rundirs)) {
Log(3, ' Setting up ' . $bench->descmode('no_threads' => 1), ': ');
my ($needed_setup, @dirnum) = $bench->setup_rundirs($bench->max_copies, $::from_runspec ? $cl_opts->{'rundir'} : undef);
Log(3, ($needed_setup ? "created" : "existing").' ('.join(', ', @dirnum).")\n");
# Do the post-setup action, if any
if ($::from_runspec == 0) {
my $postcmd = $runconfig->{'bench_post_setup'};
if ($postcmd ne '') {
my $rc = log_system($postcmd, undef, istrue($runconfig->accessor_nowarn('fake')), [ $bench ], 0);
if ($rc) {
Log(0, "\nERROR: bench_post_setup for ".$bench->descmode('no_threads' => 1)." returned non-zero exit code ($rc)\n");
do_exit(1);
}
}
}
}
} elsif ($runconfig->action ne 'report') {
Log(3, ' Writing control file for ' . $bench->descmode . "\n");
}
for my $copies (@{$bench->copylist}) {
my $rc;
if ($runconfig->action eq 'report') {
$rc = $bench->make_empty_result($copies, $iter, 1);
} else {
if ($runconfig->action ne 'setup' &&
$bench->cleanup_rundirs($copies)) {
Log(0, "\nInter-run cleanup for ".$bench->benchmark." FAILED\n");
$bench->release_rundirs();
do_exit(1);
}
if ($bench->post_setup(map { $_->path } @{$bench->{'dirlist'}})) {
Log(0, "ERROR: post_setup for " . $bench->benchmark . " failed!\n");
Log(0, "\nError during inter-run post-setup of ".$bench->benchmark."\n");
return(undef);
}
if ($runconfig->action ne 'setup') {
my $logstr = ' Running ';
$logstr .= '(#'.($iter + 1).') ' if ($max_iter > 1);
$logstr .= $bench->descmode;
if (($copies > 1) || istrue($runconfig->rate)) {
$logstr .= " ($copies ";
if ($copies != 1) {
$logstr .= 'copies)'
} else {
$logstr .= 'copy)';
}
}
$logstr .= ' ['.ctime(time).']';
Log(3, "$logstr\n");
}
$rc = $bench->run_benchmark($copies,
($runconfig->action eq 'setup'),
0, $iter);
if ($runconfig->action ne 'setup') {
my $outcome = 'Success';
my $error_code = '';
if ($rc->{'valid'} eq 'R?') {
$outcome = 'Run';
} elsif ($rc->{'valid'} ne 'S') {
$outcome = 'Error';
$error_code = ', errorcode='.$rc->{'valid'};
}
Log(106, sprintf(" %s %s %s %s ratio=%.2f, runtime=%f, power=%.2fW, temp=%.2f degC, humidity=%.2f%%%s\n",
$outcome,
$bench->benchmark,
$bench->tune,
$bench->size,
$rc->{'ratio'},
$rc->{'reported_sec'} + $rc->{'reported_nsec'}/1000000000,
$rc->{'avg_power'},
$rc->{'min_temp'},
$rc->{'max_hum'},
$error_code));
if ($rc->{'valid'} eq 'S') {
my $what = $bench->benchmark;
if ($::from_runspec) {
# Likely only 1 job, so note the tuning
# level and workload size
$what .= ' ('.$bench->tune.' '.$bench->size.')';
}
$success->{$what}++;
} elsif (istrue($config->fake)) {
Log(0, "Running with --fake; the run could not have been okay, but we will keep going.\n");
} elsif ($rc->{'valid'} ne 'R?') {
$error->{$bench->benchmark}++;
if (!istrue($runconfig->ignore_errors)) {
Log(0, "Invalid run; unable to continue.\n");
Log(0, "If you wish to ignore errors please use '-I' or ignore_errors\n") if !istrue($runconfig->reportable);
for my $bench (@benchobjs) {
$bench->release_rundirs();
}
do_exit(1);
} else {
$::keep_debug_log = 1;
}
}
}
}
}
if ($runconfig->action ne 'setup' &&
$runconfig->action ne 'report' &&
$error->{$bench->benchmark} == 0 &&
istrue($runconfig->minimize_rundirs)) {
Log(3, ' Removing ' . pluralize($bench->max_copies, 'rundir'). ' for ' . $bench->descmode('no_threads' => 1) . "\n");
$bench->remove_rundirs();
}
# If this is a fake run, make some vertical whitespace to
# separate these commands from others appearing later
if (istrue($runconfig->fake)) {
Log(0, "\n\n\n");
}
}
}
}
if ($runconfig->action eq 'setup') {
for my $obj (@benchobjs) {
$obj->release_rundirs();
}
Log(2, "Setup Complete\n");
do_exit(0);
}
# Print summary of results
if (keys %$error > 0) {
my $errors = 'Error:';
for my $bench (sort keys %$error) {
$errors .= ' '.$error->{$bench}.'x'.$bench;
}
Log(103, "$errors\n");
}
if (keys %$success > 0) {
my $successes = 'Success:';
for my $bench (sort keys %$success) {
$successes .= ' '.$success->{$bench}.'x'.$bench;
}
Log(103, "$successes\n");
}
for my $bench (@benchobjs) {
$bench->release_rundirs();
}
if ( !$::from_runspec
&& !::check_list($runconfig->no_monitor, $size)) {
monitor_post($runconfig);
}
# Measure idle power
if ( !$::from_runspec
&& $global_config->action =~ /^(validate|run|onlyrun|only_run)$/) {
if (istrue($global_config->power) && (!istrue($runconfig->{'reportable'}) || $benchobjs[0]->size_class eq 'ref')) {
Log(2, "Taking idle power measurement\n");
# Sleep a while to let the system quiesce
sleep $runconfig->{'idledelay'} if $runconfig->{'idledelay'} > 0;
measure_idle_power($runconfig);
}
}
if ($runconfig->action eq 'only_run') {
Log(2, "Run Complete\n");
next;
}
if ($::from_runspec) {
# When runspec calls itself, it does not want to generate reports
next;
}
next if (istrue($config->fake));
# The size_class for a given size MUST be the same for all benchmarks
# in the benchset, so getting the size from the first benchobj will not
# be a problem.
my $size_class = $benchobjs[0]->{'size_class'};
my $sizestr = ($size eq $size_class) ? $size : "$size ($size_class)";
# Skip production of raw reports for the mandatory test/train phase
# of a reportable run.
next if ($::lcsuite !~ /^(mpi2007|omp2001|omp2012)$/ &&
istrue($runconfig->reportable) &&
$benchobjs[0]->size_class ne 'ref');
Log(2, "Producing Raw Reports\n");
# Report results
Log(0, "mach: $mach\n");
Log(0, " ext: $ext\n");
Log(0, " size: $sizestr\n");
# Make a list of benchsets that will potentially be generating reports
my @setlist = grep {
istrue($_->output) &&
$_->{$size_class} eq $size &&
(!istrue($runconfig->reportable) ||
(istrue($runconfig->{'rate'}) && $_->{'rate_multiplier'} > 0) ||
(!istrue($runconfig->{'rate'}) && $_->{'speed_multiplier'} > 0))
}
sort { $b->{'name'} cmp $a->{'name'} }
@{$runconfig->setobjs};
for my $set (@setlist) {
Log(0, " set: ".$set->name."\n");
my $result = $set->report(\@benchobjs, $runconfig, $mach, $ext, $size, $size_class);
next unless defined($result);
if (search_flags_byclass($result, 'forbidden')) {
$result->{'forbiddenused'} = 1;
}
if (search_flags_byclass($result, 'unknown')) {
$result->{'unknownused'} = 1;
}
do_report($runconfig, $result, (@setlist > 1) ? $set->{'name'} : undef);
}
}
do_exit(0);
# This is the end of the main routine.
sub do_exit {
my ($rc) = @_;
my $rm_temps = ($rc == 0 && !istrue($global_config->keeptmp) && !$::from_runspec);
my $top = $global_config->top;
if ($global_config->output_root ne '') {
$top = $global_config->output_root;
}
# Wait for running children (if any) to exit
if ($::running) {
Log(0, "\nWaiting for subprocesses to exit...\n");
while($::running) {
check_children('do_exit', 1);
sleep 1;
}
}
my $lognum = $global_config->accessor_nowarn('lognum');
my $logname = $global_config->accessor_nowarn('logname');
my $tmpdir = get_tmp_directory($global_config, 0);
if (!$::from_runspec) {
if (defined($lognum) && $lognum+0 > 0) {
Log(0, "\nThe log for this run is in $top/result/${main::suite}.".$global_config->lognum.".log\n");
if (( !$rm_temps
|| (defined($::keep_debug_log) && $::keep_debug_log != 0))
&& ($logname ne '' && -f "${logname}.debug")) {
Log(0, "The debug log for this run is in ${logname}.debug\n");
}
Log(0, "\n");
} else {
Log(0, "\nThere is no log file for this run.\n\n");
}
if (!$rm_temps && (-d $tmpdir || $logname ne '')) {
Log(0, "*\n");
Log(0, "* Temporary files were NOT deleted; keeping temporaries such as\n");
if ($logname ne '') {
Log(0, "* ${logname}.debug");
}
if (-d $tmpdir) {
Log(0, " and\n") if ($logname ne '');
Log(0, "* $tmpdir\n");
} else {
Log(0, "\n");
}
Log(0, "* (These may be large!)\n");
Log(0, "*\n");
}
my $runspec_end_time=time;
Log(0, "runspec finished at ".ctime($runspec_end_time)."; ".($runspec_end_time - $::runspec_time)." total seconds elapsed\n");
}
close_log();
if ($rm_temps) {
# Attempt to remove temporary directories (if any)
if (-d $tmpdir && $tmpdir ne $top) {
# Make sure we're not _in_ the directory being removed
chdir $top;
eval {
local $SIG{__WARN__} = sub { die @_ };
File::Path::rmtree($tmpdir, 0, 1);
};
print "\nWARNING: $@\n" if $@;
}
# Also remove the debug log
if (!defined($::keep_debug_log) || $::keep_debug_log == 0) {
if ( defined($logname)
&& $logname ne ''
&& -f "${logname}.debug") {
unlink "${logname}.debug";
}
}
# And try a little to remove empty tmp directories. This is just
# to take care of the case when they would otherwise be left empty.
chdir $top;
foreach my $dir (sort keys %::tmpdirs_seen) {
if (-d $dir) {
Log(95, "Attempting to remove temporary directory \"$dir\" and its parent if they are empty.\n");
eval { rmdir $dir, dirname($dir) };
}
}
eval { rmdir dirname($tmpdir) };
}
exit $rc;
}
sub do_report {
my ($config, $result, $setname) = @_;
my $top = $config->top;
if ($config->output_root ne '') {
$top = $config->output_root;
}
my $subdir = $config->expid;
$subdir = undef if $subdir eq '';
my $fname = '';
return unless defined($result);
$result->{'time'}=$::runspec_time unless exists $result->{'time'};
if (exists($config->{'nc'}) && (::ref_type($config->{'nc'}) eq 'ARRAY') &&
@{$config->{'nc'}}+0 > 0) {
# New NC text overrides old NC text
$result->{'nc'} = $config->{'nc'};
} elsif (!exists($result->{'nc'}) || (::ref_type($result->{'nc'}) ne 'ARRAY')) {
$result->{'nc'} = [];
}
my $lognum = '';
$lognum = sprintf "%03d", $config->lognum;
$lognum .= '.'.$setname if defined($setname) && $setname ne '';
unless (defined($::website_formatter) && $::website_formatter) {
$lognum .= '.'.$config->size;
}
# Figure out if the log number needs to be incremented. Do this here so
# that all result files from the same run have the same number.
# This is of course not necessary when re-formatting results.
my $path = jp($top, $config->resultdir, $subdir);
my $current_lognum_ok = 0;
my $increment = undef;
while (!$current_lognum_ok) {
$current_lognum_ok = 1;
my $fname = $result->metric.'.'.$lognum;
$fname .= ".${increment}" if (defined($increment));
if (-f jp($path, "${fname}.${Spec::Format::raw::extension}")) {
$current_lognum_ok = 0;
$increment++;
next;
}
}
if (defined($increment)) {
$lognum = "${lognum}.${increment}";
}
# Always make a new raw file so that it can be incorporated into
# the other results.
delete $result->{'compraw'};
my $fn = get_raw_filename($config, $result, $lognum);
my ($rawtext, $rawwritten) = Spec::Format::raw->new->format($result, $fn);
Log(0, " format: raw -> ");
my $fh = new IO::File '>'.$fn;
if (!defined($fh)) {
Log(0, "\nERROR: Can't open output file '$fn': $!\n");
} else {
if (::ref_type($rawtext) ne 'ARRAY') {
Log(0, "\nFormatter didn't give me what I expected!\n(I wanted an ARRAY, and I got a ".ref($rawtext).".\n");
} else {
$fh->print(join("\n", @{$rawtext})."\n");
$fh->close();
if (-s $fn < length($rawtext)) {
Log(0, "\nERROR: Short file write for $fn (raw format)\n");
} else {
if ($config->action eq 'report') {
Log(0, "not saved");
} else {
Log(0, join(', ', ($fn, @{$rawwritten}))) if (::ref_type($rawwritten) eq 'ARRAY');
}
Log(0, "\n");
}
my $raw_exclude = '(?i:'.join('|', keys %{$Spec::Format::raw::synonyms}).')';
my @formats = grep { !m/^${raw_exclude}$/ } @{$config->formatlist};
# Now call rawformat
if (@formats) {
my @cmd = ('specperl');
push @cmd, '-d' if $^P;
push @cmd, jp($ENV{'SPEC'}, 'bin', 'rawformat'), '--output_format', join(':', @formats), '--from_runspec';
# The Windows command shell is remarkably inflexible when it
# comes to quoting things, so to be safe, options that may be
# commonly specified with whitespace, or commas, or anything
# else will be put into this file, which rawformat will read.
my $fh = new IO::File ">${fn}.opts";
if (defined($fh)) {
foreach my $key (qw(mailto mailmethod mailserver mailport
username lognum logname sendmail
mailcompress mail_reports
notes_wrap_columns notes_wrap_indent
review table)) {
$fh->print("$key=".$config->accessor_nowarn($key)."\n");
}
$fh->print('runspec_argv='.basename($0).' '.join(' ', @{$::global_config->orig_argv})."\n");
$fh->close();
push @cmd, '--opts-file', "${fn}.opts";
} else {
Log(110, "Error opening rawformat options file \"${fn}.opts\" for writing: $!\n");
}
push @cmd, @{$config->rawformat_opts}, $fn;
if ($^O =~ /MSWin/i) {
my $cmd = join(' ', @cmd);
my $out = qx/$cmd 2>&1/;
Log(0, $out);
} else {
runspec_system(1, undef, undef, undef, @cmd);
}
unlink "${fn}.opts";
}
if ($config->action eq 'report') {
# Report-only runs should not generate raw files. (There will
# still be one in the results themselves, though they will be
# devoid of any result sections.)
unlink $fn;
}
}
}
}
sub get_tmp_logdir {
my ($config, $no_create) = @_;
return get_tmp_directory($config, 1 - $no_create, 'templogs');
}
sub get_raw_filename {
my ($config, $result, $lognum) = @_;
my $top = $config->top;
if ($config->output_root ne '') {
$top = $config->output_root;
}
my $subdir = $config->expid;
$subdir = undef if $subdir eq '';
my $dir = jp($top, $config->resultdir, $subdir);
eval { mkpath($dir) };
if ($@) {
Log(0, "ERROR: Could not create result directory: $@\n");
return undef;
}
my $fname = $result->metric.".${lognum}.";
# If lognum is correct, this should never happen...
if (-f jp($dir, $fname.$Spec::Format::raw::extension)) {
my $count = 1;
while (-f jp($dir, $fname."$count.".$Spec::Format::raw::extension)) {
$count++;
}
$fname .= "$count.".$Spec::Format::raw::extension;
} else {
$fname .= $Spec::Format::raw::extension;
}
return jp($dir, $fname);
}
sub initialize_specdirs {
my ($config) = @_;
my $top = $config->top;
my $dirmode = $config->dirprot;
my $result = $config->resultdir;
my $configdir = $config->configdir;
# Make sure some basic directories exist
eval { mkpath([jp($top, $result), jp($top, $configdir)], 0, $dirmode) };
if ($@) {
Log(0, "ERROR: Couldn't create top-level directories\n");
do_exit(1);
}
}
sub update_config_md5 {
my ($localconfig, $ext, $mach) = @_;
my @newmd5 = ();
my %newmd5 = ();
my $ref;
my $globalref;
Log(90, "update_config_md5($localconfig, $ext, $mach) called\n");
# Ok, now update the md5 section of the config file
# These changes are made to the global config as well as the local, in case
# some runs are pending that might depend on this information.
for my $bench (sort keys %{$localconfig}) {
next if ($bench !~ /^\d\d\d\.\S+$/);
next if (::ref_type($localconfig->{$bench}) ne 'HASH');
$global_config->{$bench} = {} if (::ref_type($global_config->{$bench}) ne 'HASH');
for my $tune (sort keys %{$localconfig->{$bench}}) {
next if (::ref_type($localconfig->{$bench}{$tune}) ne 'HASH');
$global_config->{$bench}{$tune} = {} if (::ref_type($global_config->{$bench}{$tune}) ne 'HASH');
for my $ext (sort keys %{$localconfig->{$bench}{$tune}}) {
next if (::ref_type($localconfig->{$bench}{$tune}{$ext}) ne 'HASH');
$global_config->{$bench}{$tune}{$ext} = {} if (::ref_type($global_config->{$bench}{$tune}{$ext}) ne 'HASH');
for my $mach (sort keys %{$localconfig->{$bench}{$tune}{$ext}}) {
next if (::ref_type($localconfig->{$bench}{$tune}{$ext}{$mach}) ne 'HASH');
$global_config->{$bench}{$tune}{$ext}{$mach} = {} if (::ref_type($global_config->{$bench}{$tune}{$ext}{$mach}) ne 'HASH');
$ref = $localconfig->{$bench}{$tune}{$ext}{$mach};
$globalref = $global_config->{$bench}{$tune}{$ext}{$mach};
next unless (exists($ref->{'changedmd5'}) &&
($ref->{'changedmd5'} > 0));
next if $ref->{'optmd5'} eq '';
next if $ref->{'exemd5'} eq '';
$ref->{'baggage'} = '' unless (defined($ref->{'baggage'}));
# Make sure that the global config has a copy of all this _great_ stuff!
foreach my $thing (qw(compile_options rawcompile_options baggage optmd5
exemd5)) {
$globalref->{$thing} = deep_copy($ref->{$thing});
}
my @comp_options = split(/\n+/, $ref->{'compile_options'});
my @raw_options = split(/\n+/, $ref->{'rawcompile_options'});
my @baggage = split(/\n+/, $ref->{'baggage'});
push (@newmd5, "$bench=$tune=$ext=$mach:\n",
"# Last updated ".ctime(time)."\n",
"optmd5=".$ref->{'optmd5'}."\n",
"baggage=".join("\\\n", @baggage)."\n",
"compile_options=\\\n".join("\\\n", @comp_options)."\n",
# "raw_compile_options=".join("\\\n", @raw_options)."\n",
"exemd5=".$ref->{'exemd5'}."\n",
"\n");
$newmd5{"$bench=$tune=$ext=$mach:"} = 1;
Log(90, "Found new MD5 signature for $bench=$tune=$ext=$mach\n");
# Mark it as saved so it's not re-written for future runs
delete $ref->{'changedmd5'};
delete $globalref->{'changedmd5'};
}
}
}
}
if (@newmd5) {
my $name = $global_config->configpath;
Log(90, "Updating config file $name\n");
# This is all we have to do here, because we promise that the
# update process that follows won't change the file's inode
# (Systems without inodes, well, you're on your own.)
# Open the old config file to get the non-updated MD5 stuff, and
# eventually write out the new config file.
my $origfh = new IO::File "+<$name";
# Access to this section needs to be totally serialized to ensure
# that there are no races, that config file backups will be
# named properly, etc.
if (!defined($origfh)) {
Log(0, "Couldn't open config file ($name) for update.\n");
Log(0, "The error is '$!'.\n");
ignore_or_exit();
# If errors _are_ being ignored, don't continue; that'll spew a
# bunch of bogus error messages about locking not working.
Log(0, "\n************************************\n");
Log(0, "************************************\n");
Log(0, "** Your config file has _not_ been updated; your binaries will\n");
Log(0, "** be rebuilt the next time you try to run them.\n");
Log(0, "************************************\n");
Log(0, "************************************\n");
return;
}
my %locked = ();
$locked{$origfh} = 0;
if (istrue($localconfig->locking) && !istrue($localconfig->absolutely_no_locking)) {
# This will make a pile of errors if they're ignoring errors
my ($rc, $what) = lock_file($origfh, $name);
if (!defined($rc)) {
if ($what eq 'unimplemented') {
Log(0, "\n\nLOCK ERROR: Your system claims to not support file locking.\n\n");
} elsif ($what eq 'error') {
Log(0, "\n\nLOCK ERROR: Could not lock the config file ($name).\n");
}
Log(0, " There is now no guarantee that the update of the config file will go\n");
Log(0, " without trouble. Compare the backups to the new config file to ensure\n");
Log(0, " that things went properly.\n\n");
# Make sure there's a backup, since we can't ensure that the
# new config file won't be messed up.
$global_config->{'backup_config'} = 1;
$localconfig->{'backup_config'} = 1;
} else {
$locked{$origfh}++;
}
} else {
Log(0, "File locking is disabled by your config file. It is not safe to do parallel\n".
"builds or runs without locking.\n");
}
$origfh->seek(0, 0); # Probably unnecessary, but it won't hurt.
my $newname = $name;
my $vary = '';
my $olddate = '';
my $oldnum = '';
if ($newname =~ s/\.(\d{4})-(\d{2})-(\d{2})_(\d{4})$//) {
$oldnum = "$1$2$3$4";
$olddate = "$1-$2-$3_$4";
}
my $time = localtime(time);
my $newdate = sprintf("%04d-%02d-%02d_%02d%02d",
$time->year+1900, $time->mon+1, $time->mday,
$time->hour, $time->min);
my $newnum = sprintf("%04d%02d%02d%02d%02d",
$time->year+1900, $time->mon+1, $time->mday,
$time->hour, $time->min);
$newdate = $olddate if $oldnum > $newnum;
$newname .= ".$newdate";
$vary = 'a' if (-f "$newname$vary");
while (-f "$newname$vary") {
$vary++;
}
Log(90, "$name will be saved as $newname\n");
my $outfh = new IO::File ">$name.$$.new";
my ($rc, $what) = (1, '');
if (defined($outfh)) {
$locked{$outfh} = 0;
if (istrue($localconfig->locking) && !istrue($localconfig->absolutely_no_locking)) {
# This probably isn't completely necessary, but it won't
# hurt.
($rc, $what) = lock_file($outfh, "$name.$$.new");
if (!defined($rc) || $what ne 'ok') {
Log(0, "\n\nLOCK ERROR: \"$name.$$.new\" could not be locked, so \n");
Log(0, " there is no guarantee that the update of the config file will go without\n");
Log(0, " trouble. Compare the backups to the new config file to ensure that\n");
Log(0, " things went properly.\n\n");
$global_config->{'backup_config'} = 1;
$localconfig->{'backup_config'} = 1;
} else {
$locked{$outfh}++;
}
}
} else {
Log(0, "Could not open temporary config file ($name.$$.new) for writing.\nThe error message was '$!'.\n");
ignore_or_exit();
Log(0, "It's probably stupid to continue, but I'll do it anyway.\n");
}
# Clear out the old saved MD5 sums from the config structures
$global_config->{'oldmd5'} = '';
$localconfig->{'oldmd5'} = '';
my $rawtxtconfig = '';
my $lastline = '';
my @oldmd5s = ();
while (<$origfh>) {
last if /^__MD5__$/;
$rawtxtconfig .= $_;
$lastline = $_;
}
# Check to see if $lastline has \n at the end. If not, add one.
# __MD5__ *must* be on its own line!
if ($lastline !~ /^\s*$/o) {
$rawtxtconfig .= "\n";
}
# Now build up the list of old MD5 stuff
while (<$origfh>) {
tr/\015\012//d;
push @oldmd5s, $_;
}
# Now write the old stuff (and our new stuff) to the new config file
my $tmpoutput = "${rawtxtconfig}__MD5__\n";
my $expectedlength = length($tmpoutput);
$outfh->print($tmpoutput);
# Now go through the old MD5s and don't output the ones that
# are in newmd5
my $output = 0;
for my $line (@oldmd5s) {
if ($line =~ /^\s*([^=]+)=[^=]+=[^=]+=[^=]+:$/o) {
# This is the start of a new MD5 section
# If it's a key in the %newmd5 hash, we've updated it,
# so don't output.
# If it's not a valid benchmark name, don't output it.
if (exists($newmd5{$line}) ||
!exists($global_config->{'benchmarks'}->{$1})) {
$output = 0;
} else {
$output = 1;
$outfh->print("$line\n");
$expectedlength += length("$line\n");
}
} elsif ($output) {
$outfh->print("$line\n");
$expectedlength += length("$line\n");
}
}
$tmpoutput = join('', @newmd5);
$expectedlength += length($tmpoutput);
$outfh->print($tmpoutput);
# We're done with this output file, so unlock it
unlock_file($outfh) if (exists($locked{$outfh}) && $locked{$outfh} && istrue($localconfig->locking) && !istrue($localconfig->absolutely_no_locking));
$outfh->close();
# Check the size
if (-s "$name.$$.new" < $expectedlength) {
Log(0, "\nERROR: Short write while updating config file\n");
do_exit(1);
}
if (istrue($localconfig->backup_config)) {
# They want the backup, so make it
my $bfh = new IO::File ">$newname$vary";
if (!defined($bfh)) {
Log(0, "Couldn't create config backup file '$newname$vary': $!\n");
ignore_or_exit();
}
# Just rewind the original config file...
$origfh->seek(0, 0);
$bfh->print(<$origfh>);
$bfh->close(); # It'd be closed when we leave the scope anyway
}
# Okay, so now it's time to copy the newly written config file
# ($name.$$.new) to the original file ($name)
# We've opened the original config file for update, so let's use it!
seek($origfh, 0, 0);
my $ifh = new IO::File "<$name.$$.new";
if (!defined($ifh)) {
Log(0, "Couldn't open temporary config file ($name.$$.new) for reading.\nThe error message is '$!'\n");
ignore_or_exit();
}
# We need the array for the count of lines
my @configfile = <$ifh>;
$ifh->close();
# ...and we need $origconfig so we know how big the file is supposed to be.
my $origconfig = join('', @configfile);
print $origfh $origconfig;
$origfh->flush();
# Now, there's *no* *way* this should ever get smaller, since we're
# at worst replacing information, and often adding. Nevertheless,
# truncate the file to avoid boo-boos.
my $configlen = length($origconfig);
if ($^O =~ /MSWin/) {
# length() isn't right for the size of the file on disk. On NT,
# there will be one extra character per line.
$configlen += @configfile+0;
}
eval '$rc = truncate($origfh, $configlen);';
if ($@ || !defined($rc)) {
Log(0, "There was a problem truncating the config file.\n");
Log(0, "This *shouldn't* cause trouble, but you might want to visually inspect\n");
Log(0, "the end of the config file to make sure that it isn't longer or shorter\nthan it should be.");
}
# Now unlink the temporary file
if (unlink("$name.$$.new") != 1) {
Log(0, "Error unlinking temporary config file.\n");
ignore_or_exit();
}
# Everything probably went well (enough to get to this point, anyway)
# Unlock the config file
unlock_file($origfh) if (exists($locked{$origfh}) && $locked{$origfh} && istrue($localconfig->locking) && !istrue($localconfig->absolutely_no_locking));
$origfh->close();
}
}
sub make_per_run_config {
my ($master, $runconf) = @_;
my $runconfig = new Spec::Config;
# Copy everything so we can start fresh at will
# Ask for Storable's indulgence, as the benchsets contain CODE refs
my $old = $Storable::forgive_me;
$Storable::forgive_me = 1;
$runconfig = deep_copy($master);
$Storable::forgive_me = $old;
$runconfig->{'copies'} = $runconf->[0];
$runconfig->{'ext'} = $runconf->[1];
$runconfig->{'mach'} = $runconf->[2];
$runconfig->{'size'} = $runconf->[3];
$runconfig->{'iterations'} = $runconf->[4];
# Turn on --nobuild for each of the subsequent runs that may cause a
# rebuild. Also turn off --rebuild, since runs will fail (build error)
# when --nobuild and --rebuild are both "on".
if ($runconf->[5] > 0) {
$runconfig->{'nobuild'} = 1;
$runconfig->{'rebuild'} = 0;
}
# Copy the power analyzer and temperature meter lists; the socket object
# is a GLOB, which Storable doesn't deal with.
foreach my $type ('power', 'temp') {
for(my $i = 0; $i < @{$global_config->{$type.'meterlist'}}; $i++) {
# Only copy the reference to the socket, as we still want the
# response list to be empty
$runconfig->{$type.'meterlist'}->[$i]->{'sock'} = $global_config->{$type.'meterlist'}->[$i]->{'sock'};
}
}
return $runconfig;
}
sub usage {
my ($rc) = @_;
$rc = 0 unless defined($rc);
my $iswindows = ($^O =~ /win/i);
my $sep = ($iswindows) ? ':' : ',';
print "\nUsage: $0 [options]\n";
print "\nIf a long option shows an argument as mandatory, then it is mandatory\n";
print "for the equivalent short option also. Similarly for optional arguments.\n";
print "Optional arguments are enclosed in [].\n";
print "When using long arguments, the equals sign ('=') is optional.\n";
print "\nOption list (alphabetical order):\n";
print " -a ACTION Same as '--action ACTION'\n";
print " --action=ACTION Set the action for runspec to take. ACTION is\n";
print " one of: build, buildsetup, clean, clobber,\n";
print " configpp, scrub, report, run, setup, trash,\n";
print " validate\n";
print " --nobuild Do not attempt to build binaries\n";
print " -c FILE Same as '--config FILE'\n";
print " -C USERS[${sep}USERS...] Same as '--copies USERS[${sep}USERS...]\n" if ($::lcsuite !~ /^(mpi2007|omp2001|omp2012|accel)$/);
print " --check_version Check the suite version even for non-\n";
print " reportable runs\n";
print " --comment 'text' Add a comment to the log and the stored config\n";
print " file\n";
print " --config=FILE Set config file for runspec to use\n";
print " --copies=USERS[${sep}USERS...] Set the number of copies for a rate run\n" if ($::lcsuite !~ /^(mpi2007|omp2001|omp2012|accel)$/);
print " -D Same as '--rebuild'\n";
print " -d Same as '--deletework'\n";
print " --debug LEVEL Same as '--verbose LEVEL'\n";
print " --define SYMBOL[=VALUE] Define a config preprocessor macro called\n";
print " SYMBOL with the value VALUE.\n";
print " This option may be used more than once\n";
print " --define SYMBOL:VALUE Same as '--define SYMBOL=VALUE'\n";
print " --delay=<n> Sleep for <n> seconds before and after each\n";
print " benchmark invocation.\n";
print " --deletework Force work directories to be rebuilt\n";
if ($::lcsuite eq 'accel') {
print " --device name Select the device number or type to run on\n";
}
print " --dryrun Same as '--fake'\n";
print " --dry-run Same as '--fake'\n";
print " -e EXT[${sep}EXT...] Same as '--extension EXT[${sep}EXT...]'\n";
print " --ext=EXT[${sep}EXT...] Same as '--extension EXT[${sep}EXT...]'\n";
print " --extension=EXT[${sep}EXT...] Set the extensions\n";
print " -F URL Same as '--flagsurl URL'\n";
print " --fake Show what commands would be executed\n";
print " --fakereport Generate a report without compiling codes or\n";
print " doing a run.\n";
print " --fakereportable Same as '--reportonly --reportable'\n";
print " --[no]feedback Control whether builds use feedback directed\n";
print " optimization.\n";
print " --flagsurl=URL Use the file at URL as a flags\n";
print " description file.\n";
print " -h Same as '--help'\n";
print " --help Print this usage message\n";
print " --http_proxy=HOST[:PORT] Use HOST as a proxy when fetching flags files\n";
print " or flags file updates. If unspecified, PORT\n";
print " defaults to 80.\n";
print " -I Same as '--ignore_errors'\n";
print " -i SET[${sep}SET...] Same as '--size SET[${sep}SET...]\n";
print " --ignore_errors Continue with benchmark runs even if some fail\n";
print " --ignoreerror Same as '--ignore_errors'\n";
print " --info_wrap_columns=COLUMNS Cause non-note informational items to be\n";
print " wrapped at COLUMNS column\n";
print " --[no]keeptmp Controls deletion of temp files (default off)\n";
print " --infowrap=COLUMNS Same as '--info_wrap_columns=COLUMNS'\n";
print " --input SET[${sep}SET...] Same as '--size SET[${sep}SET...]\n";
print " --iterations=N Run each benchmark N times.\n";
print " -l Same as '--loose'\n";
print " --loose Do not produce a reportable result\n";
print " --noloose Same as '--reportable'\n";
print " -m NAME[${sep}NAME...] Same as '--machine NAME[${sep}NAME...]'\n";
print " -M Same as '--make_no_clobber'\n";
print " --mach=NAME[${sep}NAME...] Same as '--machine NAME[${sep}NAME...]'\n";
print " --machine=NAME[${sep}NAME...] Set the machine types\n";
print " --make_bundle NAME Gather the currently selected set of binaries\n";
print " and config files into a bundle that can be\n";
print " used to re-create the current run on a\n";
print " different system or installation.\n";
print " --make_no_clobber Do not delete existing object files before\n";
print " attempting to build\n";
print " --max_active_compares=N Same as '--maxcompares=N'\n";
print " --maxcompares=N Set the number of concurrent compares to N\n";
print " --mockup Same as '--reportonly --reportable'\n";
print " -n N Same as '--iterations=N'\n";
print " -N Same as '--nobuild'\n";
print " --notes_wrap_columns=COLUMNS Set wrap width for notes lines\n";
print " --noteswrap=COLUMNS Same as '--notes_wrap_columns=COLUMNS'\n";
print " -o FORMAT[${sep}...] Same as '--output_format=FORMAT[,...]'\n";
print " --output_format=FORMAT[${sep}...] Set the output format\n";
print " FORMAT is one of: all, cfg, check, csv,\n";
print " flags, html, mail, pdf, ps, raw, screen, text\n";
if ($::lcsuite !~ /^(mpi2007|omp2001|omp2012|accel)$/) {
print " --parallel_setup=N For rate runs, do per-benchmark run directory\n";
print " setup in parallel (N jobs at a time)\n";
print " --parallel_setup_type=X For parallel setup, set the job creation\n";
print " method. (X may be one of 'fork', 'submit',\n";
print " or 'none')\n";
print " --parallel_test=N For the mandatory test and train portion of\n";
print " a reportable run, run N jobs at a time.\n";
}
if ($::lcsuite eq 'accel') {
print " --platform name Select the platform to run on\n";
}
print " --[no]power Control power measurement during run\n";
print " --[no]preenv Control pre-run setting of environment variables\n";
print " via 'preENV_<xxx>' in the config file.\n";
print " -R Same as '--rawformat'\n";
if ($::lcsuite eq 'mpi2007') {
print " --ranks N Set the number of MPI ranks to run\n";
} elsif ($::lcsuite !~ /^(omp2001|omp2012|accel)$/) {
print " -r Same as '--rate'\n";
print " --rate [N] Do a throughput (rate) run\n";
}
print " --rawformat FILE[,FILE...] Format raw (.rsf) files\n";
print " --rebuild Force a rebuild of binaries\n";
print " --reportable Produce a reportable result\n";
print " --noreportable Same as '--loose'\n";
print " --reportonly Same as '--fakereport'\n";
print " --[no]review Format results for review\n";
print " -s Same as '--reportable'\n";
print " -S SYMBOL[=VALUE] Same as '--define SYMBOL=VALUE'\n";
print " -S SYMBOL:VALUE Same as '--define SYMBOL=VALUE'\n";
print " --[no]setprocgroup [Don't] attempt to create all\n";
print " processes in a single process group.\n";
#print " --shrate [n] Do a throughput (staggered homogenous rate) run\n";
#print " [n] is optional and specifies the number of\n";
#print " copies to run.\n";
print " --size=SET[,SET...] Select data set(s): test, train, ref\n";
#print " --stagger Set the between-copy time delay\n";
#print " (in milliseconds)\n"
print " --strict Same as '--reportable'\n";
print " --nostrict Same as '--loose'\n";
print " -T TUNE[,TUNE...] Same as '--tune TUNE[,TUNE...]\n";
print " --[no]table Do [not] include a detailed table of\n";
print " results in the text output.\n";
print " --test Run the Perl test suite\n";
if ($::lcsuite ne 'mpi2007') {
print " --threads N Set the number of threads to run\n";
}
print " --tuning=TUNE[,TUNE...] Select tuning levels: base, peak, all\n";
print " Same as '--tune TUNE[,TUNE...]\n";
print " --undef SYMBOL Remove any definition of this config\n";
print " preprocessor macro\n";
print " This option may be used more than once\n";
print " --unpack_bundle NAME Unpack a previously-created bundle of binaries\n";
print " and config files, but do not attempt to\n";
print " start a run using the settings in the bundle.\n";
print " -U NAME Same as '--username NAME'\n";
print " --update Check www.spec.org for updates to benchmark\n";
print " and example flag files, and example config\n";
print " files.\n";
print " --update_flags Same as '--update'\n";
print " --use_bundle NAME Use a previously-created bundle of binaries\n";
print " and config files for the current run.\n";
print " --username NAME Name of user to tag as owner for run directories\n";
print " -v N Same as '--verbose=N'\n";
print " --verbose=N Set verbosity level for messages to N\n";
print " -V Same as '--version'\n";
print " --version Output lots of version information\n";
print " -? Same as '--help'\n";
print "\nFor more detailed information about the options, please see\nhttp://www.spec.org/$::lcsuite/Docs/runspec.html\n";
exit($rc);
}
sub verbose_version_string {
my ($dont_panic) = @_;
# CVT2DEV: $dont_panic = 1; # You are free to shoot yourself in the foot
# Output lots of version information to make our lives easier when
# non-developers try to run the suite...
my $retval = '';
my %versions = ();
my $rcs_version = '$Id: runspec 2989 2015-03-03 18:59:03Z CloyceS $'; # '
# Get the version information from the various files
$versions{'suite'} = $::suite_version || get_suite_version();
my $fh = new IO::File "<$ENV{'SPEC'}/benchspec/version.txt";
$versions{'benchmarks'} = defined($fh) ? <$fh> : 'unknown';
$versions{'benchmarks'} =~ tr/\015\012//d;
$fh = new IO::File "<$ENV{'SPEC'}/bin/version.txt";
$versions{'tools'} = defined($fh) ? <$fh> : 'unknown';
$versions{'tools'} =~ tr/\015\012//d;
my $tmp = "This is the SPEC ${main::suite} benchmark tools suite.";
$retval .= sprintf "%*s$tmp\n\n", 40 - int(length($tmp) / 2), ' ';
$retval .= "Version summary:\n";
$retval .= sprintf "%11s version: $versions{'suite'}\n", ${main::suite};
$retval .= " Benchmarks version: $versions{'benchmarks'}\n";
$retval .= " Tools version: $versions{'tools'}\n";
$retval .= " runspec version: $version ($rcs_version)\n";
$retval .= "\n";
# Now do a listing of the relevant tools scripts & binaries
$retval .= "Tools information:\n";
$retval .= " Tools package installed: $toolset_name\n";
$retval .= " File locking method: ";
if ($^O !~ /MSWin/) {
if ($Config{'d_flock'} eq 'define') {
$retval .= "flock(2) (probably not network-safe)\n";
} elsif ($Config{'d_fcntl_can_lock'} eq 'define') {
$retval .= "fcntl(2) (probably network-safe)\n";
} elsif ($Config{'d_lockf'} eq 'define') {
$retval .= "lockf(3)\n";
} else {
$retval .= "none; DO NOT run multiple copies of runspec concurrently!\n";
}
} else {
$retval .= "LockFileEx (network-safe)\n";
}
# Read the directory stuff the "hard way" (in perl, without system) so we
# don't have to have two versions for NT and unix, and so the output can
# be made to look similar
my %bindir;
tie %bindir, 'IO::Dir', "$ENV{'SPEC'}/bin";
# Now, *theoretically*, we can just look for the files we want in the
# hash.
$retval .= "Mode | UID | GID | Size | Modified Date | Name\n";
foreach my $file (qw( specmake specmake.exe specperl specperl.exe
specinvoke specinvoke.exe specinvoke_pm specinvoke_pm.exe
specxz specxz.exe
specmd5sum specmd5sum.exe
specdiff specdiff.exe specpp
specrxp specrxp.exe
runspec runspec.bat
),
(grep { /(^libperl|\.dll$)/ } sort keys %bindir) ) {
if (!exists($bindir{$file})) {
# Might we be on a system that's case-stupid?
if (exists $bindir{uc($file)}) {
$file = uc($file);
} elsif (exists $bindir{lc($file)}) {
$file = lc($file);
}
}
if (exists ($bindir{$file})) {
my ($mode, $uid, $gid, $size, $mtime) = (
$bindir{$file}->mode() & 07777,
$bindir{$file}->uid(),
$bindir{$file}->gid(),
$bindir{$file}->size(),
$bindir{$file}->mtime() );
$retval .= sprintf "%04o | %-5d | %-5d | %7d | %20s | $file\n",
$mode, $uid, $gid, $size, $mtime ? timeformat($mtime) : '';
}
}
$retval .= "\n";
for my $ref ( [ 1, 0, 'specinvoke', 'specinvoke', '-v' ],
[ 1, 0, 'specmake', 'specmake', '-v' ],
[ 0, 1, 'specrxp', 'specrxp', '--version' ],
[ 0, 0, 'specxz', 'specxz', '-V' ],
[ 0, 0, 'specpp', 'specperl', '"'.$ENV{'SPEC'}.'/bin/specpp" -v' ],
[ 0, 0, 'specperl', 'specperl', '-v' ] ) {
my ($check, $multiline, $name, $file, $flag) = @{$ref};
# Check means that the program must be in the PATH
if (!$check) {
$file = "$ENV{'SPEC'}/bin/$file";
if ($^O =~ /MSWin/) {
$file =~ s#/#\\#g; # / to \
if (-e "${file}.bat") {
$file .= '.bat';
} else {
$file .= '.exe';
}
}
}
my $tmphdr = "Version info for $name ($file): ";
my $padding = (' ' x length($tmphdr));
$retval .= $tmphdr;
if (! -f "$file" && !$check) {
$retval = "$file is missing!\n";
print "\n\n*** Critical binary $file is missing!\n\n";
exit(1) unless $dont_panic;
} else {
# Try to run the thing to get its version. The devnull thing is
# to keep a program that wants to read stdin (older specbzip2)
# from hanging forever.
my $cmd = "\"$file\" $flag 2>&1 <".File::Spec->devnull();
# Get the non-blank lines
my @out = grep { !/^\s*$/ } split(/\n/, qx($cmd));
if ($? == 0) {
$retval .= shift(@out)."\n";
$retval .= $padding.join("\n$padding", @out)."\n" if ($multiline && @out);
} else {
@out = grep { !/\Q$file\E/ } @out;
if (@out) {
$retval .= shift(@out)."\n";
$retval .= $padding.join("\n$padding", @out)."\n" if ($multiline && @out);
} else {
$retval .= "$file is not in the search path!\n";
}
if ($check) {
print "\n\n*** Critical binary $file is not in the search path!\n\n";
exit(1) unless $dont_panic;
}
}
}
if ($name eq 'specperl') {
# This would be nonsensical if specperl isn't around, but this won't
# run without it...
$retval .= "${padding}For more detail on specperl, say 'specperl -V'\n";
}
}
return $retval;
}
sub verbose_version {
# Make the pipes hot!
$| = 1;
print verbose_version_string(1);
exit 0;
}
sub make_bundle {
my ($config, $benchobjs) = @_;
Log(2, "Making Bundle\n");
my $ans = 'n';
my @files = ();
unshift @files, @{$config->{'bundle_files'}} if (::ref_type($config->{'files_read'}) eq 'ARRAY');
push @files, @{$config->{'files_read'}};
for (my $i = 0; $i < @{$benchobjs}; $i++) {
push @files, $benchobjs->[$i]->exe_files_abs;
}
my $top = $config->top;
chdir($top);
if ($^O =~ /MSWin/) {
$top = Win32::GetLongPathName($top);
$top =~ s#\\#/#g;
}
my $topre = '';
$topre = 'i' if ($^O =~ /MSWin/);
$topre = qr/^(?${topre}:\Q$top\E[\/\\])/;
foreach my $file (@files) {
$file = File::Spec->rel2abs( $file );
if ($^O =~ /MSWin/) {
$file = Win32::GetLongPathName($file);
}
# Convert backslashes to forward slashes. Otherwise tar will not do
# the right thing on Windows when unpacking
$file =~ s#\\#/#g;
# Make sure each file is under $SPEC
if ($file !~ s/$topre//) {
Log(0, "ERROR: Cannot bundle files not under '$top'.\n");
Log(0, " The unbundleable file is '$file'\n");
do_exit(1);
}
}
# Check to see if we'll be stomping anything
my $shortname = basename($config->{'bundlename'});
my $cfname = $shortname.'.control';
my $bundlename = $config->{'bundlename'}.'.'.$::lcsuite.'bundle';
my $bundlepath = $bundlename;
if (dirname($bundlepath) eq '.') {
$bundlepath = jp($top, $bundlepath);
}
if (-f jp($top, 'config', $cfname)) {
print "\n\nWARNING: A control file for bundle \"$shortname\" already exists.\n";
print "Overwrite it? (y/n) ";
chomp($ans = <STDIN>);
if (!istrue($ans)) {
print "Aborting.\n";
do_exit(0);
}
unlink jp($top, 'config', $cfname);
}
if (-f $bundlepath || -f $bundlepath.'.xz') {
print "\n\nWARNING: A bundle file for \"$config->{'bundlename'}\" already exists.\n";
print "Overwrite it? (y/n) ";
chomp($ans = <STDIN>);
if (!istrue($ans)) {
print "Aborting.\n";
do_exit(0);
}
unlink $bundlepath;
unlink $bundlepath.'.xz';
}
# Write the control file
my $ofh = new IO::File '>'.jp($top, 'config', $cfname);
if (!defined($ofh)) {
Log(0, "ERROR: Couldn't open config/$cfname for writing: $!\n");
do_exit(1);
}
my $configfile = $config->configpath;
$configfile =~ s/^\Q$top\E[\/\\]config[\/\\]//;
$ofh->print("--config=$configfile\n");
$ofh->print("--ext=".$config->ext."\n");
$ofh->print("--mach=".$config->mach."\n");
if (exists($cl_opts->{'reportable'})) {
if (istrue($cl_opts->{'reportable'})) {
$ofh->print("--reportable\n");
} else {
$ofh->print("--loose\n");
}
}
# Deal with command-line macros
if (::ref_type($cl_pp_macros) eq 'HASH') {
foreach my $macro (sort keys %{$cl_pp_macros}) {
$ofh->print("--define=$macro=$cl_pp_macros->{$macro}\n");
}
}
if (::ref_type($cl_opts->{'pp_unmacros'}) eq 'HASH') {
foreach my $macro (sort keys %{$cl_opts->{'pp_unmacros'}}) {
$ofh->print("--undef=$macro\n");
}
}
$ofh->print("--size=".$config->size."\n");
$ofh->print("--iterations=".$config->iterations."\n");
if ($::lcsuite eq 'mpi2007') {
$ofh->print("--ranks=".$config->{'ranks'}."\n") if ($config->{'ranks'} > 0);
} elsif ($::lcsuite =~ /^(?:cpuv6|omp20(01|12))$/) {
$ofh->print("--threads=".$config->{'ranks'}."\n") if ($config->{'ranks'} > 0);
}
if ($::lcsuite =~ /^cpu/) {
$ofh->print("--rate\n--copies=".$config->{'copies'}."\n") if istrue($config->rate);
}
$ofh->print("--tune=".join(':', @{$config->tunelist})."\n");
$ofh->print(join (' ', map { $_->benchmark } @{$config->runlist})."\n");
$ofh->close();
unshift @files, jp('config', $cfname);
# Make up MD5s for the included files, so we can do a better job of
# not stomping things whose size don't change
my @md5files = ();
foreach my $file (@files) {
my ($fn, $path) = fileparse($file);
my $md5 = md5filedigest($file);
my $md5file = jp($path, "MD5.$fn.$md5");
my $ofh = new IO::File '>'.$md5file;
$ofh->close() if defined($ofh); # Okay if it fails
push @md5files, $md5file if (-f $md5file);
}
push @files, @md5files;
Log(0, "\n\nNOTE: Libraries or DLLs dynamically linked to the bundled executables\n");
Log(0, " will NOT automatically be included in the bundle!\n");
Log(0, " You may specify other files and directories for inclusion on the runspec\n");
Log(0, " command line.\n");
my $rc = 0;
my @cmd = ('spectar', '-cf', $bundlepath, @files);
if ($^O =~ /MSWin/i) {
# Windows cmd.exe has a REALLY small limit on the length of a command
# line... 8KB. It's not long enough to handle all the filenames in a
# full base+peak int+fp bundle.
# The loop below will create a tarball (initially) and subsequently
# add to it until all the files are packed. The command lists are
# kept below 4KB because it's best to be a little conservative for
# stuff like this.
my $cmd = join(' ', splice(@cmd, 0, 3)); # Get the initial spectar
my $out;
while (@cmd > 0) {
while ((length($cmd)+length($cmd[0])) < 4090 && @cmd > 0) {
my $file = shift(@cmd);
next if $file =~ /^\s*$/;
$cmd .= ' '.$file;
}
$cmd .= ' 2>&1';
# Double up the backslashes so that they're not treated as escapes
$cmd =~ s/\\/\\\\/g;
$out = qx/$cmd/;
$rc = WEXITSTATUS($?);
Log(0, $out);
last if $rc;
# Queue up for the next run
$cmd = join(' ', ('spectar', '-rf', $bundlename));
}
} else {
$rc = runspec_system(1, undef, undef, undef, @cmd);
}
# Remove the MD5 dummy files now, before a possible exit
my $removed = unlink @md5files;
if ($rc) {
$rc >>= 8 if ($rc > 255);
Log(0, "\nERROR: spectar exited with code $rc when building bundle.\n\n");
do_exit(1);
}
if (-s $bundlepath) {
# Success? Try to compress it.
@cmd = ('specxz', $bundlepath);
if ($^O =~ /MSWin/i) {
my $cmd = join(' ', @cmd).' 2>&1';
# Double up the backslashes so that they're not treated as escapes
$cmd =~ s/\\/\\\\/g;
my $out = qx/$cmd/;
$rc = WEXITSTATUS($?);
Log(0, $out);
} else {
$rc = runspec_system(1, undef, undef, undef, @cmd);
}
}
if (-f $bundlepath.'.xz') {
$bundlepath .= '.xz';
}
unlink jp($top, 'config', $cfname);
Log(0, "\nBundling finished. The completed bundle is in\n ".$bundlepath."\n\n");
do_exit(0);
}
sub use_bundle {
my ($action, $name, $config) = @_;
my $rc;
print "\n".ucfirst($action)." Bundle: $name\n";
my $rm_uncomp = 1;
my $top = $config->top;
chdir($top);
$name =~ s/\.xz$//;
my $bundlename = $name;
$name = basename($bundlename, ".${main::lcsuite}bundle");
if ($bundlename !~ /\.${main::lcsuite}bundle$/) {
$bundlename .= ".${main::lcsuite}bundle";
}
# Allow for bundles that may not be in $SPEC
my $bundlepath = $bundlename;
$bundlename = basename($bundlename);
if (dirname($bundlepath) eq '.') {
$bundlepath = jp($top, $bundlename);
}
if (-f $bundlepath) {
# Uncompressed version exists; just use it.
$rm_uncomp = 0;
print " Using uncompressed bundle file \"$bundlepath\"\n";
} elsif (-f $bundlepath.'.xz') {
# Uncompress it, but only temporarily. It wouldn't do to surprise
# users by changing their files around
print " Uncompressing bundle file \"${bundlepath}.xz\"...";
my $ofh = new IO::File '>'.jp($top, $bundlename);
if (!defined($ofh)) {
print "\n\nERROR: Couldn't open temporary file for writing: $!\n";
do_exit(1);
}
$ofh->close();
# When there's an IO::Uncompress module to handle XZ, look at the code
# in CPUv6:r392 for the right way to do it. For now...
system "specxz -dc < ${bundlepath}.xz > ".jp($top,$bundlename);
my $status = $? >> 8;
if ($status) {
print "\n\nError decompressing \"${bundlepath}.xz\": specxz exited with $status\n";
unlink jp($top, $bundlename);
do_exit(1);
}
print "done!\n";
$bundlepath = jp($top, $bundlename);
} else {
print "\nERROR: The specified bundle ($bundlename) does not exist in $top\n";
do_exit(1);
}
# Use spectar to extract the TOC for the file
print " Reading bundle table of contents...";
my %files = ();
my @md5files = ();
my $nuldev = ($^O =~ /MSWin/) ? 'nul:' : '/dev/null';
if (open(TARPIPE, 'spectar -tvf '.$bundlepath." 2>$nuldev |")) {
while(defined(my $line = <TARPIPE>)) {
if ($line =~ m/\s+(\d+)\s+.*\s+(\S+)$/) {
my ($size, $fn) = ($1, $2);
if ($fn =~ m#(?:^|[/\\])MD5\.(.+)\.([0-9a-fA-F]{32})$#) {
my ($filepart, $md5) = ($1, $2);
push @md5files, $fn;
$fn = jp(dirname($fn), $filepart);
$files{$fn}->{'md5'} = $2;
} else {
$files{$fn}->{'size'} = $size;
}
}
}
close(TARPIPE);
$rc = WEXITSTATUS($?);
if ($rc) {
print "error!\n\nThe \"$bundlename\" file is not a valid $::suite bundle!\n\n";
do_exit(1);
}
if ((keys %files)+0 > 0) {
print ''.((keys %files)+0)." files\n";
} else {
print "error!\n\nThe \"$bundlename\" file is not a valid $::suite bundle!\n";
do_exit(1);
}
if (!exists($files{'config/'.$name.'.control'})) {
print "\nThis is not a valid bundle file.\n";
do_exit(1);
}
} else {
print "\n\nERROR: Could not run spectar to get bundle table of contents\n";
do_exit(1);
}
# Check for existence of files. For speed, just check the file sizes.
my @existing = ();
foreach my $file (keys %files) {
if (-f jp($top, $file)) {
if ( (-s jp($top, $file) != $files{$file}->{'size'})
|| ( $files{$file}->{'md5'} ne ''
&& md5filedigest(jp($top, $file)) ne $files{$file}->{'md5'})
) {
push @existing, $file;
}
}
}
if (@existing) {
print "\nThe following files already exist. Unpacking this bundle will cause\n";
print "these files to be overwritten:\n ".join("\n ", @existing)."\n";
print "Proceed with unpacking? (y/n) ";
my $ans = <STDIN>;
chomp($ans);
if (!istrue($ans)) {
print "Aborted\n";
do_exit(1);
}
}
print " Unpacking bundle file...";
my @cmd = ('spectar', '-xf', $bundlepath);
if ($^O =~ /MSWin/i) {
my $cmd = join(' ', @cmd).' 2>&1';
# Double up the backslashes so that they're not treated as escapes
$cmd =~ s/\\/\\\\/g;
my $out = qx/$cmd/;
$rc = WEXITSTATUS($?);
Log(0, $out);
} else {
$rc = runspec_system(1, undef, undef, undef, @cmd);
}
unlink jp($top, $bundlename) if $rm_uncomp;
unlink @md5files;
if ($rc) {
print "error!\n\nThere was an error unpacking the bundle; spectar returned $rc\n\n";
do_exit(1);
} else {
print "done\n";
}
# Read the control file and figure out what the new command line will
# be.
my $ifh = new IO::File '<'.jp($top, 'config', $name.'.control');
if (!defined($ifh)) {
print "\nERROR: The bundle control file couldn't be opened for reading: $!\n";
do_exit(1);
}
@cmd = (jp($top, 'bin', 'specperl'), jp($top, 'bin', 'runspec'));
while (defined(my $line = <$ifh>)) {
chomp($line);
push @cmd, split(/\s+/, $line);
}
$ifh->close();
# Clean up after ourselves
unlink jp($top, 'config', $name.'.control');
print " Bundle unpacking complete.\n";
if ($action eq 'unpack') {
print "\nTo execute this bundle as packaged, run the following command:\n ".join(' ', @cmd)."\n\n";
do_exit(0);
} else {
# Strip out the '--use-bundle' args from this command line and add them
# to the rest.
for(my $i = 0; $i < @::original_ARGV; $i++) {
if ($::original_ARGV[$i] =~ /^--use.bundle$/) {
$i++; # Skip the bundle name
next;
} elsif ($::original_ARGV[$i] =~ /^--use.bundle=\S+/) {
next;
}
push @cmd, $::original_ARGV[$i];
}
print " About to run:\n\n ".join(' ', @cmd)."\n\n";
if ($^O !~ /MSWin/) {
exec(@cmd);
} else {
# If we just exec(), the main program will run, the command prompt
# will be printed, and runspec will run. runspec will finish
# normally, but since no new prompt will be printed, the user will
# think that it's hung. So do this stupid thing...
system(@cmd);
exit;
}
print "\nERROR: Execution of the command failed: $!\n";
do_exit(1);
}
}
sub run_parallel_tests {
my ($config, $cl_opts, @benchobjs) = @_;
my $top = $config->top;
my @runspec_opts = ('--iterations', $runconfig->{'iterations'},
'--from_runspec', 1,
'--speed',
'--nouse-submit-for-speed',
'--extension', $runconfig->{'ext'},
'--machine', $runconfig->{'mach'},
'--size', $runconfig->{'size'},
'--nobuild',
'--noreportable',
'--noignore-errors',
'--verbose', $config->verbose,
);
my $logdir = ::get_tmp_logdir($::global_config);
if ( ! -d $logdir ) {
# Something went wrong!
Log(0, "WARNING: Temporary log directory \"$logdir\" couldn't be created\n");
do_exit(1);
}
my $concurrent = $config->parallel_test || 1;
%::children = ();
$::running = 0;
$::child_loglevel = 110;
@::copy_numbers = ( 0 .. $concurrent-1 );
my $start_time;
my @command = ();
my $command = '';
for(my $i = 0; $i < @benchobjs; $i++) {
my $obj = $benchobjs[$i];
next unless defined($obj) && (::ref_type($obj) eq 'HASH');
my $pid = undef;
if ($::running < $concurrent) {
my $logfile = jp($logdir, $obj->num.'.'.$obj->name.'.'.$runconfig->{'size'}.'.'.$obj->tune);
my $lognum = $::global_config->{'lognum'}.'.'.$i;
my $tmpdir = ::get_tmp_directory($config, 1, $obj->num.'.'.$obj->name.'.'.$runconfig->{'size'}.'.'.$obj->tune.$i);
if ( ! -d $tmpdir ) {
# Something went wrong!
Log(0, "ERROR: Temporary directory \"$tmpdir\" couldn't be created\n");
next;
}
chdir($tmpdir);
# Assemble the command here so that it can be logged to the main
# log file.
@command = generate_runspec_commandline($cl_opts, $config,
$cl_pp_macros,
$cl_opts->{'pp_unmacros'},
@runspec_opts,
'--copynum', $i,
'--tune', $obj->tune,
'--logfile', $logfile,
'--lognum', $lognum,
$obj->num.'.'.$obj->name);
my %submit = $obj->assemble_submit();
my $submit = exists($submit{'runspec'}) ? $submit{'runspec'} : $submit{'default'};
if ($submit eq '' || !istrue($config->parallel_test_submit)) {
$submit = '$command';
}
$obj->unshift_ref({ 'command' => '' });
$obj->command(join(' ', @command));
$command = ::command_expand($submit, $obj);
$obj->shift_ref();
my $copynum = shift @::copy_numbers;
if (!defined($copynum)) {
$copynum = $i;
}
$command =~ s/\$SPECCOPYNUM/$copynum/g;
my $bindval = $obj->bind;
my @bindopts = (::ref_type($bindval) eq 'ARRAY') ? @{$bindval} : ();
if (defined($bindval) && @bindopts) {
$bindval = $bindopts[$copynum % ($#bindopts + 1)];
$command =~ s/\$BIND/$bindval/g;
}
Log(110, "\nAbout to exec \"$command\"\n");
($start_time, $pid) = runspec_fork($obj, \%::children, $i,
'loglevel' => 3,
'parent_msg' => " Running ".$obj->descmode."\n",
'logfile' => $logfile,
);
if ($pid) {
chdir($top);
$::children{$pid}->{'logfile'} = $logfile;
$::children{$pid}->{'bench'} = $obj;
$::children{$pid}->{'tmpdir'} = $tmpdir;
$::children{$pid}->{'copynum'} = $copynum if defined($copynum);
next;
}
} else {
# Wait a bit for kids to exit
check_children('Run');
sleep 1;
redo; # Try again
}
# In child process here
exec $command;
Log(0, "ERROR: exec of runspec failed: $!\n");
do_exit(1);
}
if ($::running) {
Log(3, "Waiting for running processes to finish...\n\n");
}
while ($::running) {
check_children('Run');
sleep 1;
}
check_children('Run'); # Just in case
}
sub handle_child_exit {
my ($pid, $rc) = @_;
my @rmdirs = ();
if (!exists($::children{$pid})) {
::Log(99, "handle_child_exit(UNKNOWN:$pid, $rc)");
} else {
::Log(99, "handle_child_exit($pid, $rc)");
}
::Log(99, ' => '.(WIFEXITED($rc) ? 'EXITED' : '').' '.(WIFSIGNALED($rc) ? 'SIGNALED' : '').' status='.WEXITSTATUS($rc).'; signal='.WTERMSIG($rc)."\n");
return if ($::children{$pid}->{'handled'}); # Don't do it twice
$::children{$pid}->{'handled'} = 1;
if (exists $::children{$pid}->{'copynum'}) {
push @::copy_numbers, $::children{$pid}->{'copynum'};
}
$::running--;
$::children{$pid}->{'rc'} = -1;
if (WIFEXITED($rc)) {
$::children{$pid}->{'rc'} = WEXITSTATUS($rc);
$::children{$pid}->{'sig'} = 0;
}
if (WIFSIGNALED($rc)) {
$::children{$pid}->{'sig'} = WTERMSIG($rc);
}
my $baselogfile = $::children{$pid}->{'logfile'};
foreach my $logref ([ '', $::child_loglevel, 0 ], [ '.debug', 99, 1 ]) {
my ($ext, $loglvl, $isdebug) = @{$logref};
my $logfile = $baselogfile.$ext;
next unless $logfile ne '';
if (-f $logfile) {
my $ifh = new IO::File "<$logfile";
if (!defined($ifh)) {
Log(0, "Could not open $logfile for reading: $!\n");
} else {
my @lines = <$ifh>;
$ifh->close();
&{$::children{$pid}->{'log_proc'}}(@lines) if (::ref_type($::children{$pid}->{'log_proc'}) eq 'CODE');
if ($::children{$pid}->{'rc'} != 0 && $isdebug == 0) {
# As there was an error, make sure the log gets into the
# main system log.
Log(110, "\n***************************\n");
Log(110, "Child $pid exited with errors. Here is the full text of its log (from\n");
Log(110, "$logfile):\n");
Log(110, map { " $_" } @lines);
Log(110, "***************************\n");
} else {
Log($loglvl, @lines);
}
}
if (istrue($::global_config->keeptmp)) {
if ( -s $logfile > 0
&& ($isdebug == 0 || $::children{$pid}->{'rc'} != 0)) {
# Move it out of the way so that the next job with the same
# index doesn't nuke it.
# Minor race here, but these aren't really critical...
my $count = 0;
while (-f "${logfile}.read.$count") {
$count++;
}
rename $logfile, "${logfile}.read.$count";
} else {
# No need to save zero-length files or debug output for non-error exits
unlink $logfile;
}
} else {
unlink $logfile;
push @rmdirs, [ File::Basename::dirname($logfile), 0 ];
}
} elsif ($isdebug == 0) {
Log(0, "ERROR: Could not locate child log file \"$logfile\"\n Perhaps the process exited before it could produce output.\n");
Log(99, " --------\nLog dir list (".dirname($logfile)."):\n ".join("\n ", ::list_dir(dirname($logfile), 'stat' => 1))."\n--------\n");
$::children{$pid}->{'rc'} = -1 unless $::children{$pid}->{'rc'} || $::children{$pid}->{'sig'};
}
}
if (!istrue($::global_config->keeptmp) &&
exists($::children{$pid}->{'tmpdir'})) {
# $pid has a tmpdir registered; queue it for removal
push @rmdirs, [ $::children{$pid}->{'tmpdir'}, 1 ];
}
my $top = $::global_config->top;
$top = $::global_config->output_root if ($::global_config->output_root ne '');
my $tmplogdir = ::get_tmp_logdir($::global_config, 1);
foreach my $dirref (@rmdirs) {
my ($dir, $rmfiles) = @{$dirref};
next if $dir eq $tmplogdir;
if ($dir =~ /^\Q$top\E.+/) {
# $dir is under $top, and it's not $top, so remove it
if ($rmfiles) {
File::Path::rmtree($dir, 0, 1);
} else {
rmdir $dir;
}
}
}
}
sub check_children {
my ($what, $no_exit) = @_;
my $rc = 0;
# Check for children that may have exited
# Reap all the good little kiddies
main::REAPER('check');
my $tries = 0;
foreach my $kidpid (keys %::children) {
if (!exists $::children{$kidpid}->{'rc'}) {
# Has it exited?
my $exited = kill 0, $kidpid;
Log(99, "check_children($what): kill says $exited about $kidpid\n");
if ($exited <= 0) {
# It exited, but hasn't been seen by the reaper.
# Ask the reaper to take a look again:
if ($tries < 2) {
Log(99, "check_children($what): Asking the REAPER to look at $kidpid\n");
main::REAPER('check_unreaped', 1);
sleep 1 unless $tries == 0;
$tries++;
redo;
}
# It has exited and hasn't been through the REAPER in more than
# two seconds, even after we asked. I think it's safe to assume that
# _something_ has gone wrong...
Log(110, "ERROR: Child $kidpid no longer exists but was not reaped\n");
::handle_child_exit($kidpid, -1);
} else {
$::children{$kidpid}->{'lifecount'}++;
if ($::children{$kidpid}->{'lifecount'} > 10) {
# So the kid's been through this cycle 10 times now.
# Maybe it's still running, or maybe (Mac OS X) it's
# a zombie but kill still says it's running. So
# call the REAPER just this once.
Log(99, "check_children($what): zombie check: Asking the REAPER to look at $kidpid\n");
$::children{$kidpid}->{'lifecount'} = 0;
main::REAPER('check_old', 1);
}
next; # It's probably still running
}
}
if ($::children{$kidpid}->{'reported'} != 1) {
Log(99, "check_children($what): reporting on $kidpid\n");
$::children{$kidpid}->{'reported'} = 1;
my $benchobj = $::children{$kidpid}->{'bench'};
if (
# Either exit code was non-zero or a signal was received
( $::children{$kidpid}->{'rc'} != 0
|| $::children{$kidpid}->{'sig'} != 0)
# ...and the exit code is NOT in the error_exits_ok list
&&
( (::ref_type($::children{$kidpid}->{'error_exits_ok'}) ne 'ARRAY')
|| !grep { $_ == $::children{$kidpid}->{'rc'} } @{$::children{$kidpid}->{'error_exits_ok'}})
) {
my $msg = '';
my $desc = defined($benchobj) ? $benchobj->descmode('no_threads' => 1) : 'unknown benchmark';
if (defined($what) && $what ne '') {
$msg = "ERROR: $what for $desc FAILED (";
} else {
$msg = "ERROR: $desc FAILED (";
}
if ($::children{$kidpid}->{'rc'} > 0) {
$msg .= 'exit code '.$::children{$kidpid}->{'rc'};
$msg .= '; ' if ($::children{$kidpid}->{'sig'} > 0);
}
if ($::children{$kidpid}->{'sig'} > 0) {
$msg .= 'signal '.$::children{$kidpid}->{'sig'};
}
if ($msg =~ /\($/) {
# No signal and no exit code? Huh?
$msg .= 'no return code or signal info';
}
Log(0, "${msg}).\n See the log file for details.\n");
if (defined($no_exit) && $no_exit) {
next if istrue($::runconfig->ignore_errors);
} else {
::ignore_or_exit();
}
$rc |= $::children{$kidpid}->{'rc'} | $::children{$kidpid}->{'sig'};
}
}
$tries = 0;
}
return $rc;
}
sub REAPER {
# Do not fear it! It's no longer a signal handler anyway...
my ($signame, $no_reset_signal) = @_;
my $child;
Log(99, "REAPER($signame, $no_reset_signal) called\n");
while (($child = waitpid(-1, WNOHANG)) > 0) {
my $rc = $?;
::handle_child_exit($child, $rc);
Log(99, "REAPER reaped $child (rc was $rc)\n");
}
}
sub runspec_fork {
my ($me, $children, $idx, %opts) = @_;
my $loglevel = $opts{'loglevel'} || 0;
my $logfile = $opts{'logfile'};
if (!defined($logfile) || $logfile eq '') {
my $tmplogdir = ::get_tmp_logdir($::global_config, 0);
if (-d $tmplogdir) {
$logfile = jp($tmplogdir, $::global_config->prefix . $::global_config->log . '.' . $::global_config->{'lognum'} . '.log.' . $idx);
} else {
$logfile = $::global_config->{'logname'}.'.'.$idx;
}
}
my $start_time = Time::HiRes::time();
my $pid = fork();
if (!defined($pid)) {
Log(0, "ERROR: Could not start runspec sub-process: $!\n");
main::do_exit(1);
} elsif ($pid) {
# Parent
$children->{$pid} = {
'idx' => $idx,
'logfile' => $logfile,
'error_exits_ok' => $opts{'error_exits_ok'},
};
$::running++;
::Log(99, "Forked child $pid for index $idx at $start_time\n");
eval "::Log($loglevel, \"$opts{'parent_msg'}\")" if $opts{'parent_msg'} ne '';
} else {
# Child
main::clear_log_state();
main::close_log();
# Always open a log, because a) our parents expect us to and
# b) even if there's no log message from the parent, there might be
# from bind
main::open_log($me->config, $idx, $logfile, 1);
if ($opts{'log'} && $opts{'child_msg'} ne '') {
# This goes into the temp log, so the level information is
# effectively unused
eval "::Log($loglevel, \"$opts{'child_msg'}\")";
if ($@ ne '') {
print "Log output failed for $$: $@\n";
::do_exit(2);
}
}
if ($opts{'bind'} ne '') {
# Do copy number and BIND substition by hand, because log_system
# won't (it expects specinvoke to take care of it)
$opts{'bind'} =~ s/\$SPEC(?:COPY|USER)NUM/$idx/g;
my $bindval = $me->bind;
my @bindopts = (::ref_type($bindval) eq 'ARRAY') ? @{$bindval} : ();
if (defined($bindval) && @bindopts) {
$bindval = $bindopts[$idx % ($#bindopts + 1)];
$opts{'bind'} =~ s/\$BIND/$bindval/g;
}
# Do the expansion by hand so that the actual command can be
# logged.
$opts{'bind'} = ::path_protect($opts{'bind'});
$opts{'bind'} = command_expand($opts{'bind'}, [ $me, { '$' => $$ } ]);
$opts{'bind'} = ::path_unprotect($opts{'bind'});
# Try to get into a temp dir to catch the output (if any) from
# the bind command
my $tmpdir = get_tmp_directory($me->config, 0);
chdir $tmpdir if (-d $tmpdir);
::Log($loglevel, "About to run binding command for $$:\n---------\n$opts{'bind'}\n---------\n");
if (main::log_system_noexpand($opts{'bind'}, 'binding.'.$idx, istrue($me->fake), undef , 0)) {
::Log($loglevel, "Binding for $$ failed: $!\n");
main::close_log(); # Make sure everything is flushed
exit(255);
}
}
}
return ($start_time, $pid);
}
sub rmpath {
# Remove the contents of a given directory. Doesn't actually remove the
# directory itself.
my ($path) = @_;
# Remove the contents of the given path
my $dh = new IO::Dir $path;
return 0 if (!defined $dh); # Fail quietly; there's nothing to do.
while (defined($_ = $dh->read)) {
my $target = jp($path, $_);
if (-d $target) {
next if ($target =~ /\/\.{1,2}/o);
rmpath($target);
rmdir($target);
} else {
if (!unlink ($target)) {
Log(0, "Couldn't unlink $target - tree removal aborted\n");
return 0;
}
}
}
return 1;
}
sub ignore_or_exit {
if (!istrue($runconfig->ignore_errors)) {
if (!istrue($runconfig->reportable)) {
Log(0, "If you wish to ignore errors please use '-I' or ignore_errors\n");
}
do_exit(1);
}
$::keep_debug_log = 1;
}
sub is_clean {
# Return true if the string passed is the name of a cleaning action
my ($action) = @_;
return (
$action eq 'clean' ||
$action eq 'trash' ||
$action eq 'realclean' ||
$action eq 'clobber' ||
$action eq 'scrub' ||
0
);
return 0;
}
sub measure_idle_power {
my ($runconfig) = @_;
my $interval = [[time, undef]];
my $duration = $runconfig->{'idleduration'};
$duration = 5 unless $duration > 5;
# Now start the meters
my $isok = meter_start('Idle',
{
'a' => { 'default' => $runconfig->idle_current_range },
'v' => { 'default' => $runconfig->voltage_range },
},
@{$runconfig->powermeterlist});
if (!$isok) {
Log(0, "ERROR: Power analyzers could not be started\n");
ignore_or_exit();
}
$isok = meter_start('Idle', undef, @{$runconfig->tempmeterlist});
if (!$isok) {
Log(0, "ERROR: Temperature meters could not be started\n");
ignore_or_exit();
}
# Now sleep for a while
sleep $duration;
# ....and collect the results
$isok = meter_stop(@{$runconfig->powermeterlist});
if (!$isok) {
Log(0, "ERROR: Power analyzers could not be stopped\n");
ignore_or_exit();
}
$isok = meter_stop(@{$runconfig->tempmeterlist});
if (!$isok) {
Log(0, "ERROR: Temperature meters could not be stopped\n");
ignore_or_exit();
}
# Give the meters a second to stop
sleep 1;
$interval->[0]->[1] = time;
# Read the info and store it in the result object
my ($total, $avg, $min, $max, $max_uncertainty, $avg_uncertainty, $statsref, @list);
# First, power:
($isok, $total, $avg, $max_uncertainty, $avg_uncertainty, @list) = power_analyzer_watts($runconfig->meter_errors_percentage, @{$runconfig->powermeterlist});
if (!$isok || !defined($avg)) {
Log(0, "ERROR: Reading power analyzers returned errors\n");
ignore_or_exit();
}
$runconfig->{'idle_max_uncertainty'} = $max_uncertainty;
$runconfig->{'idle_avg_uncertainty'} = $avg_uncertainty;
extract_ranges($runconfig, \@list, 'idle_', @{$runconfig->powermeterlist});
# Generate totals (no samples should actually be trimmed)
my $junk;
($runconfig->{'idle_avg_power'},
$junk,
$runconfig->{'idle_min_power'},
$runconfig->{'idle_max_power'},
@{$runconfig->{'powersamples'}}) = extract_samples(\@list, $interval, 0);
# Now, temperature:
($isok, $statsref, @list) = temp_meter_temp_and_humidity($runconfig->meter_errors_percentage, @{$runconfig->tempmeterlist});
if ( !$isok
|| ::ref_type($statsref) ne 'HASH'
|| ::ref_type($statsref->{'temperature'}) ne 'ARRAY'
|| ::ref_type($statsref->{'humidity'}) ne 'ARRAY') {
Log(0, "ERROR: Temperature meters could not be read\n");
ignore_or_exit();
}
$statsref = {} unless ::ref_type($statsref) eq 'HASH';
foreach my $thing (qw(temperature humidity)) {
$statsref->{$thing} = [] unless ::ref_type($statsref->{$thing}) eq 'ARRAY';
}
($avg, $min, $max) = @{$statsref->{'temperature'}};
push @{$runconfig->{'tempsamples'}}, @list;
$runconfig->{'idle_avg_temp'} = defined($avg) ? $avg : 'Not Measured';
$runconfig->{'idle_min_temp'} = defined($min) ? $min : 'Not Measured';
$runconfig->{'idle_max_temp'} = defined($max) ? $max : 'Not Measured';
($avg, $min, $max) = @{$statsref->{'humidity'}};
$runconfig->{'idle_avg_hum'} = defined($avg) ? $avg : 'Not Measured';
$runconfig->{'idle_min_hum'} = defined($min) ? $min : 'Not Measured';
$runconfig->{'idle_max_hum'} = defined($max) ? $max : 'Not Measured';
}
BEGIN {
# Compiled last; executed first
require 5.10.0; # Make sure we have a recent version of perl
# See if we're being invoked by ourselves. If so, it'll be quiet time.
$::from_runspec = (grep { /^--from_runspec$/ } @ARGV)+0;
@::original_ARGV = @ARGV;
require 'setup_common.pl';
# Get the suite version (important when loading vars.pl)
$::suite_version = get_suite_version();
# Load some vars to find out what we're called today
load_module('vars.pl', 1);
if (! -f "$ENV{'SPEC'}/bin/runspec" &&
! -f "$ENV{'SPEC'}/bin/rawformat" ) {
print STDERR "\nThe SPEC environment variable is not set correctly!\nPlease source the shrc before invoking runspec.\n\n";
exit 1;
}
# Verify the integrity of the tools as early as possible
$| = 1; # Unbuffer the output
if (grep { /^-(?:-rawformat|R)$/ } @ARGV) {
# It's a request to format results. Pass it off to rawformat
if ($^O !~ /MSWin/) {
exec 'specperl', jp($ENV{'SPEC'}, 'bin', 'rawformat'), @ARGV;
} else {
# If we just exec(), the main program will run, the command prompt
# will be printed, and rawformat will run. rawformat will finish
# normally, but since no new prompt will be printed, the user will
# think that it's hung. So do this stupid thing...
system jp($ENV{'SPEC'}, 'bin', 'specperl'), jp($ENV{'SPEC'}, 'bin', 'rawformat'), @ARGV;
exit;
}
}
$version = '$Id: runspec 2989 2015-03-03 18:59:03Z CloyceS $ '; # Make emacs happier
my $year = 2015; # Just in case
if ($version =~ /^\044Id: \S+ (\d+) (\d+)-\d+-\d+ \d+:\d+:\S+ \S+ \$ $/) {
($version, $year) = ("v$1", $2);
} else {
$version = ''; # This should never happen
}
$tools_versions{'runspec'} = $1;
$toolset_name = read_toolset_name();
if (!$::from_runspec) {
print "runspec $version - Copyright 1999-$year Standard Performance Evaluation Corporation\n";
print "Using '$toolset_name' tools\n";
}
# Check for help options. There's no reason to load all the modules
# if they just want to see the usage message...
usage if (grep { /^--?(?:help|hel|he|h|\?)$/i } @ARGV);
if (0
# CVT2DEV: || 1
) {
print "\n\nWarning: this is a benchmark development tree. Please note that it is not\n";
print "possible to generate \"reportable\" runs using this copy of SPEC $::suite.\n";
print "If you wish to do a reportable run, please reinstall from the origial media\n";
print "in a new directory.\n\n\n";
sleep 1;
}
# No reason to load all the other crap if they just want the extended
# version info
verbose_version() if (grep { /^((?i:--version)|-V)$/o } @ARGV);
$debug = 0;
# Get an early indication of the verbosity desired
if (my @tmp = grep { /^(?:--verbose=?|--debug=?|-v)(\d*)$/ } @ARGV) {
($debug = $tmp[$#tmp]) =~ s/^(?:--verbose=?|--debug=?|-v)(\d*)$/$1/;
}
my ($file_size, $file_md5) = read_manifests('SUMS.tools', 'MANIFEST');
%file_size = %{$file_size};
%file_md5 = %{$file_md5};
check_important_files(qr#^\Q$ENV{'SPEC'}\E/bin/s[^/]+$#);
}
# Editor settings: (please leave this at the end of the file)
# vim: set filetype=perl syntax=perl shiftwidth=4 tabstop=8 expandtab nosmarttab:
|
./openacc-vv/atomic_update_max_expr_x.F90 | #ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a !Data
REAL(8),DIMENSION(LOOPCOUNT/10 + 1):: totals, totals_comparison
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
totals = 0
totals_comparison = 0
!$acc data copyin(a(1:LOOPCOUNT)) copy(totals(1:(LOOPCOUNT/10 + 1)))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
!$acc atomic update
totals(MOD(x, LOOPCOUNT/10 + 1) + 1) = max(a(x), totals(MOD(x, LOOPCOUNT/10 + 1) + 1))
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
totals_comparison(MOD(x, LOOPCOUNT/10 + 1) + 1) = max(totals_comparison(MOD(x, LOOPCOUNT/10 + 1) + 1), a(x))
END DO
DO x = 1, LOOPCOUNT/10 + 1
IF (totals_comparison(x) .NE. totals(x)) THEN
errors = errors + 1
WRITE(*, *) totals_comparison(x)
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./SPECaccel/benchspec/ACCEL/370.bt/src/y_solve.c | //-------------------------------------------------------------------------//
// //
// This benchmark is a serial C version of the NPB BT code. This C //
// version is developed by the Center for Manycore Programming at Seoul //
// National University and derived from the serial Fortran versions in //
// "NPB3.3-SER" developed by NAS. //
// //
// Permission to use, copy, distribute and modify this software for any //
// purpose with or without fee is hereby granted. This software is //
// provided "as is" without express or implied warranty. //
// //
// Information on NPB 3.3, including the technical report, the original //
// specifications, source code, results and information on how to submit //
// new results, is available at: //
// //
// http://www.nas.nasa.gov/Software/NPB/ //
// //
// Send comments or suggestions for this C version to cmp@aces.snu.ac.kr //
// //
// Center for Manycore Programming //
// School of Computer Science and Engineering //
// Seoul National University //
// Seoul 151-744, Korea //
// //
// E-mail: cmp@aces.snu.ac.kr //
// //
//-------------------------------------------------------------------------//
//-------------------------------------------------------------------------//
// Authors: Sangmin Seo, Jungwon Kim, Jun Lee, Jeongho Nah, Gangwon Jo, //
// and Jaejin Lee //
//-------------------------------------------------------------------------//
#include "header.h"
#include "work_lhs.h"
//#include "timers.h"
//---------------------------------------------------------------------
// Performs line solves in Y direction by first factoring
// the block-tridiagonal matrix into an upper triangular matrix,
// and then performing back substitution to solve for the unknow
// vectors of each line.
//
// Make sure we treat elements zero to cell_size in the direction
// of the sweep.
//---------------------------------------------------------------------
void y_solve()
{
int i, j, k, m, n, jsize, z;
double pivot, coeff;
int gp22, gp02;
double fjacY[5][5][PROBLEM_SIZE+1][IMAXP-1][KMAX-1];
double njacY[5][5][PROBLEM_SIZE+1][IMAXP-1][KMAX-1];
double lhsY[5][5][3][PROBLEM_SIZE][IMAXP-1][KMAX-1];
double temp1, temp2, temp3;
gp22 = grid_points[2]-2;
gp02 = grid_points[0]-2;
//---------------------------------------------------------------------
// This function computes the left hand side for the three y-factors
//---------------------------------------------------------------------
jsize = grid_points[1]-1;
//---------------------------------------------------------------------
// Compute the indices for storing the tri-diagonal matrix;
// determine a (labeled f) and n jacobians for cell c
//---------------------------------------------------------------------
#pragma acc data present(rho_i,u,rhs,square,qs) pcreate(lhsY,fjacY,njacY)
{
//#pragma acc parallel loop present(rho_i,u,qs,square,fjacY,njacY)
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
for (j = 0; j <= jsize; j++) {
temp1 = rho_i[k][j][i];
temp2 = temp1 * temp1;
temp3 = temp1 * temp2;
fjacY[0][0][j][i][k] = 0.0;
fjacY[0][1][j][i][k] = 0.0;
fjacY[0][2][j][i][k] = 1.0;
fjacY[0][3][j][i][k] = 0.0;
fjacY[0][4][j][i][k] = 0.0;
fjacY[1][0][j][i][k] = - ( u[k][j][i][1]*u[k][j][i][2] ) * temp2;
fjacY[1][1][j][i][k] = u[k][j][i][2] * temp1;
fjacY[1][2][j][i][k] = u[k][j][i][1] * temp1;
fjacY[1][3][j][i][k] = 0.0;
fjacY[1][4][j][i][k] = 0.0;
fjacY[2][0][j][i][k] = - ( u[k][j][i][2]*u[k][j][i][2]*temp2)
+ c2 * qs[k][j][i];
fjacY[2][1][j][i][k] = - c2 * u[k][j][i][1] * temp1;
fjacY[2][2][j][i][k] = ( 2.0 - c2 ) * u[k][j][i][2] * temp1;
fjacY[2][3][j][i][k] = - c2 * u[k][j][i][3] * temp1;
fjacY[2][4][j][i][k] = c2;
fjacY[3][0][j][i][k] = - ( u[k][j][i][2]*u[k][j][i][3] ) * temp2;
fjacY[3][1][j][i][k] = 0.0;
fjacY[3][2][j][i][k] = u[k][j][i][3] * temp1;
fjacY[3][3][j][i][k] = u[k][j][i][2] * temp1;
fjacY[3][4][j][i][k] = 0.0;
fjacY[4][0][j][i][k] = ( c2 * 2.0 * square[k][j][i] - c1 * u[k][j][i][4] )
* u[k][j][i][2] * temp2;
fjacY[4][1][j][i][k] = - c2 * u[k][j][i][1]*u[k][j][i][2] * temp2;
fjacY[4][2][j][i][k] = c1 * u[k][j][i][4] * temp1
- c2 * ( qs[k][j][i] + u[k][j][i][2]*u[k][j][i][2] * temp2 );
fjacY[4][3][j][i][k] = - c2 * ( u[k][j][i][2]*u[k][j][i][3] ) * temp2;
fjacY[4][4][j][i][k] = c1 * u[k][j][i][2] * temp1;
njacY[0][0][j][i][k] = 0.0;
njacY[0][1][j][i][k] = 0.0;
njacY[0][2][j][i][k] = 0.0;
njacY[0][3][j][i][k] = 0.0;
njacY[0][4][j][i][k] = 0.0;
njacY[1][0][j][i][k] = - c3c4 * temp2 * u[k][j][i][1];
njacY[1][1][j][i][k] = c3c4 * temp1;
njacY[1][2][j][i][k] = 0.0;
njacY[1][3][j][i][k] = 0.0;
njacY[1][4][j][i][k] = 0.0;
njacY[2][0][j][i][k] = - con43 * c3c4 * temp2 * u[k][j][i][2];
njacY[2][1][j][i][k] = 0.0;
njacY[2][2][j][i][k] = con43 * c3c4 * temp1;
njacY[2][3][j][i][k] = 0.0;
njacY[2][4][j][i][k] = 0.0;
njacY[3][0][j][i][k] = - c3c4 * temp2 * u[k][j][i][3];
njacY[3][1][j][i][k] = 0.0;
njacY[3][2][j][i][k] = 0.0;
njacY[3][3][j][i][k] = c3c4 * temp1;
njacY[3][4][j][i][k] = 0.0;
njacY[4][0][j][i][k] = - ( c3c4
- c1345 ) * temp3 * (u[k][j][i][1]*u[k][j][i][1])
- ( con43 * c3c4
- c1345 ) * temp3 * (u[k][j][i][2]*u[k][j][i][2])
- ( c3c4 - c1345 ) * temp3 * (u[k][j][i][3]*u[k][j][i][3])
- c1345 * temp2 * u[k][j][i][4];
njacY[4][1][j][i][k] = ( c3c4 - c1345 ) * temp2 * u[k][j][i][1];
njacY[4][2][j][i][k] = ( con43 * c3c4 - c1345 ) * temp2 * u[k][j][i][2];
njacY[4][3][j][i][k] = ( c3c4 - c1345 ) * temp2 * u[k][j][i][3];
njacY[4][4][j][i][k] = ( c1345 ) * temp1;
}
}
}
//---------------------------------------------------------------------
// now joacobians set, so form left hand side in y direction
//---------------------------------------------------------------------
//lhsY[k][i]init(lhsY[k][i], jsize);
// zero the whole left hand side for starters
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
for (n = 0; n < 5; n++) {
for (m = 0; m < 5; m++) {
lhsY[m][n][0][0][i][k] = 0.0;
lhsY[m][n][1][0][i][k] = 0.0;
lhsY[m][n][2][0][i][k] = 0.0;
lhsY[m][n][0][jsize][i][k] = 0.0;
lhsY[m][n][1][jsize][i][k] = 0.0;
lhsY[m][n][2][jsize][i][k] = 0.0;
}
}
}
}
// next, set all diagonal values to 1. This is overkill, but convenient
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
lhsY[0][0][1][0][i][k] = 1.0;
lhsY[0][0][1][jsize][i][k] = 1.0;
lhsY[1][1][1][0][i][k] = 1.0;
lhsY[1][1][1][jsize][i][k] = 1.0;
lhsY[2][2][1][0][i][k] = 1.0;
lhsY[2][2][1][jsize][i][k] = 1.0;
lhsY[3][3][1][0][i][k] = 1.0;
lhsY[3][3][1][jsize][i][k] = 1.0;
lhsY[4][4][1][0][i][k] = 1.0;
lhsY[4][4][1][jsize][i][k] = 1.0;
}
}
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
for (j = 1; j <= jsize-1; j++) {
temp1 = dt * ty1;
temp2 = dt * ty2;
lhsY[0][0][AA][j][i][k] = - temp2 * fjacY[0][0][j-1][i][k]
- temp1 * njacY[0][0][j-1][i][k]
- temp1 * dy1;
lhsY[0][1][AA][j][i][k] = - temp2 * fjacY[0][1][j-1][i][k]
- temp1 * njacY[0][1][j-1][i][k];
lhsY[0][2][AA][j][i][k] = - temp2 * fjacY[0][2][j-1][i][k]
- temp1 * njacY[0][2][j-1][i][k];
lhsY[0][3][AA][j][i][k] = - temp2 * fjacY[0][3][j-1][i][k]
- temp1 * njacY[0][3][j-1][i][k];
lhsY[0][4][AA][j][i][k] = - temp2 * fjacY[0][4][j-1][i][k]
- temp1 * njacY[0][4][j-1][i][k];
lhsY[1][0][AA][j][i][k] = - temp2 * fjacY[1][0][j-1][i][k]
- temp1 * njacY[1][0][j-1][i][k];
lhsY[1][1][AA][j][i][k] = - temp2 * fjacY[1][1][j-1][i][k]
- temp1 * njacY[1][1][j-1][i][k]
- temp1 * dy2;
lhsY[1][2][AA][j][i][k] = - temp2 * fjacY[1][2][j-1][i][k]
- temp1 * njacY[1][2][j-1][i][k];
lhsY[1][3][AA][j][i][k] = - temp2 * fjacY[1][3][j-1][i][k]
- temp1 * njacY[1][3][j-1][i][k];
lhsY[1][4][AA][j][i][k] = - temp2 * fjacY[1][4][j-1][i][k]
- temp1 * njacY[1][4][j-1][i][k];
lhsY[2][0][AA][j][i][k] = - temp2 * fjacY[2][0][j-1][i][k]
- temp1 * njacY[2][0][j-1][i][k];
lhsY[2][1][AA][j][i][k] = - temp2 * fjacY[2][1][j-1][i][k]
- temp1 * njacY[2][1][j-1][i][k];
lhsY[2][2][AA][j][i][k] = - temp2 * fjacY[2][2][j-1][i][k]
- temp1 * njacY[2][2][j-1][i][k]
- temp1 * dy3;
lhsY[2][3][AA][j][i][k] = - temp2 * fjacY[2][3][j-1][i][k]
- temp1 * njacY[2][3][j-1][i][k];
lhsY[2][4][AA][j][i][k] = - temp2 * fjacY[2][4][j-1][i][k]
- temp1 * njacY[2][4][j-1][i][k];
lhsY[3][0][AA][j][i][k] = - temp2 * fjacY[3][0][j-1][i][k]
- temp1 * njacY[3][0][j-1][i][k];
lhsY[3][1][AA][j][i][k] = - temp2 * fjacY[3][1][j-1][i][k]
- temp1 * njacY[3][1][j-1][i][k];
lhsY[3][2][AA][j][i][k] = - temp2 * fjacY[3][2][j-1][i][k]
- temp1 * njacY[3][2][j-1][i][k];
lhsY[3][3][AA][j][i][k] = - temp2 * fjacY[3][3][j-1][i][k]
- temp1 * njacY[3][3][j-1][i][k]
- temp1 * dy4;
lhsY[3][4][AA][j][i][k] = - temp2 * fjacY[3][4][j-1][i][k]
- temp1 * njacY[3][4][j-1][i][k];
lhsY[4][0][AA][j][i][k] = - temp2 * fjacY[4][0][j-1][i][k]
- temp1 * njacY[4][0][j-1][i][k];
lhsY[4][1][AA][j][i][k] = - temp2 * fjacY[4][1][j-1][i][k]
- temp1 * njacY[4][1][j-1][i][k];
lhsY[4][2][AA][j][i][k] = - temp2 * fjacY[4][2][j-1][i][k]
- temp1 * njacY[4][2][j-1][i][k];
lhsY[4][3][AA][j][i][k] = - temp2 * fjacY[4][3][j-1][i][k]
- temp1 * njacY[4][3][j-1][i][k];
lhsY[4][4][AA][j][i][k] = - temp2 * fjacY[4][4][j-1][i][k]
- temp1 * njacY[4][4][j-1][i][k]
- temp1 * dy5;
lhsY[0][0][BB][j][i][k] = 1.0
+ temp1 * 2.0 * njacY[0][0][j][i][k]
+ temp1 * 2.0 * dy1;
lhsY[0][1][BB][j][i][k] = temp1 * 2.0 * njacY[0][1][j][i][k];
lhsY[0][2][BB][j][i][k] = temp1 * 2.0 * njacY[0][2][j][i][k];
lhsY[0][3][BB][j][i][k] = temp1 * 2.0 * njacY[0][3][j][i][k];
lhsY[0][4][BB][j][i][k] = temp1 * 2.0 * njacY[0][4][j][i][k];
lhsY[1][0][BB][j][i][k] = temp1 * 2.0 * njacY[1][0][j][i][k];
lhsY[1][1][BB][j][i][k] = 1.0
+ temp1 * 2.0 * njacY[1][1][j][i][k]
+ temp1 * 2.0 * dy2;
lhsY[1][2][BB][j][i][k] = temp1 * 2.0 * njacY[1][2][j][i][k];
lhsY[1][3][BB][j][i][k] = temp1 * 2.0 * njacY[1][3][j][i][k];
lhsY[1][4][BB][j][i][k] = temp1 * 2.0 * njacY[1][4][j][i][k];
lhsY[2][0][BB][j][i][k] = temp1 * 2.0 * njacY[2][0][j][i][k];
lhsY[2][1][BB][j][i][k] = temp1 * 2.0 * njacY[2][1][j][i][k];
lhsY[2][2][BB][j][i][k] = 1.0
+ temp1 * 2.0 * njacY[2][2][j][i][k]
+ temp1 * 2.0 * dy3;
lhsY[2][3][BB][j][i][k] = temp1 * 2.0 * njacY[2][3][j][i][k];
lhsY[2][4][BB][j][i][k] = temp1 * 2.0 * njacY[2][4][j][i][k];
lhsY[3][0][BB][j][i][k] = temp1 * 2.0 * njacY[3][0][j][i][k];
lhsY[3][1][BB][j][i][k] = temp1 * 2.0 * njacY[3][1][j][i][k];
lhsY[3][2][BB][j][i][k] = temp1 * 2.0 * njacY[3][2][j][i][k];
lhsY[3][3][BB][j][i][k] = 1.0
+ temp1 * 2.0 * njacY[3][3][j][i][k]
+ temp1 * 2.0 * dy4;
lhsY[3][4][BB][j][i][k] = temp1 * 2.0 * njacY[3][4][j][i][k];
lhsY[4][0][BB][j][i][k] = temp1 * 2.0 * njacY[4][0][j][i][k];
lhsY[4][1][BB][j][i][k] = temp1 * 2.0 * njacY[4][1][j][i][k];
lhsY[4][2][BB][j][i][k] = temp1 * 2.0 * njacY[4][2][j][i][k];
lhsY[4][3][BB][j][i][k] = temp1 * 2.0 * njacY[4][3][j][i][k];
lhsY[4][4][BB][j][i][k] = 1.0
+ temp1 * 2.0 * njacY[4][4][j][i][k]
+ temp1 * 2.0 * dy5;
lhsY[0][0][CC][j][i][k] = temp2 * fjacY[0][0][j+1][i][k]
- temp1 * njacY[0][0][j+1][i][k]
- temp1 * dy1;
lhsY[0][1][CC][j][i][k] = temp2 * fjacY[0][1][j+1][i][k]
- temp1 * njacY[0][1][j+1][i][k];
lhsY[0][2][CC][j][i][k] = temp2 * fjacY[0][2][j+1][i][k]
- temp1 * njacY[0][2][j+1][i][k];
lhsY[0][3][CC][j][i][k] = temp2 * fjacY[0][3][j+1][i][k]
- temp1 * njacY[0][3][j+1][i][k];
lhsY[0][4][CC][j][i][k] = temp2 * fjacY[0][4][j+1][i][k]
- temp1 * njacY[0][4][j+1][i][k];
lhsY[1][0][CC][j][i][k] = temp2 * fjacY[1][0][j+1][i][k]
- temp1 * njacY[1][0][j+1][i][k];
lhsY[1][1][CC][j][i][k] = temp2 * fjacY[1][1][j+1][i][k]
- temp1 * njacY[1][1][j+1][i][k]
- temp1 * dy2;
lhsY[1][2][CC][j][i][k] = temp2 * fjacY[1][2][j+1][i][k]
- temp1 * njacY[1][2][j+1][i][k];
lhsY[1][3][CC][j][i][k] = temp2 * fjacY[1][3][j+1][i][k]
- temp1 * njacY[1][3][j+1][i][k];
lhsY[1][4][CC][j][i][k] = temp2 * fjacY[1][4][j+1][i][k]
- temp1 * njacY[1][4][j+1][i][k];
lhsY[2][0][CC][j][i][k] = temp2 * fjacY[2][0][j+1][i][k]
- temp1 * njacY[2][0][j+1][i][k];
lhsY[2][1][CC][j][i][k] = temp2 * fjacY[2][1][j+1][i][k]
- temp1 * njacY[2][1][j+1][i][k];
lhsY[2][2][CC][j][i][k] = temp2 * fjacY[2][2][j+1][i][k]
- temp1 * njacY[2][2][j+1][i][k]
- temp1 * dy3;
lhsY[2][3][CC][j][i][k] = temp2 * fjacY[2][3][j+1][i][k]
- temp1 * njacY[2][3][j+1][i][k];
lhsY[2][4][CC][j][i][k] = temp2 * fjacY[2][4][j+1][i][k]
- temp1 * njacY[2][4][j+1][i][k];
lhsY[3][0][CC][j][i][k] = temp2 * fjacY[3][0][j+1][i][k]
- temp1 * njacY[3][0][j+1][i][k];
lhsY[3][1][CC][j][i][k] = temp2 * fjacY[3][1][j+1][i][k]
- temp1 * njacY[3][1][j+1][i][k];
lhsY[3][2][CC][j][i][k] = temp2 * fjacY[3][2][j+1][i][k]
- temp1 * njacY[3][2][j+1][i][k];
lhsY[3][3][CC][j][i][k] = temp2 * fjacY[3][3][j+1][i][k]
- temp1 * njacY[3][3][j+1][i][k]
- temp1 * dy4;
lhsY[3][4][CC][j][i][k] = temp2 * fjacY[3][4][j+1][i][k]
- temp1 * njacY[3][4][j+1][i][k];
lhsY[4][0][CC][j][i][k] = temp2 * fjacY[4][0][j+1][i][k]
- temp1 * njacY[4][0][j+1][i][k];
lhsY[4][1][CC][j][i][k] = temp2 * fjacY[4][1][j+1][i][k]
- temp1 * njacY[4][1][j+1][i][k];
lhsY[4][2][CC][j][i][k] = temp2 * fjacY[4][2][j+1][i][k]
- temp1 * njacY[4][2][j+1][i][k];
lhsY[4][3][CC][j][i][k] = temp2 * fjacY[4][3][j+1][i][k]
- temp1 * njacY[4][3][j+1][i][k];
lhsY[4][4][CC][j][i][k] = temp2 * fjacY[4][4][j+1][i][k]
- temp1 * njacY[4][4][j+1][i][k]
- temp1 * dy5;
}
}
}
//---------------------------------------------------------------------
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// performs guaussian elimination on this cell.
//
// assumes that unpacking routines for non-first cells
// preload C' and rhs' from previous cell.
//
// assumed send happens outside this routine, but that
// c'(JMAX) and rhs'(JMAX) will be sent to next cell
//---------------------------------------------------------------------
//---------------------------------------------------------------------
// multiply c[k][0][i] by b_inverse and copy back to c
// multiply rhs(0) by b_inverse(0) and copy to rhs
//---------------------------------------------------------------------
//binvcrhs( lhsY[0][i][BB], lhsY[k][0][i][k][CC], rhs[k][0][i] );
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
/*
for(m = 0; m < 5; m++){
pivot = 1.00/lhsY[m][m][BB][0][i][k];
for(n = m+1; n < 5; n++){
lhsY[m][n][BB][0][i][k] = lhsY[m][n][BB][0][i][k]*pivot;
}
lhsY[m][0][CC][0][i][k] = lhsY[m][0][CC][0][i][k]*pivot;
lhsY[m][1][CC][0][i][k] = lhsY[m][1][CC][0][i][k]*pivot;
lhsY[m][2][CC][0][i][k] = lhsY[m][2][CC][0][i][k]*pivot;
lhsY[m][3][CC][0][i][k] = lhsY[m][3][CC][0][i][k]*pivot;
lhsY[m][4][CC][0][i][k] = lhsY[m][4][CC][0][i][k]*pivot;
rhs[k][0][i][m] = rhs[k][0][i][m]*pivot;
for(n = 0; n < 5; n++){
if(n != m){
coeff = lhsY[n][m][BB][0][i][k];
for(z = m+1; z < 5; z++){
lhsY[n][z][BB][0][i][k] = lhsY[n][z][BB][0][i][k] - coeff*lhsY[m][z][BB][0][i][k];
}
lhsY[n][0][CC][0][i][k] = lhsY[n][0][CC][0][i][k] - coeff*lhsY[m][0][CC][0][i][k];
lhsY[n][1][CC][0][i][k] = lhsY[n][1][CC][0][i][k] - coeff*lhsY[m][1][CC][0][i][k];
lhsY[n][2][CC][0][i][k] = lhsY[n][2][CC][0][i][k] - coeff*lhsY[m][2][CC][0][i][k];
lhsY[n][3][CC][0][i][k] = lhsY[n][3][CC][0][i][k] - coeff*lhsY[m][3][CC][0][i][k];
lhsY[n][4][CC][0][i][k] = lhsY[n][4][CC][0][i][k] - coeff*lhsY[m][4][CC][0][i][k];
rhs[k][0][i][n] = rhs[k][0][i][n] - coeff*rhs[k][0][i][m];
}
}
}
*/
pivot = 1.00/lhsY[0][0][BB][0][i][k];
lhsY[0][1][BB][0][i][k] = lhsY[0][1][BB][0][i][k]*pivot;
lhsY[0][2][BB][0][i][k] = lhsY[0][2][BB][0][i][k]*pivot;
lhsY[0][3][BB][0][i][k] = lhsY[0][3][BB][0][i][k]*pivot;
lhsY[0][4][BB][0][i][k] = lhsY[0][4][BB][0][i][k]*pivot;
lhsY[0][0][CC][0][i][k] = lhsY[0][0][CC][0][i][k]*pivot;
lhsY[0][1][CC][0][i][k] = lhsY[0][1][CC][0][i][k]*pivot;
lhsY[0][2][CC][0][i][k] = lhsY[0][2][CC][0][i][k]*pivot;
lhsY[0][3][CC][0][i][k] = lhsY[0][3][CC][0][i][k]*pivot;
lhsY[0][4][CC][0][i][k] = lhsY[0][4][CC][0][i][k]*pivot;
rhs[k][0][i][0] = rhs[k][0][i][0] *pivot;
coeff = lhsY[1][0][BB][0][i][k];
lhsY[1][1][BB][0][i][k]= lhsY[1][1][BB][0][i][k] - coeff*lhsY[0][1][BB][0][i][k];
lhsY[1][2][BB][0][i][k]= lhsY[1][2][BB][0][i][k] - coeff*lhsY[0][2][BB][0][i][k];
lhsY[1][3][BB][0][i][k]= lhsY[1][3][BB][0][i][k] - coeff*lhsY[0][3][BB][0][i][k];
lhsY[1][4][BB][0][i][k]= lhsY[1][4][BB][0][i][k] - coeff*lhsY[0][4][BB][0][i][k];
lhsY[1][0][CC][0][i][k] = lhsY[1][0][CC][0][i][k] - coeff*lhsY[0][0][CC][0][i][k];
lhsY[1][1][CC][0][i][k] = lhsY[1][1][CC][0][i][k] - coeff*lhsY[0][1][CC][0][i][k];
lhsY[1][2][CC][0][i][k] = lhsY[1][2][CC][0][i][k] - coeff*lhsY[0][2][CC][0][i][k];
lhsY[1][3][CC][0][i][k] = lhsY[1][3][CC][0][i][k] - coeff*lhsY[0][3][CC][0][i][k];
lhsY[1][4][CC][0][i][k] = lhsY[1][4][CC][0][i][k] - coeff*lhsY[0][4][CC][0][i][k];
rhs[k][0][i][1] = rhs[k][0][i][1] - coeff*rhs[k][0][i][0];
coeff = lhsY[2][0][BB][0][i][k];
lhsY[2][1][BB][0][i][k]= lhsY[2][1][BB][0][i][k] - coeff*lhsY[0][1][BB][0][i][k];
lhsY[2][2][BB][0][i][k]= lhsY[2][2][BB][0][i][k] - coeff*lhsY[0][2][BB][0][i][k];
lhsY[2][3][BB][0][i][k]= lhsY[2][3][BB][0][i][k] - coeff*lhsY[0][3][BB][0][i][k];
lhsY[2][4][BB][0][i][k]= lhsY[2][4][BB][0][i][k] - coeff*lhsY[0][4][BB][0][i][k];
lhsY[2][0][CC][0][i][k] = lhsY[2][0][CC][0][i][k] - coeff*lhsY[0][0][CC][0][i][k];
lhsY[2][1][CC][0][i][k] = lhsY[2][1][CC][0][i][k] - coeff*lhsY[0][1][CC][0][i][k];
lhsY[2][2][CC][0][i][k] = lhsY[2][2][CC][0][i][k] - coeff*lhsY[0][2][CC][0][i][k];
lhsY[2][3][CC][0][i][k] = lhsY[2][3][CC][0][i][k] - coeff*lhsY[0][3][CC][0][i][k];
lhsY[2][4][CC][0][i][k] = lhsY[2][4][CC][0][i][k] - coeff*lhsY[0][4][CC][0][i][k];
rhs[k][0][i][2] = rhs[k][0][i][2] - coeff*rhs[k][0][i][0];
coeff = lhsY[3][0][BB][0][i][k];
lhsY[3][1][BB][0][i][k]= lhsY[3][1][BB][0][i][k] - coeff*lhsY[0][1][BB][0][i][k];
lhsY[3][2][BB][0][i][k]= lhsY[3][2][BB][0][i][k] - coeff*lhsY[0][2][BB][0][i][k];
lhsY[3][3][BB][0][i][k]= lhsY[3][3][BB][0][i][k] - coeff*lhsY[0][3][BB][0][i][k];
lhsY[3][4][BB][0][i][k]= lhsY[3][4][BB][0][i][k] - coeff*lhsY[0][4][BB][0][i][k];
lhsY[3][0][CC][0][i][k] = lhsY[3][0][CC][0][i][k] - coeff*lhsY[0][0][CC][0][i][k];
lhsY[3][1][CC][0][i][k] = lhsY[3][1][CC][0][i][k] - coeff*lhsY[0][1][CC][0][i][k];
lhsY[3][2][CC][0][i][k] = lhsY[3][2][CC][0][i][k] - coeff*lhsY[0][2][CC][0][i][k];
lhsY[3][3][CC][0][i][k] = lhsY[3][3][CC][0][i][k] - coeff*lhsY[0][3][CC][0][i][k];
lhsY[3][4][CC][0][i][k] = lhsY[3][4][CC][0][i][k] - coeff*lhsY[0][4][CC][0][i][k];
rhs[k][0][i][3] = rhs[k][0][i][3] - coeff*rhs[k][0][i][0];
coeff = lhsY[4][0][BB][0][i][k];
lhsY[4][1][BB][0][i][k]= lhsY[4][1][BB][0][i][k] - coeff*lhsY[0][1][BB][0][i][k];
lhsY[4][2][BB][0][i][k]= lhsY[4][2][BB][0][i][k] - coeff*lhsY[0][2][BB][0][i][k];
lhsY[4][3][BB][0][i][k]= lhsY[4][3][BB][0][i][k] - coeff*lhsY[0][3][BB][0][i][k];
lhsY[4][4][BB][0][i][k]= lhsY[4][4][BB][0][i][k] - coeff*lhsY[0][4][BB][0][i][k];
lhsY[4][0][CC][0][i][k] = lhsY[4][0][CC][0][i][k] - coeff*lhsY[0][0][CC][0][i][k];
lhsY[4][1][CC][0][i][k] = lhsY[4][1][CC][0][i][k] - coeff*lhsY[0][1][CC][0][i][k];
lhsY[4][2][CC][0][i][k] = lhsY[4][2][CC][0][i][k] - coeff*lhsY[0][2][CC][0][i][k];
lhsY[4][3][CC][0][i][k] = lhsY[4][3][CC][0][i][k] - coeff*lhsY[0][3][CC][0][i][k];
lhsY[4][4][CC][0][i][k] = lhsY[4][4][CC][0][i][k] - coeff*lhsY[0][4][CC][0][i][k];
rhs[k][0][i][4] = rhs[k][0][i][4] - coeff*rhs[k][0][i][0];
pivot = 1.00/lhsY[1][1][BB][0][i][k];
lhsY[1][2][BB][0][i][k] = lhsY[1][2][BB][0][i][k]*pivot;
lhsY[1][3][BB][0][i][k] = lhsY[1][3][BB][0][i][k]*pivot;
lhsY[1][4][BB][0][i][k] = lhsY[1][4][BB][0][i][k]*pivot;
lhsY[1][0][CC][0][i][k] = lhsY[1][0][CC][0][i][k]*pivot;
lhsY[1][1][CC][0][i][k] = lhsY[1][1][CC][0][i][k]*pivot;
lhsY[1][2][CC][0][i][k] = lhsY[1][2][CC][0][i][k]*pivot;
lhsY[1][3][CC][0][i][k] = lhsY[1][3][CC][0][i][k]*pivot;
lhsY[1][4][CC][0][i][k] = lhsY[1][4][CC][0][i][k]*pivot;
rhs[k][0][i][1] = rhs[k][0][i][1] *pivot;
coeff = lhsY[0][1][BB][0][i][k];
lhsY[0][2][BB][0][i][k]= lhsY[0][2][BB][0][i][k] - coeff*lhsY[1][2][BB][0][i][k];
lhsY[0][3][BB][0][i][k]= lhsY[0][3][BB][0][i][k] - coeff*lhsY[1][3][BB][0][i][k];
lhsY[0][4][BB][0][i][k]= lhsY[0][4][BB][0][i][k] - coeff*lhsY[1][4][BB][0][i][k];
lhsY[0][0][CC][0][i][k] = lhsY[0][0][CC][0][i][k] - coeff*lhsY[1][0][CC][0][i][k];
lhsY[0][1][CC][0][i][k] = lhsY[0][1][CC][0][i][k] - coeff*lhsY[1][1][CC][0][i][k];
lhsY[0][2][CC][0][i][k] = lhsY[0][2][CC][0][i][k] - coeff*lhsY[1][2][CC][0][i][k];
lhsY[0][3][CC][0][i][k] = lhsY[0][3][CC][0][i][k] - coeff*lhsY[1][3][CC][0][i][k];
lhsY[0][4][CC][0][i][k] = lhsY[0][4][CC][0][i][k] - coeff*lhsY[1][4][CC][0][i][k];
rhs[k][0][i][0] = rhs[k][0][i][0] - coeff*rhs[k][0][i][1];
coeff = lhsY[2][1][BB][0][i][k];
lhsY[2][2][BB][0][i][k]= lhsY[2][2][BB][0][i][k] - coeff*lhsY[1][2][BB][0][i][k];
lhsY[2][3][BB][0][i][k]= lhsY[2][3][BB][0][i][k] - coeff*lhsY[1][3][BB][0][i][k];
lhsY[2][4][BB][0][i][k]= lhsY[2][4][BB][0][i][k] - coeff*lhsY[1][4][BB][0][i][k];
lhsY[2][0][CC][0][i][k] = lhsY[2][0][CC][0][i][k] - coeff*lhsY[1][0][CC][0][i][k];
lhsY[2][1][CC][0][i][k] = lhsY[2][1][CC][0][i][k] - coeff*lhsY[1][1][CC][0][i][k];
lhsY[2][2][CC][0][i][k] = lhsY[2][2][CC][0][i][k] - coeff*lhsY[1][2][CC][0][i][k];
lhsY[2][3][CC][0][i][k] = lhsY[2][3][CC][0][i][k] - coeff*lhsY[1][3][CC][0][i][k];
lhsY[2][4][CC][0][i][k] = lhsY[2][4][CC][0][i][k] - coeff*lhsY[1][4][CC][0][i][k];
rhs[k][0][i][2] = rhs[k][0][i][2] - coeff*rhs[k][0][i][1];
coeff = lhsY[3][1][BB][0][i][k];
lhsY[3][2][BB][0][i][k]= lhsY[3][2][BB][0][i][k] - coeff*lhsY[1][2][BB][0][i][k];
lhsY[3][3][BB][0][i][k]= lhsY[3][3][BB][0][i][k] - coeff*lhsY[1][3][BB][0][i][k];
lhsY[3][4][BB][0][i][k]= lhsY[3][4][BB][0][i][k] - coeff*lhsY[1][4][BB][0][i][k];
lhsY[3][0][CC][0][i][k] = lhsY[3][0][CC][0][i][k] - coeff*lhsY[1][0][CC][0][i][k];
lhsY[3][1][CC][0][i][k] = lhsY[3][1][CC][0][i][k] - coeff*lhsY[1][1][CC][0][i][k];
lhsY[3][2][CC][0][i][k] = lhsY[3][2][CC][0][i][k] - coeff*lhsY[1][2][CC][0][i][k];
lhsY[3][3][CC][0][i][k] = lhsY[3][3][CC][0][i][k] - coeff*lhsY[1][3][CC][0][i][k];
lhsY[3][4][CC][0][i][k] = lhsY[3][4][CC][0][i][k] - coeff*lhsY[1][4][CC][0][i][k];
rhs[k][0][i][3] = rhs[k][0][i][3] - coeff*rhs[k][0][i][1];
coeff = lhsY[4][1][BB][0][i][k];
lhsY[4][2][BB][0][i][k]= lhsY[4][2][BB][0][i][k] - coeff*lhsY[1][2][BB][0][i][k];
lhsY[4][3][BB][0][i][k]= lhsY[4][3][BB][0][i][k] - coeff*lhsY[1][3][BB][0][i][k];
lhsY[4][4][BB][0][i][k]= lhsY[4][4][BB][0][i][k] - coeff*lhsY[1][4][BB][0][i][k];
lhsY[4][0][CC][0][i][k] = lhsY[4][0][CC][0][i][k] - coeff*lhsY[1][0][CC][0][i][k];
lhsY[4][1][CC][0][i][k] = lhsY[4][1][CC][0][i][k] - coeff*lhsY[1][1][CC][0][i][k];
lhsY[4][2][CC][0][i][k] = lhsY[4][2][CC][0][i][k] - coeff*lhsY[1][2][CC][0][i][k];
lhsY[4][3][CC][0][i][k] = lhsY[4][3][CC][0][i][k] - coeff*lhsY[1][3][CC][0][i][k];
lhsY[4][4][CC][0][i][k] = lhsY[4][4][CC][0][i][k] - coeff*lhsY[1][4][CC][0][i][k];
rhs[k][0][i][4] = rhs[k][0][i][4] - coeff*rhs[k][0][i][1];
pivot = 1.00/lhsY[2][2][BB][0][i][k];
lhsY[2][3][BB][0][i][k] = lhsY[2][3][BB][0][i][k]*pivot;
lhsY[2][4][BB][0][i][k] = lhsY[2][4][BB][0][i][k]*pivot;
lhsY[2][0][CC][0][i][k] = lhsY[2][0][CC][0][i][k]*pivot;
lhsY[2][1][CC][0][i][k] = lhsY[2][1][CC][0][i][k]*pivot;
lhsY[2][2][CC][0][i][k] = lhsY[2][2][CC][0][i][k]*pivot;
lhsY[2][3][CC][0][i][k] = lhsY[2][3][CC][0][i][k]*pivot;
lhsY[2][4][CC][0][i][k] = lhsY[2][4][CC][0][i][k]*pivot;
rhs[k][0][i][2] = rhs[k][0][i][2] *pivot;
coeff = lhsY[0][2][BB][0][i][k];
lhsY[0][3][BB][0][i][k]= lhsY[0][3][BB][0][i][k] - coeff*lhsY[2][3][BB][0][i][k];
lhsY[0][4][BB][0][i][k]= lhsY[0][4][BB][0][i][k] - coeff*lhsY[2][4][BB][0][i][k];
lhsY[0][0][CC][0][i][k] = lhsY[0][0][CC][0][i][k] - coeff*lhsY[2][0][CC][0][i][k];
lhsY[0][1][CC][0][i][k] = lhsY[0][1][CC][0][i][k] - coeff*lhsY[2][1][CC][0][i][k];
lhsY[0][2][CC][0][i][k] = lhsY[0][2][CC][0][i][k] - coeff*lhsY[2][2][CC][0][i][k];
lhsY[0][3][CC][0][i][k] = lhsY[0][3][CC][0][i][k] - coeff*lhsY[2][3][CC][0][i][k];
lhsY[0][4][CC][0][i][k] = lhsY[0][4][CC][0][i][k] - coeff*lhsY[2][4][CC][0][i][k];
rhs[k][0][i][0] = rhs[k][0][i][0] - coeff*rhs[k][0][i][2];
coeff = lhsY[1][2][BB][0][i][k];
lhsY[1][3][BB][0][i][k]= lhsY[1][3][BB][0][i][k] - coeff*lhsY[2][3][BB][0][i][k];
lhsY[1][4][BB][0][i][k]= lhsY[1][4][BB][0][i][k] - coeff*lhsY[2][4][BB][0][i][k];
lhsY[1][0][CC][0][i][k] = lhsY[1][0][CC][0][i][k] - coeff*lhsY[2][0][CC][0][i][k];
lhsY[1][1][CC][0][i][k] = lhsY[1][1][CC][0][i][k] - coeff*lhsY[2][1][CC][0][i][k];
lhsY[1][2][CC][0][i][k] = lhsY[1][2][CC][0][i][k] - coeff*lhsY[2][2][CC][0][i][k];
lhsY[1][3][CC][0][i][k] = lhsY[1][3][CC][0][i][k] - coeff*lhsY[2][3][CC][0][i][k];
lhsY[1][4][CC][0][i][k] = lhsY[1][4][CC][0][i][k] - coeff*lhsY[2][4][CC][0][i][k];
rhs[k][0][i][1] = rhs[k][0][i][1] - coeff*rhs[k][0][i][2];
coeff = lhsY[3][2][BB][0][i][k];
lhsY[3][3][BB][0][i][k]= lhsY[3][3][BB][0][i][k] - coeff*lhsY[2][3][BB][0][i][k];
lhsY[3][4][BB][0][i][k]= lhsY[3][4][BB][0][i][k] - coeff*lhsY[2][4][BB][0][i][k];
lhsY[3][0][CC][0][i][k] = lhsY[3][0][CC][0][i][k] - coeff*lhsY[2][0][CC][0][i][k];
lhsY[3][1][CC][0][i][k] = lhsY[3][1][CC][0][i][k] - coeff*lhsY[2][1][CC][0][i][k];
lhsY[3][2][CC][0][i][k] = lhsY[3][2][CC][0][i][k] - coeff*lhsY[2][2][CC][0][i][k];
lhsY[3][3][CC][0][i][k] = lhsY[3][3][CC][0][i][k] - coeff*lhsY[2][3][CC][0][i][k];
lhsY[3][4][CC][0][i][k] = lhsY[3][4][CC][0][i][k] - coeff*lhsY[2][4][CC][0][i][k];
rhs[k][0][i][3] = rhs[k][0][i][3] - coeff*rhs[k][0][i][2];
coeff = lhsY[4][2][BB][0][i][k];
lhsY[4][3][BB][0][i][k]= lhsY[4][3][BB][0][i][k] - coeff*lhsY[2][3][BB][0][i][k];
lhsY[4][4][BB][0][i][k]= lhsY[4][4][BB][0][i][k] - coeff*lhsY[2][4][BB][0][i][k];
lhsY[4][0][CC][0][i][k] = lhsY[4][0][CC][0][i][k] - coeff*lhsY[2][0][CC][0][i][k];
lhsY[4][1][CC][0][i][k] = lhsY[4][1][CC][0][i][k] - coeff*lhsY[2][1][CC][0][i][k];
lhsY[4][2][CC][0][i][k] = lhsY[4][2][CC][0][i][k] - coeff*lhsY[2][2][CC][0][i][k];
lhsY[4][3][CC][0][i][k] = lhsY[4][3][CC][0][i][k] - coeff*lhsY[2][3][CC][0][i][k];
lhsY[4][4][CC][0][i][k] = lhsY[4][4][CC][0][i][k] - coeff*lhsY[2][4][CC][0][i][k];
rhs[k][0][i][4] = rhs[k][0][i][4] - coeff*rhs[k][0][i][2];
pivot = 1.00/lhsY[3][3][BB][0][i][k];
lhsY[3][4][BB][0][i][k] = lhsY[3][4][BB][0][i][k]*pivot;
lhsY[3][0][CC][0][i][k] = lhsY[3][0][CC][0][i][k]*pivot;
lhsY[3][1][CC][0][i][k] = lhsY[3][1][CC][0][i][k]*pivot;
lhsY[3][2][CC][0][i][k] = lhsY[3][2][CC][0][i][k]*pivot;
lhsY[3][3][CC][0][i][k] = lhsY[3][3][CC][0][i][k]*pivot;
lhsY[3][4][CC][0][i][k] = lhsY[3][4][CC][0][i][k]*pivot;
rhs[k][0][i][3] = rhs[k][0][i][3] *pivot;
coeff = lhsY[0][3][BB][0][i][k];
lhsY[0][4][BB][0][i][k]= lhsY[0][4][BB][0][i][k] - coeff*lhsY[3][4][BB][0][i][k];
lhsY[0][0][CC][0][i][k] = lhsY[0][0][CC][0][i][k] - coeff*lhsY[3][0][CC][0][i][k];
lhsY[0][1][CC][0][i][k] = lhsY[0][1][CC][0][i][k] - coeff*lhsY[3][1][CC][0][i][k];
lhsY[0][2][CC][0][i][k] = lhsY[0][2][CC][0][i][k] - coeff*lhsY[3][2][CC][0][i][k];
lhsY[0][3][CC][0][i][k] = lhsY[0][3][CC][0][i][k] - coeff*lhsY[3][3][CC][0][i][k];
lhsY[0][4][CC][0][i][k] = lhsY[0][4][CC][0][i][k] - coeff*lhsY[3][4][CC][0][i][k];
rhs[k][0][i][0] = rhs[k][0][i][0] - coeff*rhs[k][0][i][3];
coeff = lhsY[1][3][BB][0][i][k];
lhsY[1][4][BB][0][i][k]= lhsY[1][4][BB][0][i][k] - coeff*lhsY[3][4][BB][0][i][k];
lhsY[1][0][CC][0][i][k] = lhsY[1][0][CC][0][i][k] - coeff*lhsY[3][0][CC][0][i][k];
lhsY[1][1][CC][0][i][k] = lhsY[1][1][CC][0][i][k] - coeff*lhsY[3][1][CC][0][i][k];
lhsY[1][2][CC][0][i][k] = lhsY[1][2][CC][0][i][k] - coeff*lhsY[3][2][CC][0][i][k];
lhsY[1][3][CC][0][i][k] = lhsY[1][3][CC][0][i][k] - coeff*lhsY[3][3][CC][0][i][k];
lhsY[1][4][CC][0][i][k] = lhsY[1][4][CC][0][i][k] - coeff*lhsY[3][4][CC][0][i][k];
rhs[k][0][i][1] = rhs[k][0][i][1] - coeff*rhs[k][0][i][3];
coeff = lhsY[2][3][BB][0][i][k];
lhsY[2][4][BB][0][i][k]= lhsY[2][4][BB][0][i][k] - coeff*lhsY[3][4][BB][0][i][k];
lhsY[2][0][CC][0][i][k] = lhsY[2][0][CC][0][i][k] - coeff*lhsY[3][0][CC][0][i][k];
lhsY[2][1][CC][0][i][k] = lhsY[2][1][CC][0][i][k] - coeff*lhsY[3][1][CC][0][i][k];
lhsY[2][2][CC][0][i][k] = lhsY[2][2][CC][0][i][k] - coeff*lhsY[3][2][CC][0][i][k];
lhsY[2][3][CC][0][i][k] = lhsY[2][3][CC][0][i][k] - coeff*lhsY[3][3][CC][0][i][k];
lhsY[2][4][CC][0][i][k] = lhsY[2][4][CC][0][i][k] - coeff*lhsY[3][4][CC][0][i][k];
rhs[k][0][i][2] = rhs[k][0][i][2] - coeff*rhs[k][0][i][3];
coeff = lhsY[4][3][BB][0][i][k];
lhsY[4][4][BB][0][i][k]= lhsY[4][4][BB][0][i][k] - coeff*lhsY[3][4][BB][0][i][k];
lhsY[4][0][CC][0][i][k] = lhsY[4][0][CC][0][i][k] - coeff*lhsY[3][0][CC][0][i][k];
lhsY[4][1][CC][0][i][k] = lhsY[4][1][CC][0][i][k] - coeff*lhsY[3][1][CC][0][i][k];
lhsY[4][2][CC][0][i][k] = lhsY[4][2][CC][0][i][k] - coeff*lhsY[3][2][CC][0][i][k];
lhsY[4][3][CC][0][i][k] = lhsY[4][3][CC][0][i][k] - coeff*lhsY[3][3][CC][0][i][k];
lhsY[4][4][CC][0][i][k] = lhsY[4][4][CC][0][i][k] - coeff*lhsY[3][4][CC][0][i][k];
rhs[k][0][i][4] = rhs[k][0][i][4] - coeff*rhs[k][0][i][3];
pivot = 1.00/lhsY[4][4][BB][0][i][k];
lhsY[4][0][CC][0][i][k] = lhsY[4][0][CC][0][i][k]*pivot;
lhsY[4][1][CC][0][i][k] = lhsY[4][1][CC][0][i][k]*pivot;
lhsY[4][2][CC][0][i][k] = lhsY[4][2][CC][0][i][k]*pivot;
lhsY[4][3][CC][0][i][k] = lhsY[4][3][CC][0][i][k]*pivot;
lhsY[4][4][CC][0][i][k] = lhsY[4][4][CC][0][i][k]*pivot;
rhs[k][0][i][4] = rhs[k][0][i][4] *pivot;
coeff = lhsY[0][4][BB][0][i][k];
lhsY[0][0][CC][0][i][k] = lhsY[0][0][CC][0][i][k] - coeff*lhsY[4][0][CC][0][i][k];
lhsY[0][1][CC][0][i][k] = lhsY[0][1][CC][0][i][k] - coeff*lhsY[4][1][CC][0][i][k];
lhsY[0][2][CC][0][i][k] = lhsY[0][2][CC][0][i][k] - coeff*lhsY[4][2][CC][0][i][k];
lhsY[0][3][CC][0][i][k] = lhsY[0][3][CC][0][i][k] - coeff*lhsY[4][3][CC][0][i][k];
lhsY[0][4][CC][0][i][k] = lhsY[0][4][CC][0][i][k] - coeff*lhsY[4][4][CC][0][i][k];
rhs[k][0][i][0] = rhs[k][0][i][0] - coeff*rhs[k][0][i][4];
coeff = lhsY[1][4][BB][0][i][k];
lhsY[1][0][CC][0][i][k] = lhsY[1][0][CC][0][i][k] - coeff*lhsY[4][0][CC][0][i][k];
lhsY[1][1][CC][0][i][k] = lhsY[1][1][CC][0][i][k] - coeff*lhsY[4][1][CC][0][i][k];
lhsY[1][2][CC][0][i][k] = lhsY[1][2][CC][0][i][k] - coeff*lhsY[4][2][CC][0][i][k];
lhsY[1][3][CC][0][i][k] = lhsY[1][3][CC][0][i][k] - coeff*lhsY[4][3][CC][0][i][k];
lhsY[1][4][CC][0][i][k] = lhsY[1][4][CC][0][i][k] - coeff*lhsY[4][4][CC][0][i][k];
rhs[k][0][i][1] = rhs[k][0][i][1] - coeff*rhs[k][0][i][4];
coeff = lhsY[2][4][BB][0][i][k];
lhsY[2][0][CC][0][i][k] = lhsY[2][0][CC][0][i][k] - coeff*lhsY[4][0][CC][0][i][k];
lhsY[2][1][CC][0][i][k] = lhsY[2][1][CC][0][i][k] - coeff*lhsY[4][1][CC][0][i][k];
lhsY[2][2][CC][0][i][k] = lhsY[2][2][CC][0][i][k] - coeff*lhsY[4][2][CC][0][i][k];
lhsY[2][3][CC][0][i][k] = lhsY[2][3][CC][0][i][k] - coeff*lhsY[4][3][CC][0][i][k];
lhsY[2][4][CC][0][i][k] = lhsY[2][4][CC][0][i][k] - coeff*lhsY[4][4][CC][0][i][k];
rhs[k][0][i][2] = rhs[k][0][i][2] - coeff*rhs[k][0][i][4];
coeff = lhsY[3][4][BB][0][i][k];
lhsY[3][0][CC][0][i][k] = lhsY[3][0][CC][0][i][k] - coeff*lhsY[4][0][CC][0][i][k];
lhsY[3][1][CC][0][i][k] = lhsY[3][1][CC][0][i][k] - coeff*lhsY[4][1][CC][0][i][k];
lhsY[3][2][CC][0][i][k] = lhsY[3][2][CC][0][i][k] - coeff*lhsY[4][2][CC][0][i][k];
lhsY[3][3][CC][0][i][k] = lhsY[3][3][CC][0][i][k] - coeff*lhsY[4][3][CC][0][i][k];
lhsY[3][4][CC][0][i][k] = lhsY[3][4][CC][0][i][k] - coeff*lhsY[4][4][CC][0][i][k];
rhs[k][0][i][3] = rhs[k][0][i][3] - coeff*rhs[k][0][i][4];
}/*end i*/
}/*end k*/
//---------------------------------------------------------------------
// begin inner most do loop
// do all the elements of the cell unless last
//---------------------------------------------------------------------
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
for (j = 1; j <= jsize-1; j++) {
//-------------------------------------------------------------------
// subtract A*lhsY[k][i]_vector(j-1) from lhsY[k][i]_vector(j)
//
// rhs(j) = rhs(j) - A*rhs(j-1)
//-------------------------------------------------------------------
//matvec_sub(lhsY[i][j-1][AA], rhs[k][j][i][k], rhs[k][j][i]);
/*
for(m = 0; m < 5; m++){
rhs[k][j][i][m] = rhs[k][j][i][m] - lhsY[m][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[m][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[m][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[m][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[m][4][AA][j][i][k]*rhs[k][j-1][i][4];
}
*/
rhs[k][j][i][0] = rhs[k][j][i][0] - lhsY[0][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[0][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[0][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[0][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[0][4][AA][j][i][k]*rhs[k][j-1][i][4];
rhs[k][j][i][1] = rhs[k][j][i][1] - lhsY[1][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[1][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[1][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[1][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[1][4][AA][j][i][k]*rhs[k][j-1][i][4];
rhs[k][j][i][2] = rhs[k][j][i][2] - lhsY[2][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[2][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[2][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[2][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[2][4][AA][j][i][k]*rhs[k][j-1][i][4];
rhs[k][j][i][3] = rhs[k][j][i][3] - lhsY[3][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[3][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[3][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[3][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[3][4][AA][j][i][k]*rhs[k][j-1][i][4];
rhs[k][j][i][4] = rhs[k][j][i][4] - lhsY[4][0][AA][j][i][k]*rhs[k][j-1][i][0]
- lhsY[4][1][AA][j][i][k]*rhs[k][j-1][i][1]
- lhsY[4][2][AA][j][i][k]*rhs[k][j-1][i][2]
- lhsY[4][3][AA][j][i][k]*rhs[k][j-1][i][3]
- lhsY[4][4][AA][j][i][k]*rhs[k][j-1][i][4];
//-------------------------------------------------------------------
// B(j) = B(j) - C(j-1)*A(j)
//-------------------------------------------------------------------
// matmul_sub(lhsY[j-1][i][AA], lhsY[k][j][i][k][CC], lhsY[k][i][j][BB]);
/*
for(m = 0; m < 5; m++){
for(n = 0; n < 5; n++){
lhsY[n][m][BB][j][i][k] = lhsY[n][m][BB][j][i][k] - lhsY[n][0][AA][j][i][k]*lhsY[0][m][CC][j-1][i][k]
- lhsY[n][1][AA][j][i][k]*lhsY[1][m][CC][j-1][i][k]
- lhsY[n][2][AA][j][i][k]*lhsY[2][m][CC][j-1][i][k]
- lhsY[n][3][AA][j][i][k]*lhsY[3][m][CC][j-1][i][k]
- lhsY[n][4][AA][j][i][k]*lhsY[4][m][CC][j-1][i][k];
}
}
*/
lhsY[0][0][BB][j][i][k] = lhsY[0][0][BB][j][i][k] - lhsY[0][0][AA][j][i][k]*lhsY[0][0][CC][j-1][i][k]
- lhsY[0][1][AA][j][i][k]*lhsY[1][0][CC][j-1][i][k]
- lhsY[0][2][AA][j][i][k]*lhsY[2][0][CC][j-1][i][k]
- lhsY[0][3][AA][j][i][k]*lhsY[3][0][CC][j-1][i][k]
- lhsY[0][4][AA][j][i][k]*lhsY[4][0][CC][j-1][i][k];
lhsY[1][0][BB][j][i][k] = lhsY[1][0][BB][j][i][k] - lhsY[1][0][AA][j][i][k]*lhsY[0][0][CC][j-1][i][k]
- lhsY[1][1][AA][j][i][k]*lhsY[1][0][CC][j-1][i][k]
- lhsY[1][2][AA][j][i][k]*lhsY[2][0][CC][j-1][i][k]
- lhsY[1][3][AA][j][i][k]*lhsY[3][0][CC][j-1][i][k]
- lhsY[1][4][AA][j][i][k]*lhsY[4][0][CC][j-1][i][k];
lhsY[2][0][BB][j][i][k] = lhsY[2][0][BB][j][i][k] - lhsY[2][0][AA][j][i][k]*lhsY[0][0][CC][j-1][i][k]
- lhsY[2][1][AA][j][i][k]*lhsY[1][0][CC][j-1][i][k]
- lhsY[2][2][AA][j][i][k]*lhsY[2][0][CC][j-1][i][k]
- lhsY[2][3][AA][j][i][k]*lhsY[3][0][CC][j-1][i][k]
- lhsY[2][4][AA][j][i][k]*lhsY[4][0][CC][j-1][i][k];
lhsY[3][0][BB][j][i][k] = lhsY[3][0][BB][j][i][k] - lhsY[3][0][AA][j][i][k]*lhsY[0][0][CC][j-1][i][k]
- lhsY[3][1][AA][j][i][k]*lhsY[1][0][CC][j-1][i][k]
- lhsY[3][2][AA][j][i][k]*lhsY[2][0][CC][j-1][i][k]
- lhsY[3][3][AA][j][i][k]*lhsY[3][0][CC][j-1][i][k]
- lhsY[3][4][AA][j][i][k]*lhsY[4][0][CC][j-1][i][k];
lhsY[4][0][BB][j][i][k] = lhsY[4][0][BB][j][i][k] - lhsY[4][0][AA][j][i][k]*lhsY[0][0][CC][j-1][i][k]
- lhsY[4][1][AA][j][i][k]*lhsY[1][0][CC][j-1][i][k]
- lhsY[4][2][AA][j][i][k]*lhsY[2][0][CC][j-1][i][k]
- lhsY[4][3][AA][j][i][k]*lhsY[3][0][CC][j-1][i][k]
- lhsY[4][4][AA][j][i][k]*lhsY[4][0][CC][j-1][i][k];
lhsY[0][1][BB][j][i][k] = lhsY[0][1][BB][j][i][k] - lhsY[0][0][AA][j][i][k]*lhsY[0][1][CC][j-1][i][k]
- lhsY[0][1][AA][j][i][k]*lhsY[1][1][CC][j-1][i][k]
- lhsY[0][2][AA][j][i][k]*lhsY[2][1][CC][j-1][i][k]
- lhsY[0][3][AA][j][i][k]*lhsY[3][1][CC][j-1][i][k]
- lhsY[0][4][AA][j][i][k]*lhsY[4][1][CC][j-1][i][k];
lhsY[1][1][BB][j][i][k] = lhsY[1][1][BB][j][i][k] - lhsY[1][0][AA][j][i][k]*lhsY[0][1][CC][j-1][i][k]
- lhsY[1][1][AA][j][i][k]*lhsY[1][1][CC][j-1][i][k]
- lhsY[1][2][AA][j][i][k]*lhsY[2][1][CC][j-1][i][k]
- lhsY[1][3][AA][j][i][k]*lhsY[3][1][CC][j-1][i][k]
- lhsY[1][4][AA][j][i][k]*lhsY[4][1][CC][j-1][i][k];
lhsY[2][1][BB][j][i][k] = lhsY[2][1][BB][j][i][k] - lhsY[2][0][AA][j][i][k]*lhsY[0][1][CC][j-1][i][k]
- lhsY[2][1][AA][j][i][k]*lhsY[1][1][CC][j-1][i][k]
- lhsY[2][2][AA][j][i][k]*lhsY[2][1][CC][j-1][i][k]
- lhsY[2][3][AA][j][i][k]*lhsY[3][1][CC][j-1][i][k]
- lhsY[2][4][AA][j][i][k]*lhsY[4][1][CC][j-1][i][k];
lhsY[3][1][BB][j][i][k] = lhsY[3][1][BB][j][i][k] - lhsY[3][0][AA][j][i][k]*lhsY[0][1][CC][j-1][i][k]
- lhsY[3][1][AA][j][i][k]*lhsY[1][1][CC][j-1][i][k]
- lhsY[3][2][AA][j][i][k]*lhsY[2][1][CC][j-1][i][k]
- lhsY[3][3][AA][j][i][k]*lhsY[3][1][CC][j-1][i][k]
- lhsY[3][4][AA][j][i][k]*lhsY[4][1][CC][j-1][i][k];
lhsY[4][1][BB][j][i][k] = lhsY[4][1][BB][j][i][k] - lhsY[4][0][AA][j][i][k]*lhsY[0][1][CC][j-1][i][k]
- lhsY[4][1][AA][j][i][k]*lhsY[1][1][CC][j-1][i][k]
- lhsY[4][2][AA][j][i][k]*lhsY[2][1][CC][j-1][i][k]
- lhsY[4][3][AA][j][i][k]*lhsY[3][1][CC][j-1][i][k]
- lhsY[4][4][AA][j][i][k]*lhsY[4][1][CC][j-1][i][k];
lhsY[0][2][BB][j][i][k] = lhsY[0][2][BB][j][i][k] - lhsY[0][0][AA][j][i][k]*lhsY[0][2][CC][j-1][i][k]
- lhsY[0][1][AA][j][i][k]*lhsY[1][2][CC][j-1][i][k]
- lhsY[0][2][AA][j][i][k]*lhsY[2][2][CC][j-1][i][k]
- lhsY[0][3][AA][j][i][k]*lhsY[3][2][CC][j-1][i][k]
- lhsY[0][4][AA][j][i][k]*lhsY[4][2][CC][j-1][i][k];
lhsY[1][2][BB][j][i][k] = lhsY[1][2][BB][j][i][k] - lhsY[1][0][AA][j][i][k]*lhsY[0][2][CC][j-1][i][k]
- lhsY[1][1][AA][j][i][k]*lhsY[1][2][CC][j-1][i][k]
- lhsY[1][2][AA][j][i][k]*lhsY[2][2][CC][j-1][i][k]
- lhsY[1][3][AA][j][i][k]*lhsY[3][2][CC][j-1][i][k]
- lhsY[1][4][AA][j][i][k]*lhsY[4][2][CC][j-1][i][k];
lhsY[2][2][BB][j][i][k] = lhsY[2][2][BB][j][i][k] - lhsY[2][0][AA][j][i][k]*lhsY[0][2][CC][j-1][i][k]
- lhsY[2][1][AA][j][i][k]*lhsY[1][2][CC][j-1][i][k]
- lhsY[2][2][AA][j][i][k]*lhsY[2][2][CC][j-1][i][k]
- lhsY[2][3][AA][j][i][k]*lhsY[3][2][CC][j-1][i][k]
- lhsY[2][4][AA][j][i][k]*lhsY[4][2][CC][j-1][i][k];
lhsY[3][2][BB][j][i][k] = lhsY[3][2][BB][j][i][k] - lhsY[3][0][AA][j][i][k]*lhsY[0][2][CC][j-1][i][k]
- lhsY[3][1][AA][j][i][k]*lhsY[1][2][CC][j-1][i][k]
- lhsY[3][2][AA][j][i][k]*lhsY[2][2][CC][j-1][i][k]
- lhsY[3][3][AA][j][i][k]*lhsY[3][2][CC][j-1][i][k]
- lhsY[3][4][AA][j][i][k]*lhsY[4][2][CC][j-1][i][k];
lhsY[4][2][BB][j][i][k] = lhsY[4][2][BB][j][i][k] - lhsY[4][0][AA][j][i][k]*lhsY[0][2][CC][j-1][i][k]
- lhsY[4][1][AA][j][i][k]*lhsY[1][2][CC][j-1][i][k]
- lhsY[4][2][AA][j][i][k]*lhsY[2][2][CC][j-1][i][k]
- lhsY[4][3][AA][j][i][k]*lhsY[3][2][CC][j-1][i][k]
- lhsY[4][4][AA][j][i][k]*lhsY[4][2][CC][j-1][i][k];
lhsY[0][3][BB][j][i][k] = lhsY[0][3][BB][j][i][k] - lhsY[0][0][AA][j][i][k]*lhsY[0][3][CC][j-1][i][k]
- lhsY[0][1][AA][j][i][k]*lhsY[1][3][CC][j-1][i][k]
- lhsY[0][2][AA][j][i][k]*lhsY[2][3][CC][j-1][i][k]
- lhsY[0][3][AA][j][i][k]*lhsY[3][3][CC][j-1][i][k]
- lhsY[0][4][AA][j][i][k]*lhsY[4][3][CC][j-1][i][k];
lhsY[1][3][BB][j][i][k] = lhsY[1][3][BB][j][i][k] - lhsY[1][0][AA][j][i][k]*lhsY[0][3][CC][j-1][i][k]
- lhsY[1][1][AA][j][i][k]*lhsY[1][3][CC][j-1][i][k]
- lhsY[1][2][AA][j][i][k]*lhsY[2][3][CC][j-1][i][k]
- lhsY[1][3][AA][j][i][k]*lhsY[3][3][CC][j-1][i][k]
- lhsY[1][4][AA][j][i][k]*lhsY[4][3][CC][j-1][i][k];
lhsY[2][3][BB][j][i][k] = lhsY[2][3][BB][j][i][k] - lhsY[2][0][AA][j][i][k]*lhsY[0][3][CC][j-1][i][k]
- lhsY[2][1][AA][j][i][k]*lhsY[1][3][CC][j-1][i][k]
- lhsY[2][2][AA][j][i][k]*lhsY[2][3][CC][j-1][i][k]
- lhsY[2][3][AA][j][i][k]*lhsY[3][3][CC][j-1][i][k]
- lhsY[2][4][AA][j][i][k]*lhsY[4][3][CC][j-1][i][k];
lhsY[3][3][BB][j][i][k] = lhsY[3][3][BB][j][i][k] - lhsY[3][0][AA][j][i][k]*lhsY[0][3][CC][j-1][i][k]
- lhsY[3][1][AA][j][i][k]*lhsY[1][3][CC][j-1][i][k]
- lhsY[3][2][AA][j][i][k]*lhsY[2][3][CC][j-1][i][k]
- lhsY[3][3][AA][j][i][k]*lhsY[3][3][CC][j-1][i][k]
- lhsY[3][4][AA][j][i][k]*lhsY[4][3][CC][j-1][i][k];
lhsY[4][3][BB][j][i][k] = lhsY[4][3][BB][j][i][k] - lhsY[4][0][AA][j][i][k]*lhsY[0][3][CC][j-1][i][k]
- lhsY[4][1][AA][j][i][k]*lhsY[1][3][CC][j-1][i][k]
- lhsY[4][2][AA][j][i][k]*lhsY[2][3][CC][j-1][i][k]
- lhsY[4][3][AA][j][i][k]*lhsY[3][3][CC][j-1][i][k]
- lhsY[4][4][AA][j][i][k]*lhsY[4][3][CC][j-1][i][k];
lhsY[0][4][BB][j][i][k] = lhsY[0][4][BB][j][i][k] - lhsY[0][0][AA][j][i][k]*lhsY[0][4][CC][j-1][i][k]
- lhsY[0][1][AA][j][i][k]*lhsY[1][4][CC][j-1][i][k]
- lhsY[0][2][AA][j][i][k]*lhsY[2][4][CC][j-1][i][k]
- lhsY[0][3][AA][j][i][k]*lhsY[3][4][CC][j-1][i][k]
- lhsY[0][4][AA][j][i][k]*lhsY[4][4][CC][j-1][i][k];
lhsY[1][4][BB][j][i][k] = lhsY[1][4][BB][j][i][k] - lhsY[1][0][AA][j][i][k]*lhsY[0][4][CC][j-1][i][k]
- lhsY[1][1][AA][j][i][k]*lhsY[1][4][CC][j-1][i][k]
- lhsY[1][2][AA][j][i][k]*lhsY[2][4][CC][j-1][i][k]
- lhsY[1][3][AA][j][i][k]*lhsY[3][4][CC][j-1][i][k]
- lhsY[1][4][AA][j][i][k]*lhsY[4][4][CC][j-1][i][k];
lhsY[2][4][BB][j][i][k] = lhsY[2][4][BB][j][i][k] - lhsY[2][0][AA][j][i][k]*lhsY[0][4][CC][j-1][i][k]
- lhsY[2][1][AA][j][i][k]*lhsY[1][4][CC][j-1][i][k]
- lhsY[2][2][AA][j][i][k]*lhsY[2][4][CC][j-1][i][k]
- lhsY[2][3][AA][j][i][k]*lhsY[3][4][CC][j-1][i][k]
- lhsY[2][4][AA][j][i][k]*lhsY[4][4][CC][j-1][i][k];
lhsY[3][4][BB][j][i][k] = lhsY[3][4][BB][j][i][k] - lhsY[3][0][AA][j][i][k]*lhsY[0][4][CC][j-1][i][k]
- lhsY[3][1][AA][j][i][k]*lhsY[1][4][CC][j-1][i][k]
- lhsY[3][2][AA][j][i][k]*lhsY[2][4][CC][j-1][i][k]
- lhsY[3][3][AA][j][i][k]*lhsY[3][4][CC][j-1][i][k]
- lhsY[3][4][AA][j][i][k]*lhsY[4][4][CC][j-1][i][k];
lhsY[4][4][BB][j][i][k] = lhsY[4][4][BB][j][i][k] - lhsY[4][0][AA][j][i][k]*lhsY[0][4][CC][j-1][i][k]
- lhsY[4][1][AA][j][i][k]*lhsY[1][4][CC][j-1][i][k]
- lhsY[4][2][AA][j][i][k]*lhsY[2][4][CC][j-1][i][k]
- lhsY[4][3][AA][j][i][k]*lhsY[3][4][CC][j-1][i][k]
- lhsY[4][4][AA][j][i][k]*lhsY[4][4][CC][j-1][i][k];
//-------------------------------------------------------------------
// multiply c[k][j][i] by b_inverse and copy back to c
// multiply rhs[k][0][i] by b_inverse[k][0][i] and copy to rhs
//-------------------------------------------------------------------
//binvcrhs( lhsY[j][i][BB], lhsY[k][j][i][k][CC], rhs[k][j][i] );
/*
for(m = 0; m < 5; m++){
pivot = 1.00/lhsY[m][m][BB][j][i][k];
for(n = m+1; n < 5; n++){
lhsY[m][n][BB][j][i][k] = lhsY[m][n][BB][j][i][k]*pivot;
}
lhsY[m][0][CC][j][i][k] = lhsY[m][0][CC][j][i][k]*pivot;
lhsY[m][1][CC][j][i][k] = lhsY[m][1][CC][j][i][k]*pivot;
lhsY[m][2][CC][j][i][k] = lhsY[m][2][CC][j][i][k]*pivot;
lhsY[m][3][CC][j][i][k] = lhsY[m][3][CC][j][i][k]*pivot;
lhsY[m][4][CC][j][i][k] = lhsY[m][4][CC][j][i][k]*pivot;
rhs[k][j][i][m] = rhs[k][j][i][m]*pivot;
for(n = 0; n < 5; n++){
if(n != m){
coeff = lhsY[n][m][BB][j][i][k];
for(z = m+1; z < 5; z++){
lhsY[n][z][BB][j][i][k] = lhsY[n][z][BB][j][i][k] - coeff*lhsY[m][z][BB][j][i][k];
}
lhsY[n][0][CC][j][i][k] = lhsY[n][0][CC][j][i][k] - coeff*lhsY[m][0][CC][j][i][k];
lhsY[n][1][CC][j][i][k] = lhsY[n][1][CC][j][i][k] - coeff*lhsY[m][1][CC][j][i][k];
lhsY[n][2][CC][j][i][k] = lhsY[n][2][CC][j][i][k] - coeff*lhsY[m][2][CC][j][i][k];
lhsY[n][3][CC][j][i][k] = lhsY[n][3][CC][j][i][k] - coeff*lhsY[m][3][CC][j][i][k];
lhsY[n][4][CC][j][i][k] = lhsY[n][4][CC][j][i][k] - coeff*lhsY[m][4][CC][j][i][k];
rhs[k][j][i][n] = rhs[k][j][i][n] - coeff*rhs[k][j][i][m];
}
}
}
*/
pivot = 1.00/lhsY[0][0][BB][j][i][k];
lhsY[0][1][BB][j][i][k] = lhsY[0][1][BB][j][i][k]*pivot;
lhsY[0][2][BB][j][i][k] = lhsY[0][2][BB][j][i][k]*pivot;
lhsY[0][3][BB][j][i][k] = lhsY[0][3][BB][j][i][k]*pivot;
lhsY[0][4][BB][j][i][k] = lhsY[0][4][BB][j][i][k]*pivot;
lhsY[0][0][CC][j][i][k] = lhsY[0][0][CC][j][i][k]*pivot;
lhsY[0][1][CC][j][i][k] = lhsY[0][1][CC][j][i][k]*pivot;
lhsY[0][2][CC][j][i][k] = lhsY[0][2][CC][j][i][k]*pivot;
lhsY[0][3][CC][j][i][k] = lhsY[0][3][CC][j][i][k]*pivot;
lhsY[0][4][CC][j][i][k] = lhsY[0][4][CC][j][i][k]*pivot;
rhs[k][j][i][0] = rhs[k][j][i][0] *pivot;
coeff = lhsY[1][0][BB][j][i][k];
lhsY[1][1][BB][j][i][k]= lhsY[1][1][BB][j][i][k] - coeff*lhsY[0][1][BB][j][i][k];
lhsY[1][2][BB][j][i][k]= lhsY[1][2][BB][j][i][k] - coeff*lhsY[0][2][BB][j][i][k];
lhsY[1][3][BB][j][i][k]= lhsY[1][3][BB][j][i][k] - coeff*lhsY[0][3][BB][j][i][k];
lhsY[1][4][BB][j][i][k]= lhsY[1][4][BB][j][i][k] - coeff*lhsY[0][4][BB][j][i][k];
lhsY[1][0][CC][j][i][k] = lhsY[1][0][CC][j][i][k] - coeff*lhsY[0][0][CC][j][i][k];
lhsY[1][1][CC][j][i][k] = lhsY[1][1][CC][j][i][k] - coeff*lhsY[0][1][CC][j][i][k];
lhsY[1][2][CC][j][i][k] = lhsY[1][2][CC][j][i][k] - coeff*lhsY[0][2][CC][j][i][k];
lhsY[1][3][CC][j][i][k] = lhsY[1][3][CC][j][i][k] - coeff*lhsY[0][3][CC][j][i][k];
lhsY[1][4][CC][j][i][k] = lhsY[1][4][CC][j][i][k] - coeff*lhsY[0][4][CC][j][i][k];
rhs[k][j][i][1] = rhs[k][j][i][1] - coeff*rhs[k][j][i][0];
coeff = lhsY[2][0][BB][j][i][k];
lhsY[2][1][BB][j][i][k]= lhsY[2][1][BB][j][i][k] - coeff*lhsY[0][1][BB][j][i][k];
lhsY[2][2][BB][j][i][k]= lhsY[2][2][BB][j][i][k] - coeff*lhsY[0][2][BB][j][i][k];
lhsY[2][3][BB][j][i][k]= lhsY[2][3][BB][j][i][k] - coeff*lhsY[0][3][BB][j][i][k];
lhsY[2][4][BB][j][i][k]= lhsY[2][4][BB][j][i][k] - coeff*lhsY[0][4][BB][j][i][k];
lhsY[2][0][CC][j][i][k] = lhsY[2][0][CC][j][i][k] - coeff*lhsY[0][0][CC][j][i][k];
lhsY[2][1][CC][j][i][k] = lhsY[2][1][CC][j][i][k] - coeff*lhsY[0][1][CC][j][i][k];
lhsY[2][2][CC][j][i][k] = lhsY[2][2][CC][j][i][k] - coeff*lhsY[0][2][CC][j][i][k];
lhsY[2][3][CC][j][i][k] = lhsY[2][3][CC][j][i][k] - coeff*lhsY[0][3][CC][j][i][k];
lhsY[2][4][CC][j][i][k] = lhsY[2][4][CC][j][i][k] - coeff*lhsY[0][4][CC][j][i][k];
rhs[k][j][i][2] = rhs[k][j][i][2] - coeff*rhs[k][j][i][0];
coeff = lhsY[3][0][BB][j][i][k];
lhsY[3][1][BB][j][i][k]= lhsY[3][1][BB][j][i][k] - coeff*lhsY[0][1][BB][j][i][k];
lhsY[3][2][BB][j][i][k]= lhsY[3][2][BB][j][i][k] - coeff*lhsY[0][2][BB][j][i][k];
lhsY[3][3][BB][j][i][k]= lhsY[3][3][BB][j][i][k] - coeff*lhsY[0][3][BB][j][i][k];
lhsY[3][4][BB][j][i][k]= lhsY[3][4][BB][j][i][k] - coeff*lhsY[0][4][BB][j][i][k];
lhsY[3][0][CC][j][i][k] = lhsY[3][0][CC][j][i][k] - coeff*lhsY[0][0][CC][j][i][k];
lhsY[3][1][CC][j][i][k] = lhsY[3][1][CC][j][i][k] - coeff*lhsY[0][1][CC][j][i][k];
lhsY[3][2][CC][j][i][k] = lhsY[3][2][CC][j][i][k] - coeff*lhsY[0][2][CC][j][i][k];
lhsY[3][3][CC][j][i][k] = lhsY[3][3][CC][j][i][k] - coeff*lhsY[0][3][CC][j][i][k];
lhsY[3][4][CC][j][i][k] = lhsY[3][4][CC][j][i][k] - coeff*lhsY[0][4][CC][j][i][k];
rhs[k][j][i][3] = rhs[k][j][i][3] - coeff*rhs[k][j][i][0];
coeff = lhsY[4][0][BB][j][i][k];
lhsY[4][1][BB][j][i][k]= lhsY[4][1][BB][j][i][k] - coeff*lhsY[0][1][BB][j][i][k];
lhsY[4][2][BB][j][i][k]= lhsY[4][2][BB][j][i][k] - coeff*lhsY[0][2][BB][j][i][k];
lhsY[4][3][BB][j][i][k]= lhsY[4][3][BB][j][i][k] - coeff*lhsY[0][3][BB][j][i][k];
lhsY[4][4][BB][j][i][k]= lhsY[4][4][BB][j][i][k] - coeff*lhsY[0][4][BB][j][i][k];
lhsY[4][0][CC][j][i][k] = lhsY[4][0][CC][j][i][k] - coeff*lhsY[0][0][CC][j][i][k];
lhsY[4][1][CC][j][i][k] = lhsY[4][1][CC][j][i][k] - coeff*lhsY[0][1][CC][j][i][k];
lhsY[4][2][CC][j][i][k] = lhsY[4][2][CC][j][i][k] - coeff*lhsY[0][2][CC][j][i][k];
lhsY[4][3][CC][j][i][k] = lhsY[4][3][CC][j][i][k] - coeff*lhsY[0][3][CC][j][i][k];
lhsY[4][4][CC][j][i][k] = lhsY[4][4][CC][j][i][k] - coeff*lhsY[0][4][CC][j][i][k];
rhs[k][j][i][4] = rhs[k][j][i][4] - coeff*rhs[k][j][i][0];
pivot = 1.00/lhsY[1][1][BB][j][i][k];
lhsY[1][2][BB][j][i][k] = lhsY[1][2][BB][j][i][k]*pivot;
lhsY[1][3][BB][j][i][k] = lhsY[1][3][BB][j][i][k]*pivot;
lhsY[1][4][BB][j][i][k] = lhsY[1][4][BB][j][i][k]*pivot;
lhsY[1][0][CC][j][i][k] = lhsY[1][0][CC][j][i][k]*pivot;
lhsY[1][1][CC][j][i][k] = lhsY[1][1][CC][j][i][k]*pivot;
lhsY[1][2][CC][j][i][k] = lhsY[1][2][CC][j][i][k]*pivot;
lhsY[1][3][CC][j][i][k] = lhsY[1][3][CC][j][i][k]*pivot;
lhsY[1][4][CC][j][i][k] = lhsY[1][4][CC][j][i][k]*pivot;
rhs[k][j][i][1] = rhs[k][j][i][1] *pivot;
coeff = lhsY[0][1][BB][j][i][k];
lhsY[0][2][BB][j][i][k]= lhsY[0][2][BB][j][i][k] - coeff*lhsY[1][2][BB][j][i][k];
lhsY[0][3][BB][j][i][k]= lhsY[0][3][BB][j][i][k] - coeff*lhsY[1][3][BB][j][i][k];
lhsY[0][4][BB][j][i][k]= lhsY[0][4][BB][j][i][k] - coeff*lhsY[1][4][BB][j][i][k];
lhsY[0][0][CC][j][i][k] = lhsY[0][0][CC][j][i][k] - coeff*lhsY[1][0][CC][j][i][k];
lhsY[0][1][CC][j][i][k] = lhsY[0][1][CC][j][i][k] - coeff*lhsY[1][1][CC][j][i][k];
lhsY[0][2][CC][j][i][k] = lhsY[0][2][CC][j][i][k] - coeff*lhsY[1][2][CC][j][i][k];
lhsY[0][3][CC][j][i][k] = lhsY[0][3][CC][j][i][k] - coeff*lhsY[1][3][CC][j][i][k];
lhsY[0][4][CC][j][i][k] = lhsY[0][4][CC][j][i][k] - coeff*lhsY[1][4][CC][j][i][k];
rhs[k][j][i][0] = rhs[k][j][i][0] - coeff*rhs[k][j][i][1];
coeff = lhsY[2][1][BB][j][i][k];
lhsY[2][2][BB][j][i][k]= lhsY[2][2][BB][j][i][k] - coeff*lhsY[1][2][BB][j][i][k];
lhsY[2][3][BB][j][i][k]= lhsY[2][3][BB][j][i][k] - coeff*lhsY[1][3][BB][j][i][k];
lhsY[2][4][BB][j][i][k]= lhsY[2][4][BB][j][i][k] - coeff*lhsY[1][4][BB][j][i][k];
lhsY[2][0][CC][j][i][k] = lhsY[2][0][CC][j][i][k] - coeff*lhsY[1][0][CC][j][i][k];
lhsY[2][1][CC][j][i][k] = lhsY[2][1][CC][j][i][k] - coeff*lhsY[1][1][CC][j][i][k];
lhsY[2][2][CC][j][i][k] = lhsY[2][2][CC][j][i][k] - coeff*lhsY[1][2][CC][j][i][k];
lhsY[2][3][CC][j][i][k] = lhsY[2][3][CC][j][i][k] - coeff*lhsY[1][3][CC][j][i][k];
lhsY[2][4][CC][j][i][k] = lhsY[2][4][CC][j][i][k] - coeff*lhsY[1][4][CC][j][i][k];
rhs[k][j][i][2] = rhs[k][j][i][2] - coeff*rhs[k][j][i][1];
coeff = lhsY[3][1][BB][j][i][k];
lhsY[3][2][BB][j][i][k]= lhsY[3][2][BB][j][i][k] - coeff*lhsY[1][2][BB][j][i][k];
lhsY[3][3][BB][j][i][k]= lhsY[3][3][BB][j][i][k] - coeff*lhsY[1][3][BB][j][i][k];
lhsY[3][4][BB][j][i][k]= lhsY[3][4][BB][j][i][k] - coeff*lhsY[1][4][BB][j][i][k];
lhsY[3][0][CC][j][i][k] = lhsY[3][0][CC][j][i][k] - coeff*lhsY[1][0][CC][j][i][k];
lhsY[3][1][CC][j][i][k] = lhsY[3][1][CC][j][i][k] - coeff*lhsY[1][1][CC][j][i][k];
lhsY[3][2][CC][j][i][k] = lhsY[3][2][CC][j][i][k] - coeff*lhsY[1][2][CC][j][i][k];
lhsY[3][3][CC][j][i][k] = lhsY[3][3][CC][j][i][k] - coeff*lhsY[1][3][CC][j][i][k];
lhsY[3][4][CC][j][i][k] = lhsY[3][4][CC][j][i][k] - coeff*lhsY[1][4][CC][j][i][k];
rhs[k][j][i][3] = rhs[k][j][i][3] - coeff*rhs[k][j][i][1];
coeff = lhsY[4][1][BB][j][i][k];
lhsY[4][2][BB][j][i][k]= lhsY[4][2][BB][j][i][k] - coeff*lhsY[1][2][BB][j][i][k];
lhsY[4][3][BB][j][i][k]= lhsY[4][3][BB][j][i][k] - coeff*lhsY[1][3][BB][j][i][k];
lhsY[4][4][BB][j][i][k]= lhsY[4][4][BB][j][i][k] - coeff*lhsY[1][4][BB][j][i][k];
lhsY[4][0][CC][j][i][k] = lhsY[4][0][CC][j][i][k] - coeff*lhsY[1][0][CC][j][i][k];
lhsY[4][1][CC][j][i][k] = lhsY[4][1][CC][j][i][k] - coeff*lhsY[1][1][CC][j][i][k];
lhsY[4][2][CC][j][i][k] = lhsY[4][2][CC][j][i][k] - coeff*lhsY[1][2][CC][j][i][k];
lhsY[4][3][CC][j][i][k] = lhsY[4][3][CC][j][i][k] - coeff*lhsY[1][3][CC][j][i][k];
lhsY[4][4][CC][j][i][k] = lhsY[4][4][CC][j][i][k] - coeff*lhsY[1][4][CC][j][i][k];
rhs[k][j][i][4] = rhs[k][j][i][4] - coeff*rhs[k][j][i][1];
pivot = 1.00/lhsY[2][2][BB][j][i][k];
lhsY[2][3][BB][j][i][k] = lhsY[2][3][BB][j][i][k]*pivot;
lhsY[2][4][BB][j][i][k] = lhsY[2][4][BB][j][i][k]*pivot;
lhsY[2][0][CC][j][i][k] = lhsY[2][0][CC][j][i][k]*pivot;
lhsY[2][1][CC][j][i][k] = lhsY[2][1][CC][j][i][k]*pivot;
lhsY[2][2][CC][j][i][k] = lhsY[2][2][CC][j][i][k]*pivot;
lhsY[2][3][CC][j][i][k] = lhsY[2][3][CC][j][i][k]*pivot;
lhsY[2][4][CC][j][i][k] = lhsY[2][4][CC][j][i][k]*pivot;
rhs[k][j][i][2] = rhs[k][j][i][2] *pivot;
coeff = lhsY[0][2][BB][j][i][k];
lhsY[0][3][BB][j][i][k]= lhsY[0][3][BB][j][i][k] - coeff*lhsY[2][3][BB][j][i][k];
lhsY[0][4][BB][j][i][k]= lhsY[0][4][BB][j][i][k] - coeff*lhsY[2][4][BB][j][i][k];
lhsY[0][0][CC][j][i][k] = lhsY[0][0][CC][j][i][k] - coeff*lhsY[2][0][CC][j][i][k];
lhsY[0][1][CC][j][i][k] = lhsY[0][1][CC][j][i][k] - coeff*lhsY[2][1][CC][j][i][k];
lhsY[0][2][CC][j][i][k] = lhsY[0][2][CC][j][i][k] - coeff*lhsY[2][2][CC][j][i][k];
lhsY[0][3][CC][j][i][k] = lhsY[0][3][CC][j][i][k] - coeff*lhsY[2][3][CC][j][i][k];
lhsY[0][4][CC][j][i][k] = lhsY[0][4][CC][j][i][k] - coeff*lhsY[2][4][CC][j][i][k];
rhs[k][j][i][0] = rhs[k][j][i][0] - coeff*rhs[k][j][i][2];
coeff = lhsY[1][2][BB][j][i][k];
lhsY[1][3][BB][j][i][k]= lhsY[1][3][BB][j][i][k] - coeff*lhsY[2][3][BB][j][i][k];
lhsY[1][4][BB][j][i][k]= lhsY[1][4][BB][j][i][k] - coeff*lhsY[2][4][BB][j][i][k];
lhsY[1][0][CC][j][i][k] = lhsY[1][0][CC][j][i][k] - coeff*lhsY[2][0][CC][j][i][k];
lhsY[1][1][CC][j][i][k] = lhsY[1][1][CC][j][i][k] - coeff*lhsY[2][1][CC][j][i][k];
lhsY[1][2][CC][j][i][k] = lhsY[1][2][CC][j][i][k] - coeff*lhsY[2][2][CC][j][i][k];
lhsY[1][3][CC][j][i][k] = lhsY[1][3][CC][j][i][k] - coeff*lhsY[2][3][CC][j][i][k];
lhsY[1][4][CC][j][i][k] = lhsY[1][4][CC][j][i][k] - coeff*lhsY[2][4][CC][j][i][k];
rhs[k][j][i][1] = rhs[k][j][i][1] - coeff*rhs[k][j][i][2];
coeff = lhsY[3][2][BB][j][i][k];
lhsY[3][3][BB][j][i][k]= lhsY[3][3][BB][j][i][k] - coeff*lhsY[2][3][BB][j][i][k];
lhsY[3][4][BB][j][i][k]= lhsY[3][4][BB][j][i][k] - coeff*lhsY[2][4][BB][j][i][k];
lhsY[3][0][CC][j][i][k] = lhsY[3][0][CC][j][i][k] - coeff*lhsY[2][0][CC][j][i][k];
lhsY[3][1][CC][j][i][k] = lhsY[3][1][CC][j][i][k] - coeff*lhsY[2][1][CC][j][i][k];
lhsY[3][2][CC][j][i][k] = lhsY[3][2][CC][j][i][k] - coeff*lhsY[2][2][CC][j][i][k];
lhsY[3][3][CC][j][i][k] = lhsY[3][3][CC][j][i][k] - coeff*lhsY[2][3][CC][j][i][k];
lhsY[3][4][CC][j][i][k] = lhsY[3][4][CC][j][i][k] - coeff*lhsY[2][4][CC][j][i][k];
rhs[k][j][i][3] = rhs[k][j][i][3] - coeff*rhs[k][j][i][2];
coeff = lhsY[4][2][BB][j][i][k];
lhsY[4][3][BB][j][i][k]= lhsY[4][3][BB][j][i][k] - coeff*lhsY[2][3][BB][j][i][k];
lhsY[4][4][BB][j][i][k]= lhsY[4][4][BB][j][i][k] - coeff*lhsY[2][4][BB][j][i][k];
lhsY[4][0][CC][j][i][k] = lhsY[4][0][CC][j][i][k] - coeff*lhsY[2][0][CC][j][i][k];
lhsY[4][1][CC][j][i][k] = lhsY[4][1][CC][j][i][k] - coeff*lhsY[2][1][CC][j][i][k];
lhsY[4][2][CC][j][i][k] = lhsY[4][2][CC][j][i][k] - coeff*lhsY[2][2][CC][j][i][k];
lhsY[4][3][CC][j][i][k] = lhsY[4][3][CC][j][i][k] - coeff*lhsY[2][3][CC][j][i][k];
lhsY[4][4][CC][j][i][k] = lhsY[4][4][CC][j][i][k] - coeff*lhsY[2][4][CC][j][i][k];
rhs[k][j][i][4] = rhs[k][j][i][4] - coeff*rhs[k][j][i][2];
pivot = 1.00/lhsY[3][3][BB][j][i][k];
lhsY[3][4][BB][j][i][k] = lhsY[3][4][BB][j][i][k]*pivot;
lhsY[3][0][CC][j][i][k] = lhsY[3][0][CC][j][i][k]*pivot;
lhsY[3][1][CC][j][i][k] = lhsY[3][1][CC][j][i][k]*pivot;
lhsY[3][2][CC][j][i][k] = lhsY[3][2][CC][j][i][k]*pivot;
lhsY[3][3][CC][j][i][k] = lhsY[3][3][CC][j][i][k]*pivot;
lhsY[3][4][CC][j][i][k] = lhsY[3][4][CC][j][i][k]*pivot;
rhs[k][j][i][3] = rhs[k][j][i][3] *pivot;
coeff = lhsY[0][3][BB][j][i][k];
lhsY[0][4][BB][j][i][k]= lhsY[0][4][BB][j][i][k] - coeff*lhsY[3][4][BB][j][i][k];
lhsY[0][0][CC][j][i][k] = lhsY[0][0][CC][j][i][k] - coeff*lhsY[3][0][CC][j][i][k];
lhsY[0][1][CC][j][i][k] = lhsY[0][1][CC][j][i][k] - coeff*lhsY[3][1][CC][j][i][k];
lhsY[0][2][CC][j][i][k] = lhsY[0][2][CC][j][i][k] - coeff*lhsY[3][2][CC][j][i][k];
lhsY[0][3][CC][j][i][k] = lhsY[0][3][CC][j][i][k] - coeff*lhsY[3][3][CC][j][i][k];
lhsY[0][4][CC][j][i][k] = lhsY[0][4][CC][j][i][k] - coeff*lhsY[3][4][CC][j][i][k];
rhs[k][j][i][0] = rhs[k][j][i][0] - coeff*rhs[k][j][i][3];
coeff = lhsY[1][3][BB][j][i][k];
lhsY[1][4][BB][j][i][k]= lhsY[1][4][BB][j][i][k] - coeff*lhsY[3][4][BB][j][i][k];
lhsY[1][0][CC][j][i][k] = lhsY[1][0][CC][j][i][k] - coeff*lhsY[3][0][CC][j][i][k];
lhsY[1][1][CC][j][i][k] = lhsY[1][1][CC][j][i][k] - coeff*lhsY[3][1][CC][j][i][k];
lhsY[1][2][CC][j][i][k] = lhsY[1][2][CC][j][i][k] - coeff*lhsY[3][2][CC][j][i][k];
lhsY[1][3][CC][j][i][k] = lhsY[1][3][CC][j][i][k] - coeff*lhsY[3][3][CC][j][i][k];
lhsY[1][4][CC][j][i][k] = lhsY[1][4][CC][j][i][k] - coeff*lhsY[3][4][CC][j][i][k];
rhs[k][j][i][1] = rhs[k][j][i][1] - coeff*rhs[k][j][i][3];
coeff = lhsY[2][3][BB][j][i][k];
lhsY[2][4][BB][j][i][k]= lhsY[2][4][BB][j][i][k] - coeff*lhsY[3][4][BB][j][i][k];
lhsY[2][0][CC][j][i][k] = lhsY[2][0][CC][j][i][k] - coeff*lhsY[3][0][CC][j][i][k];
lhsY[2][1][CC][j][i][k] = lhsY[2][1][CC][j][i][k] - coeff*lhsY[3][1][CC][j][i][k];
lhsY[2][2][CC][j][i][k] = lhsY[2][2][CC][j][i][k] - coeff*lhsY[3][2][CC][j][i][k];
lhsY[2][3][CC][j][i][k] = lhsY[2][3][CC][j][i][k] - coeff*lhsY[3][3][CC][j][i][k];
lhsY[2][4][CC][j][i][k] = lhsY[2][4][CC][j][i][k] - coeff*lhsY[3][4][CC][j][i][k];
rhs[k][j][i][2] = rhs[k][j][i][2] - coeff*rhs[k][j][i][3];
coeff = lhsY[4][3][BB][j][i][k];
lhsY[4][4][BB][j][i][k]= lhsY[4][4][BB][j][i][k] - coeff*lhsY[3][4][BB][j][i][k];
lhsY[4][0][CC][j][i][k] = lhsY[4][0][CC][j][i][k] - coeff*lhsY[3][0][CC][j][i][k];
lhsY[4][1][CC][j][i][k] = lhsY[4][1][CC][j][i][k] - coeff*lhsY[3][1][CC][j][i][k];
lhsY[4][2][CC][j][i][k] = lhsY[4][2][CC][j][i][k] - coeff*lhsY[3][2][CC][j][i][k];
lhsY[4][3][CC][j][i][k] = lhsY[4][3][CC][j][i][k] - coeff*lhsY[3][3][CC][j][i][k];
lhsY[4][4][CC][j][i][k] = lhsY[4][4][CC][j][i][k] - coeff*lhsY[3][4][CC][j][i][k];
rhs[k][j][i][4] = rhs[k][j][i][4] - coeff*rhs[k][j][i][3];
pivot = 1.00/lhsY[4][4][BB][j][i][k];
lhsY[4][0][CC][j][i][k] = lhsY[4][0][CC][j][i][k]*pivot;
lhsY[4][1][CC][j][i][k] = lhsY[4][1][CC][j][i][k]*pivot;
lhsY[4][2][CC][j][i][k] = lhsY[4][2][CC][j][i][k]*pivot;
lhsY[4][3][CC][j][i][k] = lhsY[4][3][CC][j][i][k]*pivot;
lhsY[4][4][CC][j][i][k] = lhsY[4][4][CC][j][i][k]*pivot;
rhs[k][j][i][4] = rhs[k][j][i][4] *pivot;
coeff = lhsY[0][4][BB][j][i][k];
lhsY[0][0][CC][j][i][k] = lhsY[0][0][CC][j][i][k] - coeff*lhsY[4][0][CC][j][i][k];
lhsY[0][1][CC][j][i][k] = lhsY[0][1][CC][j][i][k] - coeff*lhsY[4][1][CC][j][i][k];
lhsY[0][2][CC][j][i][k] = lhsY[0][2][CC][j][i][k] - coeff*lhsY[4][2][CC][j][i][k];
lhsY[0][3][CC][j][i][k] = lhsY[0][3][CC][j][i][k] - coeff*lhsY[4][3][CC][j][i][k];
lhsY[0][4][CC][j][i][k] = lhsY[0][4][CC][j][i][k] - coeff*lhsY[4][4][CC][j][i][k];
rhs[k][j][i][0] = rhs[k][j][i][0] - coeff*rhs[k][j][i][4];
coeff = lhsY[1][4][BB][j][i][k];
lhsY[1][0][CC][j][i][k] = lhsY[1][0][CC][j][i][k] - coeff*lhsY[4][0][CC][j][i][k];
lhsY[1][1][CC][j][i][k] = lhsY[1][1][CC][j][i][k] - coeff*lhsY[4][1][CC][j][i][k];
lhsY[1][2][CC][j][i][k] = lhsY[1][2][CC][j][i][k] - coeff*lhsY[4][2][CC][j][i][k];
lhsY[1][3][CC][j][i][k] = lhsY[1][3][CC][j][i][k] - coeff*lhsY[4][3][CC][j][i][k];
lhsY[1][4][CC][j][i][k] = lhsY[1][4][CC][j][i][k] - coeff*lhsY[4][4][CC][j][i][k];
rhs[k][j][i][1] = rhs[k][j][i][1] - coeff*rhs[k][j][i][4];
coeff = lhsY[2][4][BB][j][i][k];
lhsY[2][0][CC][j][i][k] = lhsY[2][0][CC][j][i][k] - coeff*lhsY[4][0][CC][j][i][k];
lhsY[2][1][CC][j][i][k] = lhsY[2][1][CC][j][i][k] - coeff*lhsY[4][1][CC][j][i][k];
lhsY[2][2][CC][j][i][k] = lhsY[2][2][CC][j][i][k] - coeff*lhsY[4][2][CC][j][i][k];
lhsY[2][3][CC][j][i][k] = lhsY[2][3][CC][j][i][k] - coeff*lhsY[4][3][CC][j][i][k];
lhsY[2][4][CC][j][i][k] = lhsY[2][4][CC][j][i][k] - coeff*lhsY[4][4][CC][j][i][k];
rhs[k][j][i][2] = rhs[k][j][i][2] - coeff*rhs[k][j][i][4];
coeff = lhsY[3][4][BB][j][i][k];
lhsY[3][0][CC][j][i][k] = lhsY[3][0][CC][j][i][k] - coeff*lhsY[4][0][CC][j][i][k];
lhsY[3][1][CC][j][i][k] = lhsY[3][1][CC][j][i][k] - coeff*lhsY[4][1][CC][j][i][k];
lhsY[3][2][CC][j][i][k] = lhsY[3][2][CC][j][i][k] - coeff*lhsY[4][2][CC][j][i][k];
lhsY[3][3][CC][j][i][k] = lhsY[3][3][CC][j][i][k] - coeff*lhsY[4][3][CC][j][i][k];
lhsY[3][4][CC][j][i][k] = lhsY[3][4][CC][j][i][k] - coeff*lhsY[4][4][CC][j][i][k];
rhs[k][j][i][3] = rhs[k][j][i][3] - coeff*rhs[k][j][i][4];
}/*end j*/
}/*end i*/
}/*end k*/
//---------------------------------------------------------------------
// rhs(jsize) = rhs(jsize) - A*rhs(jsize-1)
//---------------------------------------------------------------------
//matvec_sub(lhsY[i][jsize-1][AA], rhs[k][jsize][i][k], rhs[k][jsize][i]);
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
/*
for(m = 0; m < 5; m++){
rhs[k][jsize][i][m] = rhs[k][jsize][i][m] - lhsY[m][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[m][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[m][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[m][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[m][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
}
*/
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] - lhsY[0][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[0][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[0][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[0][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[0][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] - lhsY[1][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[1][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[1][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[1][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[1][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] - lhsY[2][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[2][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[2][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[2][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[2][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] - lhsY[3][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[3][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[3][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[3][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[3][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] - lhsY[4][0][AA][jsize][i][k]*rhs[k][jsize-1][i][0]
- lhsY[4][1][AA][jsize][i][k]*rhs[k][jsize-1][i][1]
- lhsY[4][2][AA][jsize][i][k]*rhs[k][jsize-1][i][2]
- lhsY[4][3][AA][jsize][i][k]*rhs[k][jsize-1][i][3]
- lhsY[4][4][AA][jsize][i][k]*rhs[k][jsize-1][i][4];
}
}
//---------------------------------------------------------------------
// B(jsize) = B(jsize) - C(jsize-1)*A(jsize)
// matmul_sub(AA,i,jsize,k,c,
// $ CC,i,jsize-1,k,c,BB,i,jsize,k)
//---------------------------------------------------------------------
//matmul_sub(lhsY[jsize-1][i][AA], lhsY[k][jsize][i][k][CC], lhsY[k][i][jsize][BB]);
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
/*
for(m = 0; m < 5; m++){
for(n = 0; n < 5; n++){
lhsY[n][m][BB][jsize][i][k] = lhsY[n][m][BB][jsize][i][k] - lhsY[n][0][AA][jsize][i][k]*lhsY[0][m][CC][jsize-1][i][k]
- lhsY[n][1][AA][jsize][i][k]*lhsY[1][m][CC][jsize-1][i][k]
- lhsY[n][2][AA][jsize][i][k]*lhsY[2][m][CC][jsize-1][i][k]
- lhsY[n][3][AA][jsize][i][k]*lhsY[3][m][CC][jsize-1][i][k]
- lhsY[n][4][AA][jsize][i][k]*lhsY[4][m][CC][jsize-1][i][k];
}
}
*/
lhsY[0][0][BB][jsize][i][k] = lhsY[0][0][BB][jsize][i][k] - lhsY[0][0][AA][jsize][i][k]*lhsY[0][0][CC][jsize-1][i][k]
- lhsY[0][1][AA][jsize][i][k]*lhsY[1][0][CC][jsize-1][i][k]
- lhsY[0][2][AA][jsize][i][k]*lhsY[2][0][CC][jsize-1][i][k]
- lhsY[0][3][AA][jsize][i][k]*lhsY[3][0][CC][jsize-1][i][k]
- lhsY[0][4][AA][jsize][i][k]*lhsY[4][0][CC][jsize-1][i][k];
lhsY[1][0][BB][jsize][i][k] = lhsY[1][0][BB][jsize][i][k] - lhsY[1][0][AA][jsize][i][k]*lhsY[0][0][CC][jsize-1][i][k]
- lhsY[1][1][AA][jsize][i][k]*lhsY[1][0][CC][jsize-1][i][k]
- lhsY[1][2][AA][jsize][i][k]*lhsY[2][0][CC][jsize-1][i][k]
- lhsY[1][3][AA][jsize][i][k]*lhsY[3][0][CC][jsize-1][i][k]
- lhsY[1][4][AA][jsize][i][k]*lhsY[4][0][CC][jsize-1][i][k];
lhsY[2][0][BB][jsize][i][k] = lhsY[2][0][BB][jsize][i][k] - lhsY[2][0][AA][jsize][i][k]*lhsY[0][0][CC][jsize-1][i][k]
- lhsY[2][1][AA][jsize][i][k]*lhsY[1][0][CC][jsize-1][i][k]
- lhsY[2][2][AA][jsize][i][k]*lhsY[2][0][CC][jsize-1][i][k]
- lhsY[2][3][AA][jsize][i][k]*lhsY[3][0][CC][jsize-1][i][k]
- lhsY[2][4][AA][jsize][i][k]*lhsY[4][0][CC][jsize-1][i][k];
lhsY[3][0][BB][jsize][i][k] = lhsY[3][0][BB][jsize][i][k] - lhsY[3][0][AA][jsize][i][k]*lhsY[0][0][CC][jsize-1][i][k]
- lhsY[3][1][AA][jsize][i][k]*lhsY[1][0][CC][jsize-1][i][k]
- lhsY[3][2][AA][jsize][i][k]*lhsY[2][0][CC][jsize-1][i][k]
- lhsY[3][3][AA][jsize][i][k]*lhsY[3][0][CC][jsize-1][i][k]
- lhsY[3][4][AA][jsize][i][k]*lhsY[4][0][CC][jsize-1][i][k];
lhsY[4][0][BB][jsize][i][k] = lhsY[4][0][BB][jsize][i][k] - lhsY[4][0][AA][jsize][i][k]*lhsY[0][0][CC][jsize-1][i][k]
- lhsY[4][1][AA][jsize][i][k]*lhsY[1][0][CC][jsize-1][i][k]
- lhsY[4][2][AA][jsize][i][k]*lhsY[2][0][CC][jsize-1][i][k]
- lhsY[4][3][AA][jsize][i][k]*lhsY[3][0][CC][jsize-1][i][k]
- lhsY[4][4][AA][jsize][i][k]*lhsY[4][0][CC][jsize-1][i][k];
lhsY[0][1][BB][jsize][i][k] = lhsY[0][1][BB][jsize][i][k] - lhsY[0][0][AA][jsize][i][k]*lhsY[0][1][CC][jsize-1][i][k]
- lhsY[0][1][AA][jsize][i][k]*lhsY[1][1][CC][jsize-1][i][k]
- lhsY[0][2][AA][jsize][i][k]*lhsY[2][1][CC][jsize-1][i][k]
- lhsY[0][3][AA][jsize][i][k]*lhsY[3][1][CC][jsize-1][i][k]
- lhsY[0][4][AA][jsize][i][k]*lhsY[4][1][CC][jsize-1][i][k];
lhsY[1][1][BB][jsize][i][k] = lhsY[1][1][BB][jsize][i][k] - lhsY[1][0][AA][jsize][i][k]*lhsY[0][1][CC][jsize-1][i][k]
- lhsY[1][1][AA][jsize][i][k]*lhsY[1][1][CC][jsize-1][i][k]
- lhsY[1][2][AA][jsize][i][k]*lhsY[2][1][CC][jsize-1][i][k]
- lhsY[1][3][AA][jsize][i][k]*lhsY[3][1][CC][jsize-1][i][k]
- lhsY[1][4][AA][jsize][i][k]*lhsY[4][1][CC][jsize-1][i][k];
lhsY[2][1][BB][jsize][i][k] = lhsY[2][1][BB][jsize][i][k] - lhsY[2][0][AA][jsize][i][k]*lhsY[0][1][CC][jsize-1][i][k]
- lhsY[2][1][AA][jsize][i][k]*lhsY[1][1][CC][jsize-1][i][k]
- lhsY[2][2][AA][jsize][i][k]*lhsY[2][1][CC][jsize-1][i][k]
- lhsY[2][3][AA][jsize][i][k]*lhsY[3][1][CC][jsize-1][i][k]
- lhsY[2][4][AA][jsize][i][k]*lhsY[4][1][CC][jsize-1][i][k];
lhsY[3][1][BB][jsize][i][k] = lhsY[3][1][BB][jsize][i][k] - lhsY[3][0][AA][jsize][i][k]*lhsY[0][1][CC][jsize-1][i][k]
- lhsY[3][1][AA][jsize][i][k]*lhsY[1][1][CC][jsize-1][i][k]
- lhsY[3][2][AA][jsize][i][k]*lhsY[2][1][CC][jsize-1][i][k]
- lhsY[3][3][AA][jsize][i][k]*lhsY[3][1][CC][jsize-1][i][k]
- lhsY[3][4][AA][jsize][i][k]*lhsY[4][1][CC][jsize-1][i][k];
lhsY[4][1][BB][jsize][i][k] = lhsY[4][1][BB][jsize][i][k] - lhsY[4][0][AA][jsize][i][k]*lhsY[0][1][CC][jsize-1][i][k]
- lhsY[4][1][AA][jsize][i][k]*lhsY[1][1][CC][jsize-1][i][k]
- lhsY[4][2][AA][jsize][i][k]*lhsY[2][1][CC][jsize-1][i][k]
- lhsY[4][3][AA][jsize][i][k]*lhsY[3][1][CC][jsize-1][i][k]
- lhsY[4][4][AA][jsize][i][k]*lhsY[4][1][CC][jsize-1][i][k];
lhsY[0][2][BB][jsize][i][k] = lhsY[0][2][BB][jsize][i][k] - lhsY[0][0][AA][jsize][i][k]*lhsY[0][2][CC][jsize-1][i][k]
- lhsY[0][1][AA][jsize][i][k]*lhsY[1][2][CC][jsize-1][i][k]
- lhsY[0][2][AA][jsize][i][k]*lhsY[2][2][CC][jsize-1][i][k]
- lhsY[0][3][AA][jsize][i][k]*lhsY[3][2][CC][jsize-1][i][k]
- lhsY[0][4][AA][jsize][i][k]*lhsY[4][2][CC][jsize-1][i][k];
lhsY[1][2][BB][jsize][i][k] = lhsY[1][2][BB][jsize][i][k] - lhsY[1][0][AA][jsize][i][k]*lhsY[0][2][CC][jsize-1][i][k]
- lhsY[1][1][AA][jsize][i][k]*lhsY[1][2][CC][jsize-1][i][k]
- lhsY[1][2][AA][jsize][i][k]*lhsY[2][2][CC][jsize-1][i][k]
- lhsY[1][3][AA][jsize][i][k]*lhsY[3][2][CC][jsize-1][i][k]
- lhsY[1][4][AA][jsize][i][k]*lhsY[4][2][CC][jsize-1][i][k];
lhsY[2][2][BB][jsize][i][k] = lhsY[2][2][BB][jsize][i][k] - lhsY[2][0][AA][jsize][i][k]*lhsY[0][2][CC][jsize-1][i][k]
- lhsY[2][1][AA][jsize][i][k]*lhsY[1][2][CC][jsize-1][i][k]
- lhsY[2][2][AA][jsize][i][k]*lhsY[2][2][CC][jsize-1][i][k]
- lhsY[2][3][AA][jsize][i][k]*lhsY[3][2][CC][jsize-1][i][k]
- lhsY[2][4][AA][jsize][i][k]*lhsY[4][2][CC][jsize-1][i][k];
lhsY[3][2][BB][jsize][i][k] = lhsY[3][2][BB][jsize][i][k] - lhsY[3][0][AA][jsize][i][k]*lhsY[0][2][CC][jsize-1][i][k]
- lhsY[3][1][AA][jsize][i][k]*lhsY[1][2][CC][jsize-1][i][k]
- lhsY[3][2][AA][jsize][i][k]*lhsY[2][2][CC][jsize-1][i][k]
- lhsY[3][3][AA][jsize][i][k]*lhsY[3][2][CC][jsize-1][i][k]
- lhsY[3][4][AA][jsize][i][k]*lhsY[4][2][CC][jsize-1][i][k];
lhsY[4][2][BB][jsize][i][k] = lhsY[4][2][BB][jsize][i][k] - lhsY[4][0][AA][jsize][i][k]*lhsY[0][2][CC][jsize-1][i][k]
- lhsY[4][1][AA][jsize][i][k]*lhsY[1][2][CC][jsize-1][i][k]
- lhsY[4][2][AA][jsize][i][k]*lhsY[2][2][CC][jsize-1][i][k]
- lhsY[4][3][AA][jsize][i][k]*lhsY[3][2][CC][jsize-1][i][k]
- lhsY[4][4][AA][jsize][i][k]*lhsY[4][2][CC][jsize-1][i][k];
lhsY[0][3][BB][jsize][i][k] = lhsY[0][3][BB][jsize][i][k] - lhsY[0][0][AA][jsize][i][k]*lhsY[0][3][CC][jsize-1][i][k]
- lhsY[0][1][AA][jsize][i][k]*lhsY[1][3][CC][jsize-1][i][k]
- lhsY[0][2][AA][jsize][i][k]*lhsY[2][3][CC][jsize-1][i][k]
- lhsY[0][3][AA][jsize][i][k]*lhsY[3][3][CC][jsize-1][i][k]
- lhsY[0][4][AA][jsize][i][k]*lhsY[4][3][CC][jsize-1][i][k];
lhsY[1][3][BB][jsize][i][k] = lhsY[1][3][BB][jsize][i][k] - lhsY[1][0][AA][jsize][i][k]*lhsY[0][3][CC][jsize-1][i][k]
- lhsY[1][1][AA][jsize][i][k]*lhsY[1][3][CC][jsize-1][i][k]
- lhsY[1][2][AA][jsize][i][k]*lhsY[2][3][CC][jsize-1][i][k]
- lhsY[1][3][AA][jsize][i][k]*lhsY[3][3][CC][jsize-1][i][k]
- lhsY[1][4][AA][jsize][i][k]*lhsY[4][3][CC][jsize-1][i][k];
lhsY[2][3][BB][jsize][i][k] = lhsY[2][3][BB][jsize][i][k] - lhsY[2][0][AA][jsize][i][k]*lhsY[0][3][CC][jsize-1][i][k]
- lhsY[2][1][AA][jsize][i][k]*lhsY[1][3][CC][jsize-1][i][k]
- lhsY[2][2][AA][jsize][i][k]*lhsY[2][3][CC][jsize-1][i][k]
- lhsY[2][3][AA][jsize][i][k]*lhsY[3][3][CC][jsize-1][i][k]
- lhsY[2][4][AA][jsize][i][k]*lhsY[4][3][CC][jsize-1][i][k];
lhsY[3][3][BB][jsize][i][k] = lhsY[3][3][BB][jsize][i][k] - lhsY[3][0][AA][jsize][i][k]*lhsY[0][3][CC][jsize-1][i][k]
- lhsY[3][1][AA][jsize][i][k]*lhsY[1][3][CC][jsize-1][i][k]
- lhsY[3][2][AA][jsize][i][k]*lhsY[2][3][CC][jsize-1][i][k]
- lhsY[3][3][AA][jsize][i][k]*lhsY[3][3][CC][jsize-1][i][k]
- lhsY[3][4][AA][jsize][i][k]*lhsY[4][3][CC][jsize-1][i][k];
lhsY[4][3][BB][jsize][i][k] = lhsY[4][3][BB][jsize][i][k] - lhsY[4][0][AA][jsize][i][k]*lhsY[0][3][CC][jsize-1][i][k]
- lhsY[4][1][AA][jsize][i][k]*lhsY[1][3][CC][jsize-1][i][k]
- lhsY[4][2][AA][jsize][i][k]*lhsY[2][3][CC][jsize-1][i][k]
- lhsY[4][3][AA][jsize][i][k]*lhsY[3][3][CC][jsize-1][i][k]
- lhsY[4][4][AA][jsize][i][k]*lhsY[4][3][CC][jsize-1][i][k];
lhsY[0][4][BB][jsize][i][k] = lhsY[0][4][BB][jsize][i][k] - lhsY[0][0][AA][jsize][i][k]*lhsY[0][4][CC][jsize-1][i][k]
- lhsY[0][1][AA][jsize][i][k]*lhsY[1][4][CC][jsize-1][i][k]
- lhsY[0][2][AA][jsize][i][k]*lhsY[2][4][CC][jsize-1][i][k]
- lhsY[0][3][AA][jsize][i][k]*lhsY[3][4][CC][jsize-1][i][k]
- lhsY[0][4][AA][jsize][i][k]*lhsY[4][4][CC][jsize-1][i][k];
lhsY[1][4][BB][jsize][i][k] = lhsY[1][4][BB][jsize][i][k] - lhsY[1][0][AA][jsize][i][k]*lhsY[0][4][CC][jsize-1][i][k]
- lhsY[1][1][AA][jsize][i][k]*lhsY[1][4][CC][jsize-1][i][k]
- lhsY[1][2][AA][jsize][i][k]*lhsY[2][4][CC][jsize-1][i][k]
- lhsY[1][3][AA][jsize][i][k]*lhsY[3][4][CC][jsize-1][i][k]
- lhsY[1][4][AA][jsize][i][k]*lhsY[4][4][CC][jsize-1][i][k];
lhsY[2][4][BB][jsize][i][k] = lhsY[2][4][BB][jsize][i][k] - lhsY[2][0][AA][jsize][i][k]*lhsY[0][4][CC][jsize-1][i][k]
- lhsY[2][1][AA][jsize][i][k]*lhsY[1][4][CC][jsize-1][i][k]
- lhsY[2][2][AA][jsize][i][k]*lhsY[2][4][CC][jsize-1][i][k]
- lhsY[2][3][AA][jsize][i][k]*lhsY[3][4][CC][jsize-1][i][k]
- lhsY[2][4][AA][jsize][i][k]*lhsY[4][4][CC][jsize-1][i][k];
lhsY[3][4][BB][jsize][i][k] = lhsY[3][4][BB][jsize][i][k] - lhsY[3][0][AA][jsize][i][k]*lhsY[0][4][CC][jsize-1][i][k]
- lhsY[3][1][AA][jsize][i][k]*lhsY[1][4][CC][jsize-1][i][k]
- lhsY[3][2][AA][jsize][i][k]*lhsY[2][4][CC][jsize-1][i][k]
- lhsY[3][3][AA][jsize][i][k]*lhsY[3][4][CC][jsize-1][i][k]
- lhsY[3][4][AA][jsize][i][k]*lhsY[4][4][CC][jsize-1][i][k];
lhsY[4][4][BB][jsize][i][k] = lhsY[4][4][BB][jsize][i][k] - lhsY[4][0][AA][jsize][i][k]*lhsY[0][4][CC][jsize-1][i][k]
- lhsY[4][1][AA][jsize][i][k]*lhsY[1][4][CC][jsize-1][i][k]
- lhsY[4][2][AA][jsize][i][k]*lhsY[2][4][CC][jsize-1][i][k]
- lhsY[4][3][AA][jsize][i][k]*lhsY[3][4][CC][jsize-1][i][k]
- lhsY[4][4][AA][jsize][i][k]*lhsY[4][4][CC][jsize-1][i][k];
}
}
//---------------------------------------------------------------------
// multiply rhs(jsize) by b_inverse(jsize) and copy to rhs
//---------------------------------------------------------------------
//binvrhs( lhsY[i][jsize][BB], rhs[k][jsize][i][k] );
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
/*
for(m = 0; m < 5; m++){
pivot = 1.00/lhsY[m][m][BB][jsize][i][k];
for(n = m+1; n < 5; n++){
lhsY[m][n][BB][jsize][i][k] = lhsY[m][n][BB][jsize][i][k]*pivot;
}
rhs[k][jsize][i][m] = rhs[k][jsize][i][m]*pivot;
for(n = 0; n < 5; n++){
if(n != m){
coeff = lhsY[n][m][BB][jsize][i][k];
for(z = m+1; z < 5; z++){
lhsY[n][z][BB][jsize][i][k] = lhsY[n][z][BB][jsize][i][k] - coeff*lhsY[m][z][BB][jsize][i][k];
}
rhs[k][jsize][i][n] = rhs[k][jsize][i][n] - coeff*rhs[k][jsize][i][m];
}
}
}
*/
pivot = 1.00/lhsY[0][0][BB][jsize][i][k];
lhsY[0][1][BB][jsize][i][k] = lhsY[0][1][BB][jsize][i][k]*pivot;
lhsY[0][2][BB][jsize][i][k] = lhsY[0][2][BB][jsize][i][k]*pivot;
lhsY[0][3][BB][jsize][i][k] = lhsY[0][3][BB][jsize][i][k]*pivot;
lhsY[0][4][BB][jsize][i][k] = lhsY[0][4][BB][jsize][i][k]*pivot;
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] *pivot;
coeff = lhsY[1][0][BB][jsize][i][k];
lhsY[1][1][BB][jsize][i][k]= lhsY[1][1][BB][jsize][i][k] - coeff*lhsY[0][1][BB][jsize][i][k];
lhsY[1][2][BB][jsize][i][k]= lhsY[1][2][BB][jsize][i][k] - coeff*lhsY[0][2][BB][jsize][i][k];
lhsY[1][3][BB][jsize][i][k]= lhsY[1][3][BB][jsize][i][k] - coeff*lhsY[0][3][BB][jsize][i][k];
lhsY[1][4][BB][jsize][i][k]= lhsY[1][4][BB][jsize][i][k] - coeff*lhsY[0][4][BB][jsize][i][k];
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] - coeff*rhs[k][jsize][i][0];
coeff = lhsY[2][0][BB][jsize][i][k];
lhsY[2][1][BB][jsize][i][k]= lhsY[2][1][BB][jsize][i][k] - coeff*lhsY[0][1][BB][jsize][i][k];
lhsY[2][2][BB][jsize][i][k]= lhsY[2][2][BB][jsize][i][k] - coeff*lhsY[0][2][BB][jsize][i][k];
lhsY[2][3][BB][jsize][i][k]= lhsY[2][3][BB][jsize][i][k] - coeff*lhsY[0][3][BB][jsize][i][k];
lhsY[2][4][BB][jsize][i][k]= lhsY[2][4][BB][jsize][i][k] - coeff*lhsY[0][4][BB][jsize][i][k];
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] - coeff*rhs[k][jsize][i][0];
coeff = lhsY[3][0][BB][jsize][i][k];
lhsY[3][1][BB][jsize][i][k]= lhsY[3][1][BB][jsize][i][k] - coeff*lhsY[0][1][BB][jsize][i][k];
lhsY[3][2][BB][jsize][i][k]= lhsY[3][2][BB][jsize][i][k] - coeff*lhsY[0][2][BB][jsize][i][k];
lhsY[3][3][BB][jsize][i][k]= lhsY[3][3][BB][jsize][i][k] - coeff*lhsY[0][3][BB][jsize][i][k];
lhsY[3][4][BB][jsize][i][k]= lhsY[3][4][BB][jsize][i][k] - coeff*lhsY[0][4][BB][jsize][i][k];
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] - coeff*rhs[k][jsize][i][0];
coeff = lhsY[4][0][BB][jsize][i][k];
lhsY[4][1][BB][jsize][i][k]= lhsY[4][1][BB][jsize][i][k] - coeff*lhsY[0][1][BB][jsize][i][k];
lhsY[4][2][BB][jsize][i][k]= lhsY[4][2][BB][jsize][i][k] - coeff*lhsY[0][2][BB][jsize][i][k];
lhsY[4][3][BB][jsize][i][k]= lhsY[4][3][BB][jsize][i][k] - coeff*lhsY[0][3][BB][jsize][i][k];
lhsY[4][4][BB][jsize][i][k]= lhsY[4][4][BB][jsize][i][k] - coeff*lhsY[0][4][BB][jsize][i][k];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] - coeff*rhs[k][jsize][i][0];
pivot = 1.00/lhsY[1][1][BB][jsize][i][k];
lhsY[1][2][BB][jsize][i][k] = lhsY[1][2][BB][jsize][i][k]*pivot;
lhsY[1][3][BB][jsize][i][k] = lhsY[1][3][BB][jsize][i][k]*pivot;
lhsY[1][4][BB][jsize][i][k] = lhsY[1][4][BB][jsize][i][k]*pivot;
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] *pivot;
coeff = lhsY[0][1][BB][jsize][i][k];
lhsY[0][2][BB][jsize][i][k]= lhsY[0][2][BB][jsize][i][k] - coeff*lhsY[1][2][BB][jsize][i][k];
lhsY[0][3][BB][jsize][i][k]= lhsY[0][3][BB][jsize][i][k] - coeff*lhsY[1][3][BB][jsize][i][k];
lhsY[0][4][BB][jsize][i][k]= lhsY[0][4][BB][jsize][i][k] - coeff*lhsY[1][4][BB][jsize][i][k];
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] - coeff*rhs[k][jsize][i][1];
coeff = lhsY[2][1][BB][jsize][i][k];
lhsY[2][2][BB][jsize][i][k]= lhsY[2][2][BB][jsize][i][k] - coeff*lhsY[1][2][BB][jsize][i][k];
lhsY[2][3][BB][jsize][i][k]= lhsY[2][3][BB][jsize][i][k] - coeff*lhsY[1][3][BB][jsize][i][k];
lhsY[2][4][BB][jsize][i][k]= lhsY[2][4][BB][jsize][i][k] - coeff*lhsY[1][4][BB][jsize][i][k];
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] - coeff*rhs[k][jsize][i][1];
coeff = lhsY[3][1][BB][jsize][i][k];
lhsY[3][2][BB][jsize][i][k]= lhsY[3][2][BB][jsize][i][k] - coeff*lhsY[1][2][BB][jsize][i][k];
lhsY[3][3][BB][jsize][i][k]= lhsY[3][3][BB][jsize][i][k] - coeff*lhsY[1][3][BB][jsize][i][k];
lhsY[3][4][BB][jsize][i][k]= lhsY[3][4][BB][jsize][i][k] - coeff*lhsY[1][4][BB][jsize][i][k];
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] - coeff*rhs[k][jsize][i][1];
coeff = lhsY[4][1][BB][jsize][i][k];
lhsY[4][2][BB][jsize][i][k]= lhsY[4][2][BB][jsize][i][k] - coeff*lhsY[1][2][BB][jsize][i][k];
lhsY[4][3][BB][jsize][i][k]= lhsY[4][3][BB][jsize][i][k] - coeff*lhsY[1][3][BB][jsize][i][k];
lhsY[4][4][BB][jsize][i][k]= lhsY[4][4][BB][jsize][i][k] - coeff*lhsY[1][4][BB][jsize][i][k];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] - coeff*rhs[k][jsize][i][1];
pivot = 1.00/lhsY[2][2][BB][jsize][i][k];
lhsY[2][3][BB][jsize][i][k] = lhsY[2][3][BB][jsize][i][k]*pivot;
lhsY[2][4][BB][jsize][i][k] = lhsY[2][4][BB][jsize][i][k]*pivot;
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] *pivot;
coeff = lhsY[0][2][BB][jsize][i][k];
lhsY[0][3][BB][jsize][i][k]= lhsY[0][3][BB][jsize][i][k] - coeff*lhsY[2][3][BB][jsize][i][k];
lhsY[0][4][BB][jsize][i][k]= lhsY[0][4][BB][jsize][i][k] - coeff*lhsY[2][4][BB][jsize][i][k];
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] - coeff*rhs[k][jsize][i][2];
coeff = lhsY[1][2][BB][jsize][i][k];
lhsY[1][3][BB][jsize][i][k]= lhsY[1][3][BB][jsize][i][k] - coeff*lhsY[2][3][BB][jsize][i][k];
lhsY[1][4][BB][jsize][i][k]= lhsY[1][4][BB][jsize][i][k] - coeff*lhsY[2][4][BB][jsize][i][k];
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] - coeff*rhs[k][jsize][i][2];
coeff = lhsY[3][2][BB][jsize][i][k];
lhsY[3][3][BB][jsize][i][k]= lhsY[3][3][BB][jsize][i][k] - coeff*lhsY[2][3][BB][jsize][i][k];
lhsY[3][4][BB][jsize][i][k]= lhsY[3][4][BB][jsize][i][k] - coeff*lhsY[2][4][BB][jsize][i][k];
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] - coeff*rhs[k][jsize][i][2];
coeff = lhsY[4][2][BB][jsize][i][k];
lhsY[4][3][BB][jsize][i][k]= lhsY[4][3][BB][jsize][i][k] - coeff*lhsY[2][3][BB][jsize][i][k];
lhsY[4][4][BB][jsize][i][k]= lhsY[4][4][BB][jsize][i][k] - coeff*lhsY[2][4][BB][jsize][i][k];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] - coeff*rhs[k][jsize][i][2];
pivot = 1.00/lhsY[3][3][BB][jsize][i][k];
lhsY[3][4][BB][jsize][i][k] = lhsY[3][4][BB][jsize][i][k]*pivot;
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] *pivot;
coeff = lhsY[0][3][BB][jsize][i][k];
lhsY[0][4][BB][jsize][i][k]= lhsY[0][4][BB][jsize][i][k] - coeff*lhsY[3][4][BB][jsize][i][k];
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] - coeff*rhs[k][jsize][i][3];
coeff = lhsY[1][3][BB][jsize][i][k];
lhsY[1][4][BB][jsize][i][k]= lhsY[1][4][BB][jsize][i][k] - coeff*lhsY[3][4][BB][jsize][i][k];
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] - coeff*rhs[k][jsize][i][3];
coeff = lhsY[2][3][BB][jsize][i][k];
lhsY[2][4][BB][jsize][i][k]= lhsY[2][4][BB][jsize][i][k] - coeff*lhsY[3][4][BB][jsize][i][k];
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] - coeff*rhs[k][jsize][i][3];
coeff = lhsY[4][3][BB][jsize][i][k];
lhsY[4][4][BB][jsize][i][k]= lhsY[4][4][BB][jsize][i][k] - coeff*lhsY[3][4][BB][jsize][i][k];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] - coeff*rhs[k][jsize][i][3];
pivot = 1.00/lhsY[4][4][BB][jsize][i][k];
rhs[k][jsize][i][4] = rhs[k][jsize][i][4] *pivot;
coeff = lhsY[0][4][BB][jsize][i][k];
rhs[k][jsize][i][0] = rhs[k][jsize][i][0] - coeff*rhs[k][jsize][i][4];
coeff = lhsY[1][4][BB][jsize][i][k];
rhs[k][jsize][i][1] = rhs[k][jsize][i][1] - coeff*rhs[k][jsize][i][4];
coeff = lhsY[2][4][BB][jsize][i][k];
rhs[k][jsize][i][2] = rhs[k][jsize][i][2] - coeff*rhs[k][jsize][i][4];
coeff = lhsY[3][4][BB][jsize][i][k];
rhs[k][jsize][i][3] = rhs[k][jsize][i][3] - coeff*rhs[k][jsize][i][4];
}
}
//---------------------------------------------------------------------
// back solve: if last cell, then generate U(jsize)=rhs(jsize)
// else assume U(jsize) is loaded in un pack backsub_info
// so just use it
// after u(jstart) will be sent to next cell
//---------------------------------------------------------------------
#pragma acc kernels loop
for (k = 1; k <= gp22; k++) {
for (i = 1; i <= gp02; i++) {
for (j = jsize-1; j >= 0; j--) {
for (m = 0; m < BLOCK_SIZE; m++) {
for (n = 0; n < BLOCK_SIZE; n++) {
rhs[k][j][i][m] = rhs[k][j][i][m]
- lhsY[m][n][CC][j][i][k]*rhs[k][j+1][i][n];
}
}
}
}
}
}/*end acc data*/
}
|
./SPEChpc/benchspec/HPC/613.soma_s/src/soma_util.c | /* Copyright (C) 2016-2017 Ludwig Schneider
This file is part of SOMA.
SOMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SOMA 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 SOMA. If not, see <http://www.gnu.org/licenses/>.
*/
//! \file soma_util.c
//! \brief Implementation of soma_util.h
#include "soma_util.h"
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#include "cmdline.h"
#include "phase.h"
#include "mpiroutines.h"
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
unsigned int get_bond_type(const uint32_t info)
{
return info<<28>>29;
}
int get_offset(const int32_t info)
{
return info>>4;
}
unsigned int get_end(const uint32_t info)
{
return info & 1;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
uint32_t get_info(const int offset,const unsigned int bond_type,const unsigned int end)
{
int ret = offset;
ret <<= 3;
#ifndef SPEC_OPENACC
assert( bond_type < 1<<3);
#endif//SPEC_OPENACC
ret |= bond_type;
ret <<= 1;
#ifndef SPEC_OPENACC
assert( end < 1<<1);
#endif//SPEC_OPENACC
ret |= end;
return ret;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp declare target
#endif
int get_bondlist_offset(const int32_t info_bl)
{
return info_bl>>8;
}
unsigned int get_particle_type(const uint32_t info_bl)
{
return info_bl<<24>>24;
}
#ifdef SPEC_OPENMP_TARGET
#pragma omp end declare target
#endif
uint32_t get_info_bl(const unsigned int offset_bl,const unsigned int type)
{
unsigned int ret = offset_bl;
ret <<= 8;
#ifndef SPEC_OPENACC
assert( type < 1<<8);
#endif//SPEC_OPENACC
ret |= type;
return ret;
}
struct som_args post_process_args(struct som_args*args,const struct Info_MPI*const mpi_info)
{
if( mpi_info->current_core == 0)
{
cmdline_parser_print_version();
printf("\n");
}
if( args->timesteps_arg < 0)
{
if(mpi_info->current_core == 0)
fprintf(stderr,"WARNING: negative number of timesteps given. Is set to 0.\n");
args->timesteps_arg = 0;
}
#ifdef OPENACC
if( (!args->gpus_given && !args->only_gpu_given) || (args->gpus_given && args->gpus_arg <= 0) )
{
if(mpi_info->current_core == 0)
fprintf(stderr,"WARNING: No GPU usage specified, but this version has been compiled with OpenACC support.\n"
"WARNING: Are you sure, that you do not want to set a GPU? If not, try the options --gpus or --only-gpu.\n");
}
if( args->gpus_given && args->gpus_arg < 0 )
{
if(mpi_info->current_core == 0)
fprintf(stderr,"WARNING: Negative number of gpus specified. Option will be ignored.\n");
args->gpus_given = false;
}
#endif
if( args->screen_output_interval_arg < 0)
{
if(mpi_info->current_core == 0)
fprintf(stderr,"WARNING: Negative number of seconds for screen ouput given. Screen ouput is switched off.\n");
args->screen_output_interval_arg = 0;
}
if(args->autotuner_restart_period_arg < 0)
{
if( mpi_info->current_core == 0)
fprintf(stderr,"WARNING: Negative number for autotuner restart given, is switched off.\n");
args->autotuner_restart_period_arg = 0;
}
uint32_t fixed_seed;
if( ! args->rng_seed_given || args->rng_seed_arg < 0)
fixed_seed = time(NULL);
else
fixed_seed = args->rng_seed_arg;
MPI_Bcast(&fixed_seed,1,MPI_UINT32_T,0,mpi_info->SOMA_MPI_Comm);
args->rng_seed_arg = fixed_seed;
if(mpi_info->current_core == 0)
printf("All %d ranks use fixed seed %u.\n",mpi_info->Ncores,args->rng_seed_arg);
if(mpi_info->current_core == 0)
cmdline_parser_dump(stdout, args);
return *args;
}
unsigned int get_number_bond_type(const struct Phase*const p,const enum Bondtype btype)
{
unsigned int counter = 0;
for(unsigned int p_type=0; p_type < p->n_poly_type; p_type++)
{
const unsigned int N = p->poly_arch[ p->poly_type_offset[ p_type ] ];
for(unsigned int mono = 0 ; mono < N; mono++)
{
const int start = get_bondlist_offset(
p->poly_arch[ p->poly_type_offset[ p_type] + 1 + mono ]);
if( start > 0)
{
int i=start;
unsigned int end;
do{
const uint32_t info = p->poly_arch[i++];
end = get_end(info);
const unsigned int bond_type = get_bond_type(info);
if( bond_type == btype )
counter++;
}while(end==0);
}
}
}
return counter;
}
int reseed(struct Phase*const p,const unsigned int seed)
{
uint64_t n_polymer_offset;
MPI_Scan( &(p->n_polymers), &n_polymer_offset, 1,MPI_UINT64_T, MPI_SUM, p->info_MPI.SOMA_MPI_Comm);
n_polymer_offset -= p->n_polymers;
//Reset PRNG to initial state
#ifdef SPEC_OPENACC
#pragma acc parallel loop independent present(p)
#endif
#ifdef SPEC_OPENMP_TARGET
#pragma omp target teams distribute parallel for
#endif
#ifdef SPEC_OPENMP
#pragma omp parallel for
#endif
for(uint64_t i=0; i < p->n_polymers;i++)
{
seed_rng_state(&(p->polymers[i].poly_state), seed,
i+n_polymer_offset, p->args.pseudo_random_number_generator_arg);
}
#if 0
for(uint64_t i=0; i < p->n_polymers;i++)
update_self_rng_state(&(p->polymers[i].poly_state), p->args.pseudo_random_number_generator_arg);
#endif
return 0;
}
|
./MURaM_main/include/muramacc.H | #ifndef __MURAMACC__
#define __MURAMACC__
#define STRINGIFY(a) #a
// NVIDIA NV TOOLS Profiler Push/Pop
#ifdef USE_NVTX
#include "nvToolsExt.h"
const uint32_t ProfilerColors[] = { 0xff00ff00, 0xff0000ff, 0xffffff00, 0xffff00ff, 0xff00ffff, 0xffff0000, 0xffffffff };
#define NVPROF_PUSH_RANGE(name,cid) { \
int color_id = cid%7; \
nvtxEventAttributes_t eventAttrib = {0}; \
eventAttrib.version = NVTX_VERSION; \
eventAttrib.size = NVTX_EVENT_ATTRIB_STRUCT_SIZE; \
eventAttrib.colorType = NVTX_COLOR_ARGB; \
eventAttrib.color = ProfilerColors[color_id]; \
eventAttrib.messageType = NVTX_MESSAGE_TYPE_ASCII; \
eventAttrib.message.ascii = name; \
nvtxRangePushEx(&eventAttrib); \
}
#define NVPROF_POP_RANGE nvtxRangePop();
#else
#define NVPROF_PUSH_RANGE(name,cid)
#define NVPROF_POP_RANGE
#endif
// PGI acc_compare pgi_compare for C++
#if defined(DEBUG) && defined(PGICOMPARE) && defined(__PGI)
#include <openacc.h>
#define PGI_COMPARE(ptr,type,numele,name,file,func,line) { \
type* pgi_compare_ptr = (type*)ptr; \
if( acc_is_present( pgi_compare_ptr , numele*sizeof(type) ) ) { \
_Pragma(STRINGIFY(acc update self(pgi_compare_ptr[:numele]))) \
} \
pgi_compare(pgi_compare_ptr, #type, numele, \
name, file, func, line); \
if( acc_is_present( pgi_compare_ptr , numele*sizeof(type) ) ) { \
_Pragma(STRINGIFY(acc update device(pgi_compare_ptr[:numele]))) \
} \
}
#else
#define PGI_COMPARE(ptr,type,size,name,file,func,line)
#endif
#if defined(DEBUG) && defined(ACCCOMPARE) && defined(_OPENACC) && defined(__PGI)
#define ACC_COMPARE(ptr,type,size) { \
type* acc_compare_ptr = (type*) ptr; \
acc_compare(acc_compare_ptr, size); \
}
#else
#define ACC_COMPARE(ptr,type,size)
#endif
#ifdef _OPENACC
#include <openacc.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <cstdint>
void * accMalloc(size_t numbytes);
void accFree(void * ptr);
void * gpuMalloc(size_t numbytes);
void gpuFree(void * ptr);
#endif
|
./openacc-vv/parallel_independent_atomic_write.c | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.7-3.2
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
#pragma acc data copy(a[0:n], b[0:n])
{
#pragma acc parallel
{
#pragma acc loop independent
for (int x = 0; x < n; ++x){
#pragma acc atomic write
b[x] = a[x];
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - b[x]) > PRECISION){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_x_rshift_expr.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int *a = (unsigned int *)malloc(n * sizeof(int));
unsigned int *b = (unsigned int *)malloc(n * sizeof(int));
for (int x = 0; x < n; ++x){
a[x] = 1<<7;
for (int y = 0; y < 7; ++y){
if ((rand()/(unsigned int) (RAND_MAX)) > .5){
b[x] += 1<<y;
}
}
}
#pragma acc data copyin(b[0:n]) copy(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc loop
for (int y = 0; y < 7; ++y){
if ((b[x]>>y)%2 == 1){
#pragma acc atomic
a[x] = a[x] >> 1;
}
}
}
}
}
for (int x = 0; x < n; ++x){
for (int y = 0; y < 7; ++y){
if ((b[x]>>y)%2 == 1){
a[x] <<= 1;
}
}
if (a[x] != 1<<7){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_reduction_bitand_loop.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,reduction,combined-constructs,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
unsigned int * a = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * b_copy = (unsigned int *)malloc(10 * n * sizeof(unsigned int));
unsigned int * c = (unsigned int *)malloc(10 * sizeof(unsigned int));
real_t false_margin = pow(exp(1), log(.5)/n);
unsigned int temp = 1;
for (int x = 0; x < 10 * n; ++x){
b[x] = (unsigned int) rand() / (real_t)(RAND_MAX / 1000);
b_copy[x] = b[x];
for (int y = 0; y < 16; ++y){
if (rand() / (real_t) RAND_MAX < false_margin){
for (int z = 0; z < y; ++z){
temp *= 2;
}
a[x] += temp;
temp = 1;
}
}
}
#pragma acc data copyin(a[0:10 * n]) copy(b[0:10 * n], c[0:10])
{
#pragma acc kernels loop gang private(temp)
for (int y = 0; y < 10; ++y){
temp = a[y * n];
#pragma acc loop worker reduction(&:temp)
for (int x = 1; x < n; ++x){
temp = temp & a[y * n + x];
}
c[y] = temp;
#pragma acc loop worker
for (int x = 0; x < n; ++x){
b[y * n + x] = b[y * n + x] + c[y];
}
}
}
unsigned int* host_c = (unsigned int *)malloc(10 * sizeof(unsigned int));
for (int x = 0; x < 10; ++x){
host_c[x] = a[x * n];
for (int y = 1; y < n; ++y){
host_c[x] = host_c[x] & a[x * n + y];
}
if (host_c[x] != c[x]){
err += 1;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < n; ++y){
if (b[x * n + y] != b_copy[x * n + y] + c[x]){
err += 1;
}
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/atomic_structured_assign_preincrement.c | #include "acc_testsuite.h"
#ifndef T1
//T1:atomic,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
int *c = (int *)malloc(n * sizeof(int));
int *distribution = (int *)malloc(10 * sizeof(int));
int *distribution_comparison = (int *)malloc(10 * sizeof(int));
bool found = false;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
}
for (int x = 0; x < 10; ++x){
distribution[x] = 0;
distribution_comparison[x] = 0;
}
#pragma acc data copyin(a[0:n], b[0:n]) copy(distribution[0:10]) copyout(c[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
#pragma acc atomic capture
{
c[x] = distribution[(int) (a[x]*b[x]/10)];
++distribution[(int) (a[x]*b[x]/10)];
}
}
}
}
for (int x = 0; x < n; ++x){
distribution_comparison[(int) (a[x]*b[x]/10)]++;
}
for (int x = 0; x < 10; ++x){
if (distribution_comparison[x] != distribution[x]){
err += 1;
break;
}
}
for (int x = 0; x < 10; ++x){
for (int y = 0; y < distribution[x]; ++y){
for (int z = 0; z < n; ++z){
if (c[z] == y && x == (int) (a[z] * b[z] / 10)){
found = true;
break;
}
}
if (!found){
err++;
}
found = false;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/init_if.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:init,if,V:2.7-3.0
int test1(){
int err = 0;
srand(SEED);
int device_num = acc_get_device_num(acc_get_device_type());
#pragma acc init if(device_num == device_num)
return err;
}
#endif
#ifndef T2
//T2:init,if,V:2.7-3.0
int test2(){
int err = 0;
srand(SEED);
int device_num = acc_get_device_num(acc_get_device_type());
#pragma acc init if(device_num != device_num)
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
return failcode;
}
|
./openacc-vv/serial_loop_reduction_and_general.F90 | #ifndef T1
!T1:serial,reduction,combined-constructs,loop,V:2.6-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER:: errors
INTEGER:: x
LOGICAL,DIMENSION(LOOPCOUNT):: a
LOGICAL:: result, host_result
REAL(8),DIMENSION(LOOPCOUNT):: randoms
REAL(8):: false_margin = EXP(LOG(.5) / LOOPCOUNT)
errors = 0
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(randoms)
DO x = 1, LOOPCOUNT
IF (randoms(x) .lt. false_margin) THEN
a(x) = .TRUE.
ELSE
a(x) = .FALSE.
END IF
END DO
result = .TRUE.
!$acc data copyin(a(1:LOOPCOUNT))
!$acc serial loop reduction(.AND.:result)
DO x = 1, LOOPCOUNT
result = result .AND. a(x)
END DO
!$acc end data
host_result = .TRUE.
DO x = 1, LOOPCOUNT
host_result = host_result .AND. a(x)
END DO
IF (host_result .NEQV. result) THEN
errors = errors + 1
END IF
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/atomic_update_expr_divided_x.F90 | RECURSIVE FUNCTION IS_POSSIBLE(subset, destination, length, init) RESULT(POSSIBLE)
INTEGER, INTENT(IN) :: length
REAL(8),DIMENSION(length), INTENT(IN) :: subset
REAL(8), INTENT(IN) :: destination
REAL(8), INTENT(IN) :: init
REAL(8),ALLOCATABLE :: passed(:)
LOGICAL :: POSSIBLE
INTEGER :: x, y
IF (length .gt. 0) THEN
ALLOCATE(passed(length - 1))
ELSE
IF (abs(init - destination) .gt. PRECISION) THEN
POSSIBLE = .TRUE.
ELSE
POSSIBLE = .FALSE.
END IF
RETURN
END IF
POSSIBLE = .FALSE.
DO x = 1, length
DO y = 1, x - 1
passed(y) = subset(y)
END DO
DO y = x + 1, length
passed(y - 1) = subset(y)
END DO
IF (IS_POSSIBLE(passed, destination, length - 1, subset(x) / init)) THEN
POSSIBLE = .TRUE.
RETURN
END IF
END DO
END FUNCTION IS_POSSIBLE
#ifndef T1
!T1:construct-independent,atomic,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
REAL(8),DIMENSION(LOOPCOUNT, 10):: a !Data
REAL(8),DIMENSION(LOOPCOUNT):: totals
REAL(8),DIMENSION(10):: passed
INTEGER :: errors = 0
LOGICAL IS_POSSIBLE
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
totals = 1
!$acc data copyin(a(1:LOOPCOUNT, 1:10)) copy(totals(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
DO y = 1, 10
!$acc atomic update
totals(x) = a(x, y) / totals(x)
END DO
END DO
!$acc end parallel
!$acc end data
DO x = 1, LOOPCOUNT
DO y = 1, 10
passed(y) = a(x, y)
END DO
IF (IS_POSSIBLE(passed, totals(x), 10, 1) .eqv. .FALSE.) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./SPECaccel/benchspec/ACCEL/122.cfd/src/util.h | #ifndef _C_UTIL_
#define _C_UTIL_
#include <math.h>
#include <iostream>
#include <omp.h>
#ifdef _WIN32
#include <stdlib.h>
#ifdef __MINGW32__
#include <sys/time.h>
#else
#error "no supported time libraries are available on this platform"
#endif
#else
#include <sys/time.h>
#endif
#ifdef SPEC_ACCEL_WG_SIZE_0_0
#define BLOCK_SIZE_0 SPEC_ACCEL_WG_SIZE_0_0
#elif defined(SPEC_ACCEL_WG_SIZE_0)
#define BLOCK_SIZE_0 SPEC_ACCEL_WG_SIZE_0
#elif defined(SPEC_ACCEL_WG_SIZE)
#define BLOCK_SIZE_0 SPEC_ACCEL_WG_SIZE
#else
#define BLOCK_SIZE_0 192
#endif
#ifdef SPEC_ACCEL_WG_SIZE_1_0
#define BLOCK_SIZE_1 SPEC_ACCEL_WG_SIZE_1_0
#elif defined(SPEC_ACCEL_WG_SIZE_1)
#define BLOCK_SIZE_1 SPEC_ACCEL_WG_SIZE_1
#elif defined(SPEC_ACCEL_WG_SIZE)
#define BLOCK_SIZE_1 SPEC_ACCEL_WG_SIZE
#else
#define BLOCK_SIZE_1 192
#endif
#ifdef SPEC_ACCEL_WG_SIZE_2_0
#define BLOCK_SIZE_2 SPEC_ACCEL_WG_SIZE_2_0
#elif defined(SPEC_ACCEL_WG_SIZE_1)
#define BLOCK_SIZE_2 SPEC_ACCEL_WG_SIZE_2
#elif defined(SPEC_ACCEL_WG_SIZE)
#define BLOCK_SIZE_2 SPEC_ACCEL_WG_SIZE
#else
#define BLOCK_SIZE_2 192
#endif
#ifdef SPEC_ACCEL_WG_SIZE_3_0
#define BLOCK_SIZE_3 SPEC_ACCEL_WG_SIZE_3_0
#elif defined(SPEC_ACCEL_WG_SIZE_3)
#define BLOCK_SIZE_3 SPEC_ACCEL_WG_SIZE_3
#elif defined(SPEC_ACCEL_WG_SIZE)
#define BLOCK_SIZE_3 SPEC_ACCEL_WG_SIZE
#else
#define BLOCK_SIZE_3 192
#endif
#ifdef SPEC_ACCEL_WG_SIZE_1_0
#define BLOCK_SIZE_4 SPEC_ACCEL_WG_SIZE_4_0
#elif defined(SPEC_ACCEL_WG_SIZE_1)
#define BLOCK_SIZE_4 SPEC_ACCEL_WG_SIZE_4
#elif defined(SPEC_ACCEL_WG_SIZE)
#define BLOCK_SIZE_4 SPEC_ACCEL_WG_SIZE
#else
#define BLOCK_SIZE_4 192
#endif
using std::endl;
#ifdef _WIN32
double gettime() {
return 0;
}
#else
double gettime() {
struct timeval t;
gettimeofday(&t,NULL);
return t.tv_sec+t.tv_usec*1e-6;
}
#endif
//-------------------------------------------------------------------
//--initialize array with maximum limit
//-------------------------------------------------------------------
template<typename datatype>
void fill(datatype *A, const int n, const datatype maxi){
for (int j = 0; j < n; j++){
A[j] = ((datatype) maxi * (rand() / (RAND_MAX + 1.0f)));
}
}
//--print matrix
template<typename datatype>
void print_matrix(datatype *A, int height, int width){
for(int i=0; i<height; i++){
for(int j=0; j<width; j++){
int idx = i*width + j;
std::cout<<A[idx]<<" ";
}
std::cout<<std::endl;
}
return;
}
//-------------------------------------------------------------------
//--verify results
//-------------------------------------------------------------------
#define MAX_RELATIVE_ERROR .002
template<typename datatype>
void verify_array(const datatype *cpuResults, const datatype *gpuResults, const int size){
bool passed = true;
#pragma omp parallel for
for (int i=0; i<size; i++){
if (fabs(cpuResults[i] - gpuResults[i]) / cpuResults[i] > MAX_RELATIVE_ERROR){
passed = false;
}
}
if (passed){
std::cout << "--cambine:passed:-)" << std::endl;
}
else{
std::cout << "--cambine: failed:-(" << std::endl;
}
return ;
}
template<typename datatype>
void compare_results(const datatype *cpu_results, const datatype *gpu_results, const int size){
bool passed = true;
//#pragma omp parallel for
for (int i=0; i<size; i++){
if (cpu_results[i]!=gpu_results[i]){
passed = false;
}
}
if (passed){
std::cout << "--cambine:passed:-)" << std::endl;
}
else{
std::cout << "--cambine: failed:-(" << std::endl;
}
return ;
}
#endif
|
./openacc-vv/kernels_num_workers.c | #include "acc_testsuite.h"
#ifndef T1
//T1:kernels,loop,V:2.5-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * restrict a = (real_t *)malloc(n * sizeof(real_t));
real_t * restrict b = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n])
{
#pragma acc kernels loop num_workers(16)
for (int x = 0; x < n; ++x){
b[x] = a[x];
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - b[x]) > PRECISION){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/parallel_wait.c | #include "acc_testsuite.h"
#ifndef T1
//T1:parallel,wait,async,V:2.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = a[x];
}
#pragma acc enter data create(a[0:n])
#pragma acc update device(a[0:n]) async(1)
#pragma acc parallel present(a[0:n]) wait(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x){
a[x] += 1;
}
}
#pragma acc exit data copyout(a[0:n])
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (b[x] + 1)) > PRECISION){
err = 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/kernels_loop_reduction_or_vector_loop.F90 | #ifndef T1
!T1:kernels,private,reduction,combined-constructs,loop,V:1.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x, y !Iterators
LOGICAL,DIMENSION(10*LOOPCOUNT):: a !Data
LOGICAL,DIMENSION(10) :: b
LOGICAL :: temp
REAL(8),DIMENSION(10*LOOPCOUNT):: randoms
REAL(8) :: false_margin = exp(log(.5) / 2)
INTEGER :: errors = 0
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(randoms)
!Initilization
DO x = 1, 10 * LOOPCOUNT
IF (randoms(x) > false_margin) THEN
a(x) = .TRUE.
ELSE
a(x) = .FALSE.
END IF
END DO
!$acc data copyin(a(1:10*LOOPCOUNT)), copy(b(1:10))
!$acc kernels loop private(temp)
DO x = 0, 9
temp = .FALSE.
!$acc loop vector reduction(.OR.:temp)
DO y = 1, LOOPCOUNT
temp = temp .OR. a(x * LOOPCOUNT + y)
END DO
b(x + 1) = temp
END DO
!$acc end data
DO x = 0, 9
temp = .FALSE.
DO y = 1, LOOPCOUNT
temp = temp .OR. a(x * LOOPCOUNT + y)
END DO
IF (temp .neqv. b(x + 1)) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/acc_deviceptr.c | #include "acc_testsuite.h"
#ifndef T1
//T1:runtime,data,executable-data,construct-independent,V:2.0-2.7
int test1(){
int err = 0;
real_t *a = (real_t *)malloc(n * sizeof(real_t));
real_t *b = (real_t *)malloc(n * sizeof(real_t));
real_t *c = (real_t *)malloc(n * sizeof(real_t));
real_t *a_ptr;
real_t *b_ptr;
real_t *c_ptr;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
#pragma acc enter data copyin(a[0:n], b[0:n]) create(c[0:n])
a_ptr = acc_deviceptr(a);
b_ptr = acc_deviceptr(b);
c_ptr = acc_deviceptr(c);
#pragma acc data deviceptr(a_ptr, b_ptr, c_ptr)
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c_ptr[x] = a_ptr[x] + b_ptr[x];
}
}
}
#pragma acc exit data copyout(c[0:n]) delete(a[0:n], b[0:n])
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (a[x] + b[x])) > PRECISION){
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
return failcode;
}
|
./openacc-vv/shutdown_device_type_num.F90 | #ifndef T1
!T1:runtime,construct-independent,internal-control-values,shutdown,nonvalidating,V:2.5-3.2
LOGICAL FUNCTION test1()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: device_num
INTEGER :: device_type
INTEGER :: errors = 0
device_type = acc_get_device_type()
device_num = acc_get_device_num(device_type)
!$acc shutdown device_type(host) device_num(device_num)
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
#ifndef T2
!T2:runtime,construct-independent,internal-control-values,shutdown,nonvalidating,V:2.5-3.2
LOGICAL FUNCTION test2()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: device_num
INTEGER :: device_type
INTEGER :: errors = 0
device_type = acc_get_device_type()
device_num = acc_get_device_num(device_type)
!$acc shutdown device_type(multicore) device_num(device_num)
IF (errors .eq. 0) THEN
test2 = .FALSE.
ELSE
test2 = .TRUE.
END IF
END
#endif
#ifndef T3
!T3:runtime,construct-independent,internal-control-values,shutdown,nonvalidating,V:2.5-3.2
LOGICAL FUNCTION test3()
USE OPENACC
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: device_num
INTEGER :: device_type
INTEGER :: errors = 0
device_type = acc_get_device_type()
device_num = acc_get_device_num(device_type)
!$acc shutdown device_type(default) device_num(device_num)
IF (errors .eq. 0) THEN
test3 = .FALSE.
ELSE
test3 = .TRUE.
END IF
END
#endif
PROGRAM shutdown_device_type_num
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
#ifndef T2
LOGICAL :: test2
#endif
#ifndef T3
LOGICAL :: test3
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
#ifndef T2
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test2()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 1
failed = .FALSE.
END IF
#endif
#ifndef T3
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test3()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 2
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/declare_copyin.cpp | #define DECLARE_TEST
#define DECLARE_COPYIN
int mult_copyin = 2;
#include "acc_testsuite_declare.h"
#include "acc_testsuite.h"
#pragma acc declare copyin(fixed_size_array)
#pragma acc declare copyin(scalar)
#pragma acc declare copyin(datapointer)
#pragma acc declare copyin(n)
#pragma acc routine vector
void multiplyData(real_t *a){
#pragma acc loop vector
for (int x = 0; x < n; ++x){
a[x] = a[x] * 2;
}
}
#ifndef T1
//T1:declare,construct-independent,V:1.0-2.7
int test1(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
int mult = 2;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n]) present(fixed_size_array)
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x] + fixed_size_array[x%10];
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(b[x] - (a[x] + fixed_size_array[x%10])) > PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
#ifndef T2
//T2:declare,construct-independent,V:1.0-2.7
int test2(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
int mult = 2;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = 0;
}
#pragma acc data copyin(a[0:n]) copyout(b[0:n]) present(scalar)
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
b[x] = a[x] + scalar;
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(b[x] - (a[x] + scalar)) > PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
#ifndef T3
//T3:declare,construct-independent,V:2.0-2.7
int test3(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
int mult = 2;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = a[x];
}
#pragma acc data copy(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < 1; ++x){
extern_multiplyData_copyin(a, n);
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (b[x] * 2)) > PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
#ifndef T4
//T4:declare,construct-independent,V:2.0-2.7
int test4(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
int mult = 2;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = a[x];
}
#pragma acc data copy(a[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < 1; ++x){
multiplyData(a);
}
}
}
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (b[x] * 2)) > PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
#ifndef T5
//T5:declare,construct-independent,attach,V:2.6-2.7
int test5(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
int mult = 2;
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = a[x];
}
datapointer = a;
#pragma acc enter data copyin(a[0:n]) attach(datapointer)
#pragma acc data present(datapointer[0:n])
{
#pragma acc parallel
{
#pragma acc loop
for (int x = 0; x < n; ++x){
datapointer[x] = datapointer[x] * 2;
}
}
}
#pragma acc exit data copyout(a[0:n])
for (int x = 0; x < n; ++x){
if (fabs(a[x] - (b[x] * 2)) > PRECISION){
err += 1;
break;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
#ifndef T3
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test3();
}
if (failed != 0){
failcode = failcode + (1 << 2);
}
#endif
#ifndef T4
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test4();
}
if (failed != 0){
failcode = failcode + (1 << 3);
}
#endif
#ifndef T5
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test5();
}
if (failed != 0){
failcode = failcode + (1 << 4);
}
#endif
return failcode;
}
|
./openacc-vv/enter_data_copyin_no_lower_bound.F90 | #ifndef T1
!T1:data,executable-data,construct-independent,V:2.0-2.7
LOGICAL FUNCTION test1()
IMPLICIT NONE
INCLUDE "acc_testsuite.Fh"
INTEGER :: x !Iterators
REAL(8),DIMENSION(LOOPCOUNT):: a, b, c !Data
INTEGER :: errors = 0
!Initilization
SEEDDIM(1) = 1
# ifdef SEED
SEEDDIM(1) = SEED
# endif
CALL RANDOM_SEED(PUT=SEEDDIM)
CALL RANDOM_NUMBER(a)
CALL RANDOM_NUMBER(b)
c = 0
!$acc enter data copyin(a(:LOOPCOUNT), b(:LOOPCOUNT))
!$acc data copyout(c(1:LOOPCOUNT)) present(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
!$acc parallel
!$acc loop
DO x = 1, LOOPCOUNT
c(x) = a(x) + b(x)
END DO
!$acc end parallel
!$acc end data
!$acc exit data delete(a(1:LOOPCOUNT), b(1:LOOPCOUNT))
DO x = 1, LOOPCOUNT
IF (abs(c(x) - (a(x) + b(x))) .gt. PRECISION) THEN
errors = errors + 1
END IF
END DO
IF (errors .eq. 0) THEN
test1 = .FALSE.
ELSE
test1 = .TRUE.
END IF
END
#endif
PROGRAM main
IMPLICIT NONE
INTEGER :: failcode, testrun
LOGICAL :: failed
INCLUDE "acc_testsuite.Fh"
#ifndef T1
LOGICAL :: test1
#endif
failed = .FALSE.
failcode = 0
#ifndef T1
DO testrun = 1, NUM_TEST_CALLS
failed = failed .or. test1()
END DO
IF (failed) THEN
failcode = failcode + 2 ** 0
failed = .FALSE.
END IF
#endif
CALL EXIT (failcode)
END PROGRAM
|
./openacc-vv/acc_copyout_async.cpp | #include "acc_testsuite.h"
#ifndef T1
//T1:runtime,data,executable-data,async,construct-independent,V:2.5-2.7
int test1(){
int err = 0;
srand(SEED);
real_t *a = new real_t[n];
real_t *b = new real_t[n];
real_t *c = new real_t[n];
real_t *d = new real_t[n];
real_t *e = new real_t[n];
real_t *f = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
d[x] = rand() / (real_t)(RAND_MAX / 10);
e[x] = rand() / (real_t)(RAND_MAX / 10);
f[x] = 0;
}
#pragma acc enter data create(c[0:n], f[0:n])
#pragma acc data copyin(a[0:n], b[0:n], d[0:n], e[0:n])
{
#pragma acc parallel async(1) present(c[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
c[x] = a[x] + b[x];
}
}
#pragma acc parallel async(2) present(f[0:n])
{
#pragma acc loop
for (int x = 0; x < n; ++x){
f[x] = d[x] + e[x];
}
}
acc_copyout_async(c, n * sizeof(real_t), 1);
acc_copyout_async(f, n * sizeof(real_t), 2);
#pragma acc wait
}
for (int x = 0; x < n; ++x){
if (fabs(c[x] - (a[x] + b[x])) > PRECISION){
err += 1;
}
if (fabs(f[x] - (d[x] + e[x])) > PRECISION){
err += 1;
}
}
return err;
}
#endif
#ifndef T2
//T2:runtime,async,data,executable-data,internal-control-values,construct-independent,V:2.5-2.7
int test2(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
int def_async_var = acc_get_default_async();
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
#pragma acc enter data create(c[0:n])
#pragma acc data copyin(a[0:n], b[0:n])
{
#pragma acc parallel present(c[0:n]) async
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] = a[x] + b[x];
}
}
acc_copyout_async(c, n * sizeof(real_t), def_async_var);
#pragma acc wait
}
for (int x = 0; x < n; ++x) {
if (fabs(c[x] - (a[x] + b[x])) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
#ifndef T3
//T3:runtime,async,data,executable-data,internal-control-values,construct-independent,V:2.5-2.7
int test3(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
int def_async_var = acc_get_default_async();
acc_set_default_async(def_async_var + 1);
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
#pragma acc enter data create(c[0:n])
#pragma acc data copyin(a[0:n], b[0:n])
{
#pragma acc parallel present(c[0:n]) async
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] = a[x] + b[x];
}
}
acc_copyout_async(c, n * sizeof(real_t), def_async_var + 1);
#pragma acc wait
}
for (int x = 0; x < n; ++x) {
if (fabs(c[x] - (a[x] + b[x])) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
#ifndef T4
//T4:runtime,async,data,executable-data,construct-independent,V:2.5-2.7
int test4(){
int err = 0;
srand(SEED);
real_t * a = new real_t[n];
real_t * b = new real_t[n];
real_t * c = new real_t[n];
for (int x = 0; x < n; ++x){
a[x] = rand() / (real_t)(RAND_MAX / 10);
b[x] = rand() / (real_t)(RAND_MAX / 10);
c[x] = 0;
}
#pragma acc enter data create(c[0:n])
#pragma acc data copyin(a[0:n], b[0:n])
{
#pragma acc parallel present(c[0:n]) async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] = a[x] + b[x];
}
}
#pragma acc enter data copyin(c[0:n])
acc_copyout_async(c, n * sizeof(real_t), 1);
#pragma acc parallel present(c[0:n]) async(1)
{
#pragma acc loop
for (int x = 0; x < n; ++x) {
c[x] += a[x] + b[x];
}
}
acc_copyout_async(c, n * sizeof(real_t), 1);
}
for (int x = 0; x < n; ++x) {
if (fabs(c[x] - (2 * (a[x] + b[x]))) > PRECISION) {
err += 1;
}
}
return err;
}
#endif
int main(){
int failcode = 0;
int failed;
#ifndef T1
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test1();
}
if (failed != 0){
failcode = failcode + (1 << 0);
}
#endif
#ifndef T2
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test2();
}
if (failed != 0){
failcode = failcode + (1 << 1);
}
#endif
#ifndef T3
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test3();
}
if (failed != 0){
failcode = failcode + (1 << 2);
}
#endif
#ifndef T4
failed = 0;
for (int x = 0; x < NUM_TEST_CALLS; ++x){
failed = failed + test4();
}
if (failed != 0){
failcode = failcode + (1 << 3);
}
#endif
return failcode;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.