source
stringlengths
3
92
c
stringlengths
26
2.25M
ex01.c
/* Copyright (c) 2019 CSC Training */ /* Copyright (c) 2021 ENCCS */ #include <stdio.h> #include <math.h> #define NX 102400 int main(void) { double vecA[NX],vecB[NX],vecC[NX]; double r=0.2; /* Initialization of vectors */ for (int i = 0; i < NX; i++) { vecA[i] = pow(r, i); vecB[i] = 1.0; } /* dot product of two vectors */ #pragma omp target for (int i = 0; i < NX; i++) { vecC[i] = vecA[i] * vecB[i]; } double sum = 0.0; /* calculate the sum */ for (int i = 0; i < NX; i++) { sum += vecC[i]; } printf("The sum is: %8.6f \n", sum); return 0; }
kmp_atomic_cas.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdbool.h> #include <omp.h> #ifdef __cplusplus extern "C" { #endif typedef void* ident_t; extern bool __kmpc_atomic_bool_1_cas(ident_t *loc, int gtid, char *x, char e, char d); extern bool __kmpc_atomic_bool_2_cas(ident_t *loc, int gtid, short *x, short e, short d); extern bool __kmpc_atomic_bool_4_cas(ident_t *loc, int gtid, int *x, int e, int d); extern bool __kmpc_atomic_bool_8_cas(ident_t *loc, int gtid, long long *x, long long e, long long d); extern char __kmpc_atomic_val_1_cas(ident_t *loc, int gtid, char *x, char e, char d); extern short __kmpc_atomic_val_2_cas(ident_t *loc, int gtid, short *x, short e, short d); extern int __kmpc_atomic_val_4_cas(ident_t *loc, int gtid, int *x, int e, int d); extern long long __kmpc_atomic_val_8_cas(ident_t *loc, int gtid, long long *x, long long e, long long d); #ifdef __cplusplus } #endif int main() { int ret = 0; bool r; char c0 = 1; char c1 = 2; char c2 = 3; char co = 2; char cc = 0; short s0 = 11; short s1 = 12; short s2 = 13; short so = 12; short sc = 0; int i0 = 211; int i1 = 212; int i2 = 213; int io = 212; int ic = 0; long long l0 = 3111; long long l1 = 3112; long long l2 = 3113; long long lo = 3112; long long lc = 0; // initialize OpenMP runtime library omp_set_dynamic(0); // #pragma omp atomic compare update capture // { r = x == e; if(r) { x = d; } } // char, co == c1 initially, co == c2 finally r = __kmpc_atomic_bool_1_cas(NULL, 0, &co, c0, c2); // no-op if (co != c1) { ret++; printf("Error bool_1_cas no-op: %d != %d\n", co, c1); } if (r) { ret++; printf("Error bool_1_cas no-op ret: %d\n", r); } r = __kmpc_atomic_bool_1_cas(NULL, 0, &co, c1, c2); if (co != c2) { ret++; printf("Error bool_1_cas: %d != %d\n", co, c2); } if (!r) { ret++; printf("Error bool_1_cas ret: %d\n", r); } // short r = __kmpc_atomic_bool_2_cas(NULL, 0, &so, s0, s2); // no-op if (so != s1) { ret++; printf("Error bool_2_cas no-op: %d != %d\n", so, s1); } if (r) { ret++; printf("Error bool_2_cas no-op ret: %d\n", r); } r = __kmpc_atomic_bool_2_cas(NULL, 0, &so, s1, s2); if (so != s2) { ret++; printf("Error bool_2_cas: %d != %d\n", so, s2); } if (!r) { ret++; printf("Error bool_2_cas ret: %d\n", r); } // int r = __kmpc_atomic_bool_4_cas(NULL, 0, &io, i0, i2); // no-op if (io != i1) { ret++; printf("Error bool_4_cas no-op: %d != %d\n", io, i1); } if (r) { ret++; printf("Error bool_4_cas no-op ret: %d\n", r); } r = __kmpc_atomic_bool_4_cas(NULL, 0, &io, i1, i2); if (io != i2) { ret++; printf("Error bool_4_cas: %d != %d\n", io, i2); } if (!r) { ret++; printf("Error bool_4_cas ret: %d\n", r); } // long long r = __kmpc_atomic_bool_8_cas(NULL, 0, &lo, l0, l2); // no-op if (lo != l1) { ret++; printf("Error bool_8_cas no-op: %lld != %lld\n", lo, l1); } if (r) { ret++; printf("Error bool_8_cas no-op ret: %d\n", r); } r = __kmpc_atomic_bool_8_cas(NULL, 0, &lo, l1, l2); if (lo != l2) { ret++; printf("Error bool_8_cas: %lld != %lld\n", lo, l2); } if (!r) { ret++; printf("Error bool_8_cas ret: %d\n", r); } // #pragma omp atomic compare update capture // { v = x; if (x == e) { x = d; } } // char, co == c2 initially, co == c1 finally cc = __kmpc_atomic_val_1_cas(NULL, 0, &co, c0, c1); // no-op if (co != c2) { ret++; printf("Error val_1_cas no-op: %d != %d\n", co, c2); } if (cc != c2) { ret++; printf("Error val_1_cas no-op ret: %d != %d\n", cc, c2); } cc = __kmpc_atomic_val_1_cas(NULL, 0, &co, c2, c1); if (co != c1) { ret++; printf("Error val_1_cas: %d != %d\n", co, c1); } if (cc != c2) { ret++; printf("Error val_1_cas ret: %d != %d\n", cc, c2); } // short sc = __kmpc_atomic_val_2_cas(NULL, 0, &so, s0, s1); // no-op if (so != s2) { ret++; printf("Error val_2_cas no-op: %d != %d\n", so, s2); } if (sc != s2) { ret++; printf("Error val_2_cas no-op ret: %d != %d\n", sc, s2); } sc = __kmpc_atomic_val_2_cas(NULL, 0, &so, s2, s1); if (so != s1) { ret++; printf("Error val_2_cas: %d != %d\n", so, s1); } if (sc != s2) { ret++; printf("Error val_2_cas ret: %d != %d\n", sc, s2); } // int ic = __kmpc_atomic_val_4_cas(NULL, 0, &io, i0, i1); // no-op if (io != i2) { ret++; printf("Error val_4_cas no-op: %d != %d\n", io, i2); } if (ic != i2) { ret++; printf("Error val_4_cas no-op ret: %d != %d\n", ic, i2); } ic = __kmpc_atomic_val_4_cas(NULL, 0, &io, i2, i1); if (io != i1) { ret++; printf("Error val_4_cas: %d != %d\n", io, i1); } if (ic != i2) { ret++; printf("Error val_4_cas ret: %d != %d\n", ic, i2); } // long long lc = __kmpc_atomic_val_8_cas(NULL, 0, &lo, l0, l1); // no-op if (lo != l2) { ret++; printf("Error val_8_cas no-op: %lld != %lld\n", lo, l2); } if (lc != l2) { ret++; printf("Error val_8_cas no-op ret: %lld != %lld\n", lc, l2); } lc = __kmpc_atomic_val_8_cas(NULL, 0, &lo, l2, l1); if (lo != l1) { ret++; printf("Error val_8_cas: %lld != %lld\n", lo, l1); } if (lc != l2) { ret++; printf("Error val_8_cas ret: %lld != %lld\n", lc, l2); } // check in parallel i0 = 1; i1 = 0; for (io = 0; io < 5; ++io) { #pragma omp parallel num_threads(2) private(i2, ic, r) { if (omp_get_thread_num() == 0) { // th0 waits for th1 to increment i1, then th0 increments i0 #pragma omp atomic read i2 = i1; ic = __kmpc_atomic_val_4_cas(NULL, 0, &i0, i2, i2 + 1); while(ic != i2) { #pragma omp atomic read i2 = i1; ic = __kmpc_atomic_val_4_cas(NULL, 0, &i0, i2, i2 + 1); } } else { // th1 increments i1 if it is equal to i0 - 1, letting th0 to proceed r = 0; while(!r) { #pragma omp atomic read i2 = i0; r = __kmpc_atomic_bool_4_cas(NULL, 0, &i1, i2 - 1, i2); } } } } if (i0 != 6 || i1 != 5) { ret++; printf("Error in parallel, %d != %d or %d != %d\n", i0, 6, i1, 5); } if (ret == 0) printf("passed\n"); return ret; }
GB_binop__le_fp64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_mkl.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__le_fp64 // A.*B function (eWiseMult): GB_AemultB__le_fp64 // A*D function (colscale): GB_AxD__le_fp64 // D*A function (rowscale): GB_DxB__le_fp64 // C+=B function (dense accum): GB_Cdense_accumB__le_fp64 // C+=b function (dense accum): GB_Cdense_accumb__le_fp64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__le_fp64 // C=scalar+B GB_bind1st__le_fp64 // C=scalar+B' GB_bind1st_tran__le_fp64 // C=A+scalar GB_bind2nd__le_fp64 // C=A'+scalar GB_bind2nd_tran__le_fp64 // C type: bool // A type: double // B,b type: double // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = (x <= y) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LE || GxB_NO_FP64 || GxB_NO_LE_FP64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__le_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__le_fp64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__le_fp64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type double double bwork = (*((double *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__le_fp64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__le_fp64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *GB_RESTRICT Cx = (bool *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB_AaddB__le_fp64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_add_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__le_fp64 ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__le_fp64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double bij = Bx [p] ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__le_fp64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; Cx [p] = (aij <= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB_bind1st_tran__le_fp64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = Ax [pA] ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB_bind2nd_tran__le_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double y = (*((const double *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
lake.c
/************************************* * lake.c * * Models pebbles on a lake * Description: * * This program uses centered finite differencing to * solve the wave equation with sources. * * The interface is given as * * lake [grid_size] [# of pebbles] [end time] [# threads] * * where * * grid_size - integer, size of one edge of the square grid; * so the true size of the computational grid will * be grid_size * grid_size * * # of pebbles - number of simulated "pebbles" to start with * * end time - the simulation starts from t=0.0 and goes to * t=[end time] * * # threads - the number of threads the simulation uses * **************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <sys/time.h> #include "omp.h" #include "./lake.h" #include "./lake_util.h" /* Probably not necessary but doesn't hurt */ #define _USE_MATH_DEFINES int main(int argc, char *argv[]) { if(argc != 5) { fprintf(stdout, "Usage: %s npoints npebs time_finish nthreads \n",argv[0]); return 0; } /* grab the arguments and setup some vars */ int npoints = atoi(argv[1]); int npebs = atoi(argv[2]); double end_time = (double)atof(argv[3]); int nthreads = atoi(argv[4]); int narea = npoints * npoints; /* check input params for resitrictions */ if ( npoints % nthreads != 0 ) { fprintf(stderr, "BONK! npoints must be evenly divisible by nthreads\n Try again!"); return 0; } /* get the program directory */ set_wrkdir(argv[0]); /* main simulation arrays */ double *u_i0, *u_i1; double *u_cpu, *pebs; /* u_err is used when calculating the * error between one version of the code * and another. */ double *u_err; /* h is the size of each grid cell */ double h; /* used for error analysis */ double avgerr; /* used for time analysis */ double elapsed_cpu; struct timeval cpu_start, cpu_end; /* allocate arrays */ u_i0 = (double*)malloc(sizeof(double) * narea); u_i1 = (double*)malloc(sizeof(double) * narea); pebs = (double*)malloc(sizeof(double) * narea); u_cpu = (double*)malloc(sizeof(double) * narea); start_lake_log("lake.log"); lake_log("running %s with (%d x %d) grid, until %f, with %d threads\n", argv[0], npoints, npoints, end_time, nthreads); /* initialize the simulation */ h = (XMAX - XMIN)/npoints; lake_log("grid step size is %f\n",h); #ifdef __DEBUG lake_log("initializing pebbles\n"); #endif init_pebbles(pebs, npebs, npoints); #ifdef __DEBUG lake_log("initializing u0, u1\n"); #endif init(u_i0, pebs, npoints); init(u_i1, pebs, npoints); /* print the initial configuration */ #ifdef __DEBUG lake_log("printing initial configuration file\n"); #endif print_heatmap("lake_i.dat", u_i0, npoints, h); /* time, run the simulation */ #ifdef __DEBUG lake_log("beginning simulation\n"); #endif gettimeofday(&cpu_start, NULL); run_sim(u_cpu, u_i0, u_i1, pebs, npoints, h, end_time, nthreads); gettimeofday(&cpu_end, NULL); elapsed_cpu = ((cpu_end.tv_sec + cpu_end.tv_usec * 1e-6)-( cpu_start.tv_sec + cpu_start.tv_usec * 1e-6)); lake_log("\nSimulation took %f seconds\n", elapsed_cpu); printf("Simulation took %f seconds\n", elapsed_cpu); /* print the final configuration */ #ifdef __DEBUG lake_log("printing final configuration file\n"); #endif print_heatmap("lake_f.dat", u_cpu, npoints, h); #ifdef __DEBUG lake_log("freeing memory\n"); #endif /* free memory */ free(u_i0); free(u_i1); free(pebs); free(u_cpu); stop_lake_log(); return 1; } /***************************** * run_sim * * Input * ---------- * double *u0 - the inital configuation * double *u1 - the intial + 1 configuration * double *pebbles - the array of pebbles * int n - the grid size * double h - the grid step size * double end_time - the final time * int nthreads - the number of threads to use * * Output * ---------- * double *u - the final configuration * * Description * ---------- * run_sim is the main driver of the program. It takes in the inital * configuration and parameters, and runs them until end_time is reached. * *******************************/ void run_sim(double *u, double *u0, double *u1, double *pebbles, int n, double h, double end_time, int nthreads) { /* arrays used in the calculation */ double un[n][n], uc[n][n], uo[n][n], pebs[n][n]; /* time vars */ double t, dt; int i, j; /* allocate the calculation arrays */ /* put the inital configurations into the calculation arrays */ memcpy(uo, u0, sizeof(double) * n * n); memcpy(uc, u1, sizeof(double) * n * n); memcpy(pebs, pebbles, sizeof(double) * n * n); /* start at t=0.0 */ t = 0.; /* this is probably not ideal. In principal, we should * keep the time-step at the size determined by the * CFL condition * * dt = h / vel_max * * where vel_max is the maximum velocity in the current * model. The condition dt = h/2. should suffice, but * be aware the possibility exists for madness and mayhem */ dt = h / 2.; /* loop until time >= end_time */ omp_set_num_threads(nthreads); printf("OpenMP running on %d threads\n", omp_get_max_threads()); #pragma opm parallel num_threads(nthreads) while(1) { /* run a central finite differenmcing scheme to solve * the wave equation in 2D */ #pragma omp parallel for schedule(static) private(i) shared(n) for( i = 0; i < n; i++) { #pragma omp parallel for schedule(static) shared(un, uc, uo, pebs, n) private(j) for( j = 0; j < n; j++) { /* impose the u|_s = 0 boundary conditions */ if( i == 0 || i == n - 1 || j == 0 || j == n - 1) { un[i][j] = 0.; } /* otherwise do the FD scheme */ else { un[i][j] = 2*uc[i][j] - uo[i][j] + VSQR *(dt * dt) *((uc[i][j-1] + uc[i][j+1] + uc[i+1][j] + uc[i-1][j] + 0.25 * (uc[i-1][j-1] + uc[i+1][j-1]+ uc[i-1][j+1] + uc[i+1][j+1]) - 5 * uc[i][j])/(h * h) + f(pebs[i][j],t)); } } } #pragma omp parallel for schedule(static) private(i) shared(n) /* update the calculation arrays for the next time step */ for( i = 0; i < n; i++ ) { #pragma omp parallel for schedule(static) private(j) shared(n, un, uc, uo) for ( j = 0; j < n; j++ ) { uo[i][j] = uc[i][j]; uc[i][j] = un[i][j]; } } /* have we reached the end? */ if(!tpdt(&t,dt,end_time)) break; } /* cpy the last updated to the output array */ memcpy(u, un, sizeof(double) * n * n); } /***************************** * init_pebbles * * Input * ---------- * int pn - the number of pebbles * int n - the grid size * * Output * ---------- * double *p - an array (dimensioned same as the grid) that * gives the inital pebble size. * * Description * ---------- * init_pebbles creates a random scattering of some pn pebbles, * along with a random size. The range of the can be adjusted by changing * the constant MAX_PSZ. * *******************************/ void init_pebbles(double *p, int pn, int n) { int i, j, k, idx; int sz; srand( time(NULL) ); /* set to zero */ memset(p, 0, sizeof(double) * n * n); for( k = 0; k < pn ; k++ ) { /* the offset is to ensure that no pebbles * are spawned on the very edge of the grid */ i = rand() % (n - 4) + 2; j = rand() % (n - 4) + 2; sz = rand() % MAX_PSZ; idx = j + i * n; p[idx] = (double) sz; } } /***************************** * f * * Input * ---------- * double p - the inital pebble value * double t - the current time * Returns * ---------- * the value of the "pebble" source term at time t * * Description * ---------- * Each pebbles influance on the surface will "fade" as * time marches forward (they may sink away, for instance). * This function models that - at large t ("large" defined * relative to the constant TSCALE) the pebble will have * little to no effect. * * NB: this function can be updated to model whatever behavior * you wish the pebbles to have - they could continually jump * up and down on the surface, driving more energic waves, for * example. ******************************/ double f(double p, double t) { return -expf(-TSCALE * t) * p; } int tpdt(double *t, double dt, double tf) { if((*t) + dt > tf) return 0; (*t) = (*t) + dt; return 1; } void init(double *u, double *pebbles, int n) { int i, j, idx; for(i = 0; i < n ; i++) { for(j = 0; j < n ; j++) { idx = j + i * n; u[idx] = f(pebbles[idx], 0.0); } } } /***************************** * error_u * * Input * ---------- * double *ua - error 1 * double *ub - error 2 * int n - array extent * * Output * ---------- * double *uerr - array of errors * double *avgerr - pointer to the average error * * Description * ---------- * Calculates the relative error between ua and ub * ********************************/ void error_u(double *uerr, double *avgerr, double *ua, double *ub, int n) { int i, j, idx; (*avgerr) = 0.; for (i = 0; i < n; i++ ) { for (j = 0; j < n; j++ ) { idx = j + i * n; uerr[idx] = fabs((ua[idx]-ub[idx])/ua[idx]); (*avgerr) = (*avgerr) * ((double)idx/(double)(idx + 1)) + uerr[idx] / (double)(idx + 1); } } } /***************************** * print_heatmap * * Input * ---------- * char *filename - the output file name * double *u - the array to output * int n - the edge extent of u (ie, u is (n x n) * double h - the step size in u * Output * ---------- * None * * Description * ---------- * Outputs the array u to the file filename ********************************/ void print_heatmap(char *filename, double *u, int n, double h) { char full_filename[64]; int i, j, idx; dir_string(filename, full_filename); FILE *fp = fopen(full_filename, "w"); for( i = 0; i < n; i++ ) { for( j = 0; j < n; j++ ) { idx = j + i * n; fprintf(fp, "%f %f %f\n", i*h, j*h, u[idx]); } } fclose(fp); }
mixed_tentusscher_myo_epi_2004_S1_6.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S1_6.h" GET_CELL_MODEL_DATA(init_cell_model_data) { if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { static bool first_call = true; if(first_call) { print_to_stdout_and_file("Using mixed version of TenTusscher 2004 myocardium + epicardium CPU model\n"); first_call = false; } // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } // Initial conditions for TenTusscher myocardium if (mapping[sv_id] == 0) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.3965119057144,0.00133824305081220,0.775463576993407,0.775278393595599,0.000179499343643571,0.483303039835057,0.00297647859235379,0.999998290403642,1.98961879737287e-08,1.93486789479597e-05,0.999599147019885,1.00646342475688,0.999975178010127,5.97703651642618e-05,0.418325344820368,10.7429775420171,138.918155900633}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } // Initial conditions for TenTusscher epicardium else { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.6064669642929,0.00127958647137661,0.780646393787312,0.780487891408514,0.000173584624633959,0.485487828596219,0.00293230969261734,0.999998360971933,1.92121849077563e-08,1.88145674866789e-05,0.999776948081716,1.00718539597045,0.999996533595373,4.30563502204742e-05,0.716390886105942,9.21744894085960,140.245419902480}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { // Get the mapping array uint32_t *mapping = NULL; if(extra_data) { mapping = (uint32_t*)extra_data; } else { print_to_stderr_and_file_and_exit("You need to specify a mask function when using a mixed model!\n"); } uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = (uint32_t )i; for (int j = 0; j < num_steps; ++j) { if (mapping[i] == 0) solve_model_ode_cpu_myo(dt, sv + (sv_id * NEQ), stim_currents[i]); else solve_model_ode_cpu_epi(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu_myo (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_myo(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_myo(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Myocardium cell real Gks=0.062; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Myocardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; Irel=A*sd*sg; Ileak=0.00008f*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; // [!] Myocardium cell R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; } void solve_model_ode_cpu_epi (real dt, real *sv, real stim_current) { real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu_epi(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu_epi(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; // [!] Epicardium cell real Gks=0.245; //Parameters for Ik1 real GK1=5.405; //Parameters for Ito // [!] Epicardium cell real Gto=0.294; //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={13.9565782218666,0.000287174371586985,0.000141340119238607,0.000581300894818177,0.247996276322519,0.183526744381808,0.0916439019365131,3.36936874118326,0.0142522777756354,2.50047611779782,1098.80622386062,0.000523336135399631,0.308744870110979,0.0177121653217909,0.00514911951229914,2.73381165333318e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); //TAU_F=1125*exp(-(svolt+27)*(svolt+27)/300)+80+165/(1.+exp((25-svolt)/10)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); // Updated from CellML FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
kmp_sch_simd_runtime_guided.c
// RUN: %libomp-compile // RUN: env OMP_SCHEDULE=guided %libomp-run // RUN: env OMP_SCHEDULE=guided,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=guided,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=dynamic %libomp-run // RUN: env OMP_SCHEDULE=dynamic,1 %libomp-run 1 // RUN: env OMP_SCHEDULE=dynamic,2 %libomp-run 2 // RUN: env OMP_SCHEDULE=auto %libomp-run // The test checks schedule(simd:runtime) // in combination with OMP_SCHEDULE=guided[,chunk] #include <stdio.h> #include <stdlib.h> #include <omp.h> #if defined(WIN32) || defined(_WIN32) #include <windows.h> #define delay() Sleep(1); #define seten(a,b,c) _putenv_s((a),(b)) #else #include <unistd.h> #define delay() usleep(10); #define seten(a,b,c) setenv((a),(b),(c)) #endif #define UBOUND 100 #define SIMD_LEN 4 int err = 0; // --------------------------------------------------------------------------- // Various definitions copied from OpenMP RTL. enum sched { kmp_sch_static_balanced_chunked = 45, kmp_sch_guided_simd = 46, kmp_sch_runtime_simd = 47, }; typedef unsigned u32; typedef long long i64; typedef unsigned long long u64; typedef struct { int reserved_1; int flags; int reserved_2; int reserved_3; char *psource; } id; #ifdef __cplusplus extern "C" { #endif int __kmpc_global_thread_num(id*); void __kmpc_barrier(id*, int gtid); void __kmpc_dispatch_init_4(id*, int, enum sched, int, int, int, int); void __kmpc_dispatch_init_8(id*, int, enum sched, i64, i64, i64, i64); int __kmpc_dispatch_next_4(id*, int, void*, void*, void*, void*); int __kmpc_dispatch_next_8(id*, int, void*, void*, void*, void*); #ifdef __cplusplus } // extern "C" #endif // End of definitions copied from OpenMP RTL. // --------------------------------------------------------------------------- static id loc = {0, 2, 0, 0, ";file;func;0;0;;"}; // --------------------------------------------------------------------------- void run_loop( int loop_lb, // Loop lower bound. int loop_ub, // Loop upper bound. int loop_st, // Loop stride. int lchunk ) { static int volatile loop_sync = 0; int lb; // Chunk lower bound. int ub; // Chunk upper bound. int st; // Chunk stride. int rc; int tid = omp_get_thread_num(); int gtid = __kmpc_global_thread_num(&loc); int last; int tc = (loop_ub - loop_lb) / loop_st + 1; int ch; int no_chunk = 0; if (lchunk == 0) { no_chunk = 1; lchunk = 1; } ch = lchunk * SIMD_LEN; #if _DEBUG > 1 printf("run_loop gtid %d tid %d (lb=%d, ub=%d, st=%d, ch=%d)\n", gtid, tid, (int)loop_lb, (int)loop_ub, (int)loop_st, lchunk); #endif // Don't test degenerate cases that should have been discovered by codegen. if (loop_st == 0) return; if (loop_st > 0 ? loop_lb > loop_ub : loop_lb < loop_ub) return; __kmpc_dispatch_init_4(&loc, gtid, kmp_sch_runtime_simd, loop_lb, loop_ub, loop_st, SIMD_LEN); { // Let the master thread handle the chunks alone. int chunk; // No of current chunk. int last_ub; // Upper bound of the last processed chunk. u64 cur; // Number of interations in current chunk. u64 max; // Max allowed iterations for current chunk. int undersized = 0; last_ub = loop_ub; chunk = 0; max = (loop_ub - loop_lb) / loop_st + 1; // The first chunk can consume all iterations. while (__kmpc_dispatch_next_4(&loc, gtid, &last, &lb, &ub, &st)) { ++ chunk; #if _DEBUG printf("th %d: chunk=%d, lb=%d, ub=%d ch %d\n", tid, chunk, (int)lb, (int)ub, (int)(ub-lb+1)); #endif // Check if previous chunk (it is not the final chunk) is undersized. if (undersized) printf("Error with chunk %d, th %d, err %d\n", chunk, tid, ++err); if (loop_st > 0) { if (!(ub <= loop_ub)) printf("Error with ub %d, %d, ch %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb <= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); } else { if (!(ub >= loop_ub)) printf("Error with ub %d, %d, %d, err %d\n", (int)ub, (int)loop_ub, chunk, ++err); if (!(lb >= ub)) printf("Error with bounds %d, %d, %d, err %d\n", (int)lb, (int)ub, chunk, ++err); }; // if // Stride should not change. if (!(st == loop_st)) printf("Error with st %d, %d, ch %d, err %d\n", (int)st, (int)loop_st, chunk, ++err); cur = ( ub - lb ) / loop_st + 1; // Guided scheduling uses FP computations, so current chunk may // be a bit bigger (+1) than allowed maximum. if (!( cur <= max + 1)) printf("Error with iter %d, %d, err %d\n", cur, max, ++err); // Update maximum for the next chunk. if (!last && cur % ch) printf("Error with chunk %d, %d, ch %d, tid %d, err %d\n", chunk, (int)cur, ch, tid, ++err); if (last && !no_chunk && cur > ch) printf("Error: too big last chunk %d (%d), tid %d, err %d\n", (int)cur, ch, tid, ++err); if (cur < max) max = cur; last_ub = ub; undersized = (cur < ch); #if _DEBUG > 1 if (last) printf("under%d cur %d, ch %d, tid %d, ub %d, lb %d, st %d =======\n", undersized,cur,ch,tid,ub,lb,loop_st); #endif } // while // Must have the right last iteration index. if (loop_st > 0) { if (!(last_ub <= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st > loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } else { if (!(last_ub >= loop_ub)) printf("Error with last1 %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_ub, chunk, ++err); if (last && !(last_ub + loop_st < loop_ub)) printf("Error with last2 %d, %d, %d, ch %d, err %d\n", (int)last_ub, (int)loop_st, (int)loop_ub, chunk, ++err); } // if } __kmpc_barrier(&loc, gtid); } // run_loop int main(int argc, char *argv[]) { int chunk = 0; if (argc > 1) { // expect chunk size as a parameter chunk = atoi(argv[1]); } #pragma omp parallel //num_threads(num_th) run_loop(0, UBOUND, 1, chunk); if (err) { printf("failed, err = %d\n", err); return 1; } else { printf("passed\n"); return 0; } }
compiler_cgen.c
/* Generated by Nim Compiler v0.15.0 */ /* (c) 2016 Andreas Rumpf */ /* The generated code is subject to the original license. */ #define NIM_INTBITS 64 #include "nimbase.h" #include <string.h> typedef struct Tcgen531027 Tcgen531027; typedef struct TNimType TNimType; typedef struct TNimNode TNimNode; typedef struct Ropeobj180006 Ropeobj180006; typedef struct NimStringDesc NimStringDesc; typedef struct TGenericSeq TGenericSeq; typedef struct Cell47305 Cell47305; typedef struct Cellseq47321 Cellseq47321; typedef struct Gcheap49818 Gcheap49818; typedef struct Gcstack49816 Gcstack49816; typedef struct Memregion29486 Memregion29486; typedef struct Smallchunk29440 Smallchunk29440; typedef struct Llchunk29480 Llchunk29480; typedef struct Bigchunk29442 Bigchunk29442; typedef struct Intset29414 Intset29414; typedef struct Trunk29410 Trunk29410; typedef struct Avlnode29484 Avlnode29484; typedef struct Gcstat49814 Gcstat49814; typedef struct Cellset47317 Cellset47317; typedef struct Pagedesc47313 Pagedesc47313; typedef struct Ttypeseq294836 Ttypeseq294836; typedef struct Ttype294840 Ttype294840; typedef struct Intset270030 Intset270030; typedef struct Trunk270026 Trunk270026; typedef struct Trunkseq270028 Trunkseq270028; typedef struct Tpasscontext343002 Tpasscontext343002; typedef struct Tsym294834 Tsym294834; typedef struct Tidobj201004 Tidobj201004; typedef struct TNimObject TNimObject; typedef struct TY294929 TY294929; typedef struct Tstrtable294806 Tstrtable294806; typedef struct Tsymseq294804 Tsymseq294804; typedef struct Tident201010 Tident201010; typedef struct Tlineinfo193336 Tlineinfo193336; typedef struct Tnode294802 Tnode294802; typedef struct Tloc294816 Tloc294816; typedef struct Tlib294820 Tlib294820; typedef struct TY531153 TY531153; typedef struct TY205018 TY205018; typedef struct Tidtable294850 Tidtable294850; typedef struct Tidpairseq294848 Tidpairseq294848; typedef struct Tlinkedlist148013 Tlinkedlist148013; typedef struct Tlistentry148007 Tlistentry148007; typedef struct Tcproc531021 Tcproc531021; typedef struct Tnodetable294862 Tnodetable294862; typedef struct Tnodepairseq294860 Tnodepairseq294860; typedef struct Debuginfo205009 Debuginfo205009; typedef struct TY205021 TY205021; typedef struct TY205023 TY205023; typedef struct Tnodeseq294796 Tnodeseq294796; typedef struct TY193350 TY193350; typedef struct TY531095 TY531095; typedef struct Trodreader334021 Trodreader334021; typedef struct TY294960 TY294960; typedef struct TY205017 TY205017; typedef struct Enumdesc205007 Enumdesc205007; typedef struct Tinfocc275008 Tinfocc275008; typedef struct Tblock531019 Tblock531019; typedef struct Ttraversalclosure539019 Ttraversalclosure539019; typedef struct TY136002 TY136002; typedef struct Tbitset341004 Tbitset341004; typedef struct TY193612 TY193612; typedef struct Tfileinfo193334 Tfileinfo193334; typedef struct Tinfoos178035 Tinfoos178035; typedef struct Tinfocpu178476 Tinfocpu178476; typedef struct Tstrentry148009 Tstrentry148009; typedef struct TY129506 TY129506; typedef struct Basechunk29438 Basechunk29438; typedef struct Freecell29430 Freecell29430; typedef struct Tinstantiation294824 Tinstantiation294824; typedef struct Tidpair294846 Tidpair294846; typedef struct Tnodepair294858 Tnodepair294858; typedef struct Filenamemapping205005 Filenamemapping205005; typedef struct TY334033 TY334033; typedef struct Tindex334019 Tindex334019; typedef struct Tiitable301142 Tiitable301142; typedef struct Tiipairseq301140 Tiipairseq301140; typedef struct Table334054 Table334054; typedef struct Keyvaluepairseq334057 Keyvaluepairseq334057; typedef struct Memfile332202 Memfile332202; typedef struct TY294961 TY294961; typedef struct Tiipair301138 Tiipair301138; typedef struct Keyvaluepair334060 Keyvaluepair334060; typedef NU8 Tnimkind3403; typedef NU8 Tnimtypeflag3409Set; typedef N_NIMCALL_PTR(void, TY3489) (void* p0, NI op0); typedef N_NIMCALL_PTR(void*, TY3494) (void* p0); struct TNimType { NI size; Tnimkind3403 kind; Tnimtypeflag3409Set flags; TNimType* base; TNimNode* node; void* finalizer; TY3489 marker; TY3494 deepcopy; }; typedef NU8 Tnimnodekind3405; struct TNimNode { Tnimnodekind3405 kind; NI offset; TNimType* typ; NCSTRING name; NI len; TNimNode** sons; }; typedef N_NIMCALL_PTR(void, Globalmarkerproc55802) (void); struct TGenericSeq { NI len; NI reserved; }; struct NimStringDesc { TGenericSeq Sup; NIM_CHAR data[SEQ_DECL_SIZE]; }; struct Cell47305 { NI refcount; TNimType* typ; }; struct Cellseq47321 { NI len; NI cap; Cell47305** d; }; typedef Smallchunk29440* TY29501[512]; typedef Trunk29410* Trunkbuckets29412[256]; struct Intset29414 { Trunkbuckets29412 data; }; struct Memregion29486 { NI minlargeobj; NI maxlargeobj; TY29501 freesmallchunks; Llchunk29480* llmem; NI currmem; NI maxmem; NI freemem; NI lastsize; Bigchunk29442* freechunkslist; Intset29414 chunkstarts; Avlnode29484* root; Avlnode29484* deleted; Avlnode29484* last; Avlnode29484* freeavlnodes; NIM_BOOL locked; }; struct Gcstat49814 { NI stackscans; NI cyclecollections; NI maxthreshold; NI maxstacksize; NI maxstackcells; NI cycletablesize; NI64 maxpause; }; struct Cellset47317 { NI counter; NI max; Pagedesc47313* head; Pagedesc47313** data; }; struct Gcheap49818 { Gcstack49816* stack; void* stackbottom; NI cyclethreshold; Cellseq47321 zct; Cellseq47321 decstack; Cellseq47321 tempstack; NI recgclock; Memregion29486 region; Gcstat49814 stat; Cellset47317 marked; Cellseq47321 additionalroots; }; struct Intset270030 { NI counter; NI max; Trunk270026* head; Trunkseq270028* data; }; struct TNimObject { TNimType* m_type; }; struct Tidobj201004 { TNimObject Sup; NI id; }; typedef NU8 Tsymkind294435; struct Tstrtable294806 { NI counter; Tsymseq294804* data; }; typedef NU16 Tmagic294524; struct Tlineinfo193336 { NI16 line; NI16 col; NI32 fileindex; }; typedef NU32 Tsymflag294184Set; typedef NU32 Toption171009Set; typedef NU8 Tlockind294808; typedef NU8 Tstorageloc294812; typedef NU16 Tlocflag294810Set; struct Tloc294816 { Tlockind294808 k; Tstorageloc294812 s; Tlocflag294810Set flags; Ttype294840* t; Ropeobj180006* r; }; struct Tsym294834 { Tidobj201004 Sup; Tsymkind294435 kind; union{ struct {Ttypeseq294836* typeinstcache; } S1; struct {TY294929* procinstcache; Tsym294834* gcunsafetyreason; } S2; struct {TY294929* usedgenerics; Tstrtable294806 tab; } S3; struct {Tsym294834* guard; NI bitsize; } S4; } kindU; Tmagic294524 magic; Ttype294840* typ; Tident201010* name; Tlineinfo193336 info; Tsym294834* owner; Tsymflag294184Set flags; Tnode294802* ast; Toption171009Set options; NI position; NI offset; Tloc294816 loc; Tlib294820* annex; Tnode294802* constraint; }; struct TY205018 { NimStringDesc* Field0; NI Field1; }; struct Tpasscontext343002 { TNimObject Sup; NIM_BOOL fromcache; }; typedef Ropeobj180006* Tcfilesections531009[18]; typedef NU8 Codegenflag531025Set; struct Tidtable294850 { NI counter; Tidpairseq294848* data; }; struct Tlinkedlist148013 { Tlistentry148007* head; Tlistentry148007* tail; NI counter; }; struct Tnodetable294862 { NI counter; Tnodepairseq294860* data; }; typedef Ropeobj180006* TY531136[10]; struct Tcgen531027 { Tpasscontext343002 Sup; Tcfilesections531009 s; Codegenflag531025Set flags; Tsym294834* module; NimStringDesc* filename; NimStringDesc* cfilename; Ropeobj180006* tmpbase; Tidtable294850 typecache; Tidtable294850 forwtypecache; Intset270030 declaredthings; Intset270030 declaredprotos; Tlinkedlist148013 headerfiles; Intset270030 typeinfomarker; Tcproc531021* initproc; Tcproc531021* postinitproc; Tcproc531021* preinitproc; Ttypeseq294836* typestack; Tnodetable294862 datacache; Tsymseq294804* forwardedprocs; NI typenodes; NI nimtypes; Ropeobj180006* typenodesname; Ropeobj180006* nimtypesname; NI labels; TY531136 extensionloaders; Ropeobj180006* injectstmt; }; struct Debuginfo205009 { NI version; TY205021* files; TY205023* enums; NIM_BOOL conflicts; }; struct Tident201010 { Tidobj201004 Sup; NimStringDesc* s; Tident201010* next; NI h; }; struct Tcproc531021 { Tsym294834* prc; NIM_BOOL beforeretneeded; NIM_BOOL threadvaraccessed; Tlineinfo193336 lastlineinfo; Tnodeseq294796* nestedtrystmts; NI inexceptblock; TY193350* finallysafepoints; NI labels; TY531095* blocks; NI breakidx; Toption171009Set options; NI maxframelen; Tcgen531027* module; NI withinloop; NI splitdecls; NI gcframeid; Ropeobj180006* gcframetype; }; typedef NU8 Tsymflag294184; typedef NU8 Codegenflag531025; typedef NU8 Toption171009; typedef NU64 Tglobaloption171013Set; typedef NU8 Tglobaloption171013; typedef NU8 Tcommands171076; typedef NU16 Tnodeflag294427Set; typedef NU8 Tnodekind294020; struct Tnode294802 { Ttype294840* typ; Tlineinfo193336 info; Tnodeflag294427Set flags; Tnodekind294020 kind; union{ struct {NI64 intval; } S1; struct {NF floatval; } S2; struct {NimStringDesc* strval; } S3; struct {Tsym294834* sym; } S4; struct {Tident201010* ident; } S5; struct {Tnodeseq294796* sons; } S6; } kindU; NimStringDesc* comment; }; typedef Ropeobj180006* TY535289[1]; typedef NU8 Tlocflag294810; struct Tlistentry148007 { TNimObject Sup; Tlistentry148007* prev; Tlistentry148007* next; }; typedef NU8 Tlibkind294818; struct Tlib294820 { Tlistentry148007 Sup; Tlibkind294818 kind; NIM_BOOL generated; NIM_BOOL isoverriden; Ropeobj180006* name; Tnode294802* path; }; typedef NU8 Tcfilesection531005; typedef NU8 Ttypekind294244; typedef NU8 Tcallingconvention294002; typedef NU32 Ttypeflag294431Set; struct Ttype294840 { Tidobj201004 Sup; Ttypekind294244 kind; Tcallingconvention294002 callconv; Ttypeflag294431Set flags; Ttypeseq294836* sons; Tnode294802* n; Tsym294834* owner; Tsym294834* sym; Tsym294834* destructor; Tsym294834* deepcopy; Tsym294834* assignment; TY294960* methods; NI64 size; NI16 align; NI16 locklevel; Tloc294816 loc; }; typedef Ropeobj180006* TY534811[2]; typedef NU8 Tctypekind531007; typedef NU64 Ttypekind294244Set; typedef NU8 Ttypeflag294431; typedef NimStringDesc* TY535943[14]; typedef NU8 Tprefereddesc322011; typedef Ropeobj180006* TY180507[1]; struct Enumdesc205007 { NI size; NU32 owner; NI id; NimStringDesc* name; TY205017* values; }; typedef Ropeobj180006* TY537235[4]; typedef NimStringDesc* TY294016[10]; typedef Ropeobj180006* TY537238[3]; struct Ropeobj180006 { TNimObject Sup; Ropeobj180006* left; Ropeobj180006* right; NI length; NimStringDesc* data; }; typedef NU8 Tinfoccprop275004Set; struct Tinfocc275008 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; NimStringDesc* Field12; NimStringDesc* Field13; NimStringDesc* Field14; NimStringDesc* Field15; NimStringDesc* Field16; NimStringDesc* Field17; NimStringDesc* Field18; NimStringDesc* Field19; Tinfoccprop275004Set Field20; }; typedef Tinfocc275008 TY275427[13]; typedef NU8 Tsystemcc275002; typedef NU8 Tnodeflag294427; typedef NU8 Tcprocsection531011; typedef Ropeobj180006* Tcprocsections531013[3]; struct Tblock531019 { NI id; Ropeobj180006* label; Tcprocsections531013 sections; NIM_BOOL isloop; NI16 nestedtrystmts; NI16 nestedexceptstmts; NI16 framelen; }; typedef NU8 Tgcmode171080; typedef NU8 Ttypeinforeason539016; struct Ttraversalclosure539019 { Tcproc531021* p; NimStringDesc* visitorfrmt; }; typedef NU8 Ttypefieldresult322145; typedef NU8 Tinfoccprop275004; typedef Ropeobj180006* TY538847[6]; typedef Ropeobj180006* TY538401[7]; typedef Ropeobj180006* TY538475[5]; typedef NU16 Tmsgkind193002; typedef NU8 Tassignmentflag540302Set; typedef NU8 Tassignmentflag540302; typedef NimStringDesc* TY554655[19]; typedef NimStringDesc* TY553642[3]; typedef NimStringDesc* TY558765[4]; typedef NimStringDesc* TY553828[42]; typedef NimStringDesc* TY553281[7]; typedef NU8 Trenderflag313004Set; typedef NimStringDesc* TY559052[2]; typedef NU8 Tclosuretypekind537681; typedef NimStringDesc* TY558428[6]; typedef NU8 Tanalysisresult475003; typedef NU8 char136Set[32]; typedef NU8 Tdistinctcompare326427; typedef NU8 Ttypecmpflag326429Set; typedef NU16 Tspecialword277003; typedef NU8 Tsystemos178004; struct Tfileinfo193334 { NimStringDesc* fullpath; NimStringDesc* projpath; NimStringDesc* shortname; Ropeobj180006* quotedname; Ropeobj180006* quotedfullname; TY193350* lines; NimStringDesc* dirtyfile; }; typedef NU8 Tinfoosprop178031Set; struct Tinfoos178035 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; NimStringDesc* Field3; NimStringDesc* Field4; NimStringDesc* Field5; NimStringDesc* Field6; NimStringDesc* Field7; NimStringDesc* Field8; NimStringDesc* Field9; NimStringDesc* Field10; NimStringDesc* Field11; Tinfoosprop178031Set Field12; }; typedef Tinfoos178035 TY178082[24]; typedef NU8 Tendian178474; struct Tinfocpu178476 { NimStringDesc* Field0; NI Field1; Tendian178474 Field2; NI Field3; NI Field4; }; typedef Tinfocpu178476 TY178510[19]; typedef NU8 Tsystemcpu178452; struct Tstrentry148009 { Tlistentry148007 Sup; NimStringDesc* data; }; struct TY129506 { NimStringDesc* Field0; NimStringDesc* Field1; NimStringDesc* Field2; }; struct Gcstack49816 { Gcstack49816* prev; Gcstack49816* next; void* starts; void* pos; NI maxstacksize; }; struct Basechunk29438 { NI prevsize; NI size; NIM_BOOL used; }; struct Smallchunk29440 { Basechunk29438 Sup; Smallchunk29440* next; Smallchunk29440* prev; Freecell29430* freelist; NI free; NI acc; NF data; }; struct Llchunk29480 { NI size; NI acc; Llchunk29480* next; }; struct Bigchunk29442 { Basechunk29438 Sup; Bigchunk29442* next; Bigchunk29442* prev; NI align; NF data; }; typedef NI TY29419[8]; struct Trunk29410 { Trunk29410* next; NI key; TY29419 bits; }; typedef Avlnode29484* TY29491[2]; struct Avlnode29484 { TY29491 link; NI key; NI upperbound; NI level; }; struct Pagedesc47313 { Pagedesc47313* next; NI key; TY29419 bits; }; struct Trunk270026 { Trunk270026* next; NI key; TY29419 bits; }; struct Tidpair294846 { Tidobj201004* key; TNimObject* val; }; struct Tnodepair294858 { NI h; Tnode294802* key; NI val; }; struct Filenamemapping205005 { NimStringDesc* package; NimStringDesc* file; NU32 mangled; }; typedef NU8 Treasonforrecompile334002; struct Tiitable301142 { NI counter; Tiipairseq301140* data; }; struct Tindex334019 { NI lastidxkey; NI lastidxval; Tiitable301142 tab; NimStringDesc* r; NI offset; }; struct Table334054 { Keyvaluepairseq334057* data; NI counter; }; struct Memfile332202 { void* mem; NI size; int handle; }; struct Trodreader334021 { TNimObject Sup; NI pos; NCSTRING s; Toption171009Set options; Treasonforrecompile334002 reason; TY334033* moddeps; TY334033* files; NI dataidx; NI convertersidx; NI initidx; NI interfidx; NI compilerprocsidx; NI methodsidx; NimStringDesc* filename; Tindex334019 index; Tindex334019 imports; NI readerindex; NI line; NI moduleid; Table334054 syms; Memfile332202 memfile; Tsymseq294804* methods; NimStringDesc* origfile; NIM_BOOL inviewmode; }; struct TY294961 { NI Field0; Tsym294834* Field1; }; struct Freecell29430 { Freecell29430* next; NI zerofield; }; struct Tinstantiation294824 { Tsym294834* sym; Ttypeseq294836* concretetypes; NI compilesid; }; struct Tiipair301138 { NI key; NI val; }; struct Keyvaluepair334060 { NI Field0; NI Field1; Tsym294834* Field2; }; struct Ttypeseq294836 { TGenericSeq Sup; Ttype294840* data[SEQ_DECL_SIZE]; }; struct TY531153 { TGenericSeq Sup; Tcgen531027* data[SEQ_DECL_SIZE]; }; struct Tsymseq294804 { TGenericSeq Sup; Tsym294834* data[SEQ_DECL_SIZE]; }; struct TY205017 { TGenericSeq Sup; TY205018 data[SEQ_DECL_SIZE]; }; struct TY136002 { TGenericSeq Sup; NimStringDesc* data[SEQ_DECL_SIZE]; }; struct Tbitset341004 { TGenericSeq Sup; NI8 data[SEQ_DECL_SIZE]; }; struct TY531095 { TGenericSeq Sup; Tblock531019 data[SEQ_DECL_SIZE]; }; struct TY193350 { TGenericSeq Sup; Ropeobj180006* data[SEQ_DECL_SIZE]; }; struct Tnodeseq294796 { TGenericSeq Sup; Tnode294802* data[SEQ_DECL_SIZE]; }; struct TY193612 { TGenericSeq Sup; Tfileinfo193334 data[SEQ_DECL_SIZE]; }; struct Trunkseq270028 { TGenericSeq Sup; Trunk270026* data[SEQ_DECL_SIZE]; }; struct TY294929 { TGenericSeq Sup; Tinstantiation294824* data[SEQ_DECL_SIZE]; }; struct Tidpairseq294848 { TGenericSeq Sup; Tidpair294846 data[SEQ_DECL_SIZE]; }; struct Tnodepairseq294860 { TGenericSeq Sup; Tnodepair294858 data[SEQ_DECL_SIZE]; }; struct TY205021 { TGenericSeq Sup; Filenamemapping205005 data[SEQ_DECL_SIZE]; }; struct TY205023 { TGenericSeq Sup; Enumdesc205007 data[SEQ_DECL_SIZE]; }; struct TY294960 { TGenericSeq Sup; TY294961 data[SEQ_DECL_SIZE]; }; struct TY334033 { TGenericSeq Sup; NI32 data[SEQ_DECL_SIZE]; }; struct Tiipairseq301140 { TGenericSeq Sup; Tiipair301138 data[SEQ_DECL_SIZE]; }; struct Keyvaluepairseq334057 { TGenericSeq Sup; Keyvaluepair334060 data[SEQ_DECL_SIZE]; }; N_NIMCALL(void, nimGCvisit)(void* d0, NI op0); N_NIMCALL(void, T839829468_2)(void); N_NIMCALL(void, nimRegisterGlobalMarker)(Globalmarkerproc55802 markerproc0); N_NIMCALL(void, T839829468_3)(void); N_NIMCALL(Ropeobj180006*, rope_180277_2381377266)(NimStringDesc* s0); static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0); static N_INLINE(Cell47305*, usrtocell_51440_1689653243)(void* usr0); static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47305* c0); N_NOINLINE(void, addzct_51417_1689653243)(Cellseq47321* s0, Cell47305* c0); N_NIMCALL(void, T839829468_5)(void); N_NIMCALL(void, T839829468_6)(void); static N_INLINE(void, nimGCunrefNoCycle)(void* p0); N_NIMCALL(void*, newSeqRC1)(TNimType* typ0, NI len0); N_NIMCALL(void, T839829468_7)(void); N_NIMCALL(void, initintset_270885_2627731572)(Intset270030* Result); N_NOINLINE(void, chckNil)(void* p0); N_NIMCALL(void, genericReset)(void* dest0, TNimType* mt0); N_NIMCALL(void, T839829468_8)(void); N_NIMCALL(Tcgen531027*, newmodule_565044_839829468)(Tsym294834* module0); N_NIMCALL(Tcgen531027*, getcgenmodule_534226_839829468)(Tsym294834* s0); N_NIMCALL(void, internalerror_198113_155036129)(NimStringDesc* errmsg0); N_NIMCALL(NimStringDesc*, HEX24_198185_1689653243)(TY205018 x0); N_NIMCALL(Tcgen531027*, rawnewmodule_565038_839829468)(Tsym294834* module0); N_NIMCALL(Tcgen531027*, rawnewmodule_564663_839829468)(Tsym294834* module0, NimStringDesc* filename0); N_NIMCALL(void*, newObj)(TNimType* typ0, NI size0); static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0); static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0); N_NIMCALL(NimStringDesc*, HEX24_8401_1689653243)(NU64 x0); N_NIMCALL(NU32, hashowner_534977_839829468)(Tsym294834* s0); N_NIMCALL(NU32, register_205121_1926258066)(Debuginfo205009* self0, NimStringDesc* package0, NimStringDesc* file0); N_NIMCALL(NimStringDesc*, rawNewString)(NI space0); N_NIMCALL(void, initlinkedlist_148031_3771138726)(Tlinkedlist148013* list0); N_NIMCALL(NimStringDesc*, copyStringRC1)(NimStringDesc* src0); N_NIMCALL(void, initidtable_298019_850551059)(Tidtable294850* x0); N_NIMCALL(Tcproc531021*, newproc_531206_3723162438)(Tsym294834* prc0, Tcgen531027* module0); static N_INLINE(void, asgnRef)(void** dest0, void* src0); static N_INLINE(void, incref_53419_1689653243)(Cell47305* c0); static N_INLINE(void, decref_53001_1689653243)(Cell47305* c0); N_NIMCALL(Toption171009Set, initprocoptions_564635_839829468)(Tcgen531027* m0); N_NIMCALL(Tcproc531021*, newpreinitproc_564625_839829468)(Tcgen531027* m0); N_NIMCALL(Tcproc531021*, newpostinitproc_564630_839829468)(Tcgen531027* m0); N_NIMCALL(void, initnodetable_298085_850551059)(Tnodetable294862* x0); N_NIMCALL(Ropeobj180006*, gettempname_535598_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, HEX26_180418_2381377266)(Ropeobj180006* a0, Ropeobj180006* b0); N_NIMCALL(Ropeobj180006*, rope_180401_2381377266)(NI64 i0); N_NIMCALL(NimStringDesc*, tofullpath_194261_155036129)(NI32 fileidx0); N_NIMCALL(TGenericSeq*, setLengthSeq)(TGenericSeq* seq0, NI elemsize0, NI newlen0); N_NIMCALL(NimStringDesc*, tofilename_194257_155036129)(NI32 fileidx0); N_NIMCALL(NimStringDesc*, noschangeFileExt)(NimStringDesc* filename0, NimStringDesc* ext0); N_NIMCALL(NimStringDesc*, completecfilepath_275854_2528170400)(NimStringDesc* cfile0, NIM_BOOL createsubdir0); N_NIMCALL(void, readmergeinfo_532613_2760143328)(NimStringDesc* cfilename0, Tcgen531027* m0); N_NIMCALL(NimStringDesc*, getcfile_565201_839829468)(Tcgen531027* m0); N_NIMCALL(NimStringDesc*, copyString)(NimStringDesc* src0); N_NIMCALL(NimStringDesc*, withpackagename_172073_2607990831)(NimStringDesc* path0); static N_INLINE(NIM_BOOL, skipcodegen_343085_2355241294)(Tnode294802* n0); N_NIMCALL(void, genstmts_541244_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(void, expr_541248_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, fillprocloc_541201_839829468)(Tsym294834* sym0); N_NIMCALL(void, fillloc_534282_839829468)(Tloc294816* a0, Tlockind294808 k0, Ttype294840* typ0, Ropeobj180006* r0, Tstorageloc294812 s0); N_NIMCALL(void, unsureAsgnRef)(void** dest0, void* src0); N_NIMCALL(Ropeobj180006*, manglename_535205_839829468)(Tsym294834* s0); N_NIMCALL(NIM_BOOL, iskeyword_534960_839829468)(Tident201010* w0); N_NIMCALL(NimStringDesc*, mangle_530847_2036603609)(NimStringDesc* name0); N_NIMCALL(void, add_180487_2381377266)(Ropeobj180006** a0, NimStringDesc* b0); N_NIMCALL(void, add_180482_2381377266)(Ropeobj180006** a0, Ropeobj180006* b0); N_NIMCALL(Ropeobj180006*, HEX25_180905_2381377266)(NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(void, genprocprototype_541254_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, useheader_534369_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(NIM_BOOL, includestr_148249_3771138726)(Tlinkedlist148013* list0, NimStringDesc* data0); N_NIMCALL(NimStringDesc*, getstr_299230_850551059)(Tnode294802* a0); N_NIMCALL(Tsym294834*, getmodule_301123_2984716966)(Tsym294834* s0); N_NIMCALL(NIM_BOOL, containsorincl_270862_2627731572)(Intset270030* s0, NI key0); N_NIMCALL(Ropeobj180006*, ropecg_534407_839829468)(Tcgen531027* m0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, nimIntToStr)(NI x0); static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI start_79210_1689653243, NI last0); N_NIMCALL(NimStringDesc*, copyStrLast)(NimStringDesc* s0, NI first0, NI last0); N_NIMCALL(Ropeobj180006*, cgsym_534403_839829468)(Tcgen531027* m0, NimStringDesc* name0); N_NIMCALL(Tsym294834*, getcompilerproc_340748_3937434831)(NimStringDesc* name0); N_NIMCALL(void, genproc_534951_839829468)(Tcgen531027* m0, Tsym294834* prc0); N_NIMCALL(NIM_BOOL, isactivated_563431_839829468)(Tsym294834* prc0); N_NIMCALL(void, addforwardedproc_534203_839829468)(Tcgen531027* m0, Tsym294834* prc0); N_NIMCALL(TGenericSeq*, incrSeqV2)(TGenericSeq* seq0, NI elemsize0); N_NIMCALL(void, genprocnoforward_562906_839829468)(Tcgen531027* m0, Tsym294834* prc0); N_NIMCALL(void, genprocaux_562284_839829468)(Tcgen531027* m0, Tsym294834* prc0); N_NIMCALL(Ropeobj180006*, genprocheader_537867_839829468)(Tcgen531027* m0, Tsym294834* prc0); N_NIMCALL(void, genclinedir_534813_839829468)(Ropeobj180006** r0, Tlineinfo193336 info0); N_NIMCALL(void, genclinedir_534725_839829468)(Ropeobj180006** r0, NimStringDesc* filename0, NI line0); N_NIMCALL(void, addf_181205_2381377266)(Ropeobj180006** c0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(NimStringDesc*, makesinglelinecstring_530835_2036603609)(NimStringDesc* s0); N_NIMCALL(NI, safelinenm_534721_839829468)(Tlineinfo193336 info0); static N_INLINE(NI, tolinenumber_194415_155036129)(Tlineinfo193336 info0); N_NIMCALL(void, genprocparams_536115_839829468)(Tcgen531027* m0, Ttype294840* t0, Ropeobj180006** rettype0, Ropeobj180006** params0, Intset270030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0); N_NIMCALL(NIM_BOOL, isinvalidreturntype_535550_839829468)(Ttype294840* rettype0); N_NIMCALL(Tctypekind531007, maptype_535394_839829468)(Ttype294840* typ0); N_NIMCALL(Tctypekind531007, mapsettype_535389_839829468)(Ttype294840* typ0); N_NIMCALL(NI64, getsize_322135_3876443242)(Ttype294840* typ0); N_NIMCALL(Ttype294840*, lastson_297377_850551059)(Ttype294840* n0); N_NIMCALL(NI64, firstord_322001_3876443242)(Ttype294840* t0); N_NIMCALL(Ttype294840*, skiptypes_298099_850551059)(Ttype294840* t0, Ttypekind294244Set kinds0); N_NIMCALL(NIM_BOOL, isimportedcpptype_535478_839829468)(Ttype294840* t0); N_NIMCALL(NIM_BOOL, needscomplexassignment_535511_839829468)(Ttype294840* typ0); N_NIMCALL(NIM_BOOL, containsgarbagecollectedref_322117_3876443242)(Ttype294840* typ0); static N_INLINE(NIM_BOOL, isobjlackingtypefield_535515_839829468)(Ttype294840* typ0); N_NIMCALL(NIM_BOOL, ispureobject_322138_3876443242)(Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, gettypedescaux_535505_839829468)(Tcgen531027* m0, Ttype294840* typ0, Intset270030* check0); N_NIMCALL(Ttype294840*, getuniquetype_530640_2036603609)(Ttype294840* key0); N_NIMCALL(Ropeobj180006*, gettypepre_535972_839829468)(Tcgen531027* m0, Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, getsimpletypedesc_535936_839829468)(Tcgen531027* m0, Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, typenameorliteral_535898_839829468)(Ttype294840* t0, NimStringDesc* literal0); N_NIMCALL(Ropeobj180006*, gettypename_535313_839829468)(Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, typename_535292_839829468)(Ttype294840* typ0); N_NIMCALL(NimStringDesc*, reprEnum)(NI e0, TNimType* typ0); N_NIMCALL(Ropeobj180006*, cachegettype_535593_839829468)(Tidtable294850 tab0, Ttype294840* key0); N_NIMCALL(TNimObject*, idtableget_301086_2984716966)(Tidtable294850 t0, Tidobj201004* key0); N_NIMCALL(NimStringDesc*, typetostring_322017_3876443242)(Ttype294840* typ0, Tprefereddesc322011 prefer0); N_NIMCALL(Ttype294840*, elemtype_322394_3876443242)(Ttype294840* t0); N_NIMCALL(Ropeobj180006*, HEX26_180447_2381377266)(Ropeobj180006* a0, NimStringDesc* b0); N_NIMCALL(Ropeobj180006*, gettypeforward_536039_839829468)(Tcgen531027* m0, Ttype294840* typ0); N_NIMCALL(NIM_BOOL, isimportedtype_535451_839829468)(Ttype294840* t0); N_NIMCALL(NimStringDesc*, getforwardstructformat_536015_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, structorunion_536001_839829468)(Ttype294840* t0); N_NIMCALL(void, idtableput_301094_2984716966)(Tidtable294850* t0, Tidobj201004* key0, TNimObject* val0); N_NIMCALL(void, pushtype_535958_839829468)(Tcgen531027* m0, Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, gettypedescweak_536079_839829468)(Tcgen531027* m0, Ttype294840* t0, Intset270030* check0); N_NIMCALL(void, internalerror_198100_155036129)(Tlineinfo193336 info0, NimStringDesc* errmsg0); N_NIMCALL(NIM_BOOL, hasenum_205230_1926258066)(Debuginfo205009* self0, NimStringDesc* ename0, NI id0, NU32 owner0); N_NIMCALL(void*, newSeq)(TNimType* typ0, NI len0); static N_INLINE(NI, len_295081_850551059)(Tnode294802* n0); N_NIMCALL(void, registerenum_205419_1926258066)(Debuginfo205009* self0, Enumdesc205007* ed0); N_NIMCALL(void, genericSeqAssign)(void* dest0, void* src_86404_1689653243, TNimType* mt0); N_NIMCALL(void, appcg_534632_839829468)(Tcgen531027* m0, Ropeobj180006** c0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(NI64, lengthord_322007_3876443242)(Ttype294840* t0); N_NIMCALL(NIM_BOOL, scancppgenericslot_536827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0); N_NIMCALL(Ttype294840*, resolvestarsincpptype_536891_839829468)(Ttype294840* typ0, NI idx0, NI stars0); N_NIMCALL(NI, len_297339_850551059)(Ttype294840* n0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI start0); N_NIMCALL(NimStringDesc*, copyStr)(NimStringDesc* s0, NI first0); N_NIMCALL(Ropeobj180006*, getrecorddesc_536643_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0, Intset270030* check0); N_NIMCALL(Ropeobj180006*, getrecordfields_536636_839829468)(Tcgen531027* m0, Ttype294840* typ0, Intset270030* check0); N_NIMCALL(Ropeobj180006*, genrecordfieldsaux_536421_839829468)(Tcgen531027* m0, Tnode294802* n0, Ropeobj180006* accessexpr0, Ttype294840* rectype0, Intset270030* check0); N_NIMCALL(NI, sonslen_297351_850551059)(Tnode294802* n0); N_NIMCALL(Tnode294802*, lastson_297364_850551059)(Tnode294802* n0); N_NIMCALL(Ropeobj180006*, HEX26_180452_2381377266)(NimStringDesc* a0, Ropeobj180006* b0); N_NIMCALL(Ropeobj180006*, manglerecfieldname_536361_839829468)(Tsym294834* field0, Ttype294840* rectype0); N_NIMCALL(NimStringDesc*, manglefield_534973_839829468)(Tident201010* name0); N_NIMCALL(NIM_CHAR, nsuToUpperAsciiChar)(NIM_CHAR c0); N_NIMCALL(Ropeobj180006*, gettupledesc_536777_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0, Intset270030* check0); N_NIMCALL(NI, sonslen_297327_850551059)(Ttype294840* n0); N_NIMCALL(void, excl_270841_2627731572)(Intset270030* s0, NI key0); static N_INLINE(NIM_BOOL, iscompiletimeonly_330706_3876443242)(Ttype294840* t0); N_NIMCALL(Tstorageloc294812, paramstorageloc_536098_839829468)(Tsym294834* param0); N_NIMCALL(NIM_BOOL, ccgintroducedptr_535611_839829468)(Tsym294834* s0); N_NIMCALL(Tctypekind531007, mapreturntype_535447_839829468)(Ttype294840* typ0); N_NIMCALL(Tnode294802*, easyresultasgn_562191_839829468)(Tnode294802* n0); static N_INLINE(Tnode294802*, HEX5BHEX5D_295238_850551059)(Tnode294802* n0, NI i0); N_NIMCALL(Tnode294802*, getbody_337226_1724185294)(Tsym294834* s0); N_NIMCALL(Ropeobj180006*, localvardecl_540532_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(Ropeobj180006*, gettypedesc_537673_839829468)(Tcgen531027* m0, Ttype294840* typ0); N_NIMCALL(void, initlocexprsingleuse_541289_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* result0); N_NIMCALL(void, initloc_534273_839829468)(Tloc294816* result0, Tlockind294808 k0, Ttype294840* typ0, Tstorageloc294812 s0); N_NIMCALL(void, linefmt_534714_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); static N_INLINE(Ropeobj180006**, s_531179_3723162438)(Tcproc531021* p0, Tcprocsection531011 s0); N_NIMCALL(Ropeobj180006*, indentline_534656_839829468)(Tcproc531021* p0, Ropeobj180006* r0); N_NIMCALL(void, prepend_180893_2381377266)(Ropeobj180006** a0, Ropeobj180006* b0); N_NIMCALL(Ropeobj180006*, rdloc_540188_839829468)(Tloc294816* a0); N_NIMCALL(void, assignlocalvar_540614_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(void, line_534690_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, Ropeobj180006* r0); N_NIMCALL(void, localdebuginfo_540449_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(void, linef_534700_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(Ropeobj180006*, makecstring_193638_155036129)(NimStringDesc* s0); N_NIMCALL(NimStringDesc*, nsuNormalize)(NimStringDesc* s0); N_NIMCALL(Ropeobj180006*, gentypeinfo_537941_839829468)(Tcgen531027* m0, Ttype294840* t_537944_839829468); N_NIMCALL(Tcgen531027*, bmod_531201_3723162438)(Tsym294834* module0); N_NIMCALL(void, gentypeinfoauxbase_537960_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0, Ropeobj180006* base0); N_NIMCALL(NIM_BOOL, canformacycle_322123_3876443242)(Ttype294840* typ0); N_NIMCALL(void, gentupleinfo_538551_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0); N_NIMCALL(Ropeobj180006*, getnimnode_537945_839829468)(Tcgen531027* m0); N_NIMCALL(Ttype294840*, fakeclosuretype_539010_839829468)(Tsym294834* owner0); N_NIMCALL(Ttype294840*, newtype_297107_850551059)(Ttypekind294244 kind0, Tsym294834* owner0); N_NIMCALL(void, rawaddson_298394_850551059)(Ttype294840* father0, Ttype294840* son0); N_NIMCALL(void, gentypeinfoaux_538027_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0); N_NIMCALL(Ropeobj180006*, gentraverseproc_539632_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttypeinforeason539016 reason0); N_NIMCALL(void, gentraverseprocseq_539399_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Ttype294840* typ0); N_NIMCALL(void, gettemp_539032_839829468)(Tcproc531021* p0, Ttype294840* t0, Tloc294816* result0, NIM_BOOL needsinit0); N_NIMCALL(void, constructloc_540388_839829468)(Tcproc531021* p0, Tloc294816* loc0, NIM_BOOL istemp0); static N_INLINE(NIM_BOOL, iscomplexvaluetype_540317_839829468)(Ttype294840* t0); N_NIMCALL(void, usestringh_534345_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, addrloc_540204_839829468)(Tloc294816* a0); N_NIMCALL(void, genobjectinit_540242_839829468)(Tcproc531021* p0, Tcprocsection531011 section0, Ttype294840* t0, Tloc294816* a0, NIM_BOOL takeaddr0); N_NIMCALL(Ttypefieldresult322145, analyseobjectwithtypefield_322149_3876443242)(Ttype294840* t0); N_NIMCALL(Ttype294840*, getsystype_340150_3937434831)(Ttypekind294244 kind0); N_NIMCALL(void, gentraverseproc_539022_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Ttype294840* typ_539027_839829468); static N_INLINE(Ropeobj180006*, parentobj_539257_839829468)(Ropeobj180006* accessor0, Tcgen531027* m0); N_NIMCALL(void, gentraverseproc_539039_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Tnode294802* n0); N_NIMCALL(void, gencaserange_539028_839829468)(Tcproc531021* p0, Tnode294802* branch0); N_NIMCALL(Ropeobj180006*, genliteral_541273_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Ropeobj180006*, genliteral_551476_839829468)(Tcproc531021* p0, Tnode294802* n0, Ttype294840* ty0); N_NIMCALL(Ropeobj180006*, intliteral_541270_839829468)(NI64 i0); N_NIMCALL(Ropeobj180006*, int64literal_551430_839829468)(NI64 i0); N_NIMCALL(Ropeobj180006*, uint64literal_551442_839829468)(NU64 i0); N_NIMCALL(NI, nodetabletestorset_344682_1142335848)(Tnodetable294862* t0, Tnode294802* key0, NI val0); N_NIMCALL(Ropeobj180006*, getstrlit_551468_839829468)(Tcgen531027* m0, NimStringDesc* s0); N_NIMCALL(NimStringDesc*, tostrmaxprecision_300007_3471544153)(NF f0); N_NIMCALL(Tnode294802*, copynode_298528_850551059)(Tnode294802* src0); N_NIMCALL(void, linecg_534707_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(void, genarrayinfo_539005_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0); N_NIMCALL(void, gensetinfo_538867_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0); N_NIMCALL(void, genenuminfo_538599_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0); N_NIMCALL(void, genobjectinfo_538508_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0); N_NIMCALL(void, genobjectfields_538104_839829468)(Tcgen531027* m0, Ttype294840* typ0, Tnode294802* n0, Ropeobj180006* expr0); N_NIMCALL(Ropeobj180006*, discriminatortablename_538057_839829468)(Tcgen531027* m0, Ttype294840* objtype_538060_839829468, Tsym294834* d0); N_NIMCALL(Tsym294834*, lookupinrecord_301119_2984716966)(Tnode294802* n0, Tident201010* field0); N_NIMCALL(NI64, getordvalue_322129_3876443242)(Tnode294802* n0); N_NIMCALL(void, gendeepcopyproc_540066_839829468)(Tcgen531027* m0, Tsym294834* s0, Ropeobj180006* result0); N_NIMCALL(void, initlocalvar_540398_839829468)(Tcproc531021* p0, Tsym294834* v0, NIM_BOOL immediateasgn0); N_NIMCALL(void, fillresult_535865_839829468)(Tsym294834* param0); N_NIMCALL(void, assignparam_540994_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(void, closuresetup_562158_839829468)(Tcproc531021* p0, Tsym294834* prc0); N_NIMCALL(Ropeobj180006*, initgcframe_540435_839829468)(Tcproc531021* p0); N_NIMCALL(Ropeobj180006*, initframe_562140_839829468)(Tcproc531021* p0, Ropeobj180006* procname0, Ropeobj180006* filename0); N_NIMCALL(Ropeobj180006*, quotedfilename_198818_155036129)(Tlineinfo193336 i0); N_NIMCALL(void, appcg_534648_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(Ropeobj180006*, deinitgcframe_540441_839829468)(Tcproc531021* p0); N_NIMCALL(Ropeobj180006*, deinitframe_562150_839829468)(Tcproc531021* p0); N_NIMCALL(Tcgen531027*, findpendingmodule_534241_839829468)(Tcgen531027* m0, Tsym294834* s0); N_NIMCALL(void, symindynamiclib_561929_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(NIM_BOOL, isgetprocaddr_561443_839829468)(Tlib294820* lib0); N_NIMCALL(void, loaddynamiclib_561481_839829468)(Tcgen531027* m0, Tlib294820* lib0); N_NIMCALL(void, libcandidates_172605_2607990831)(NimStringDesc* s0, TY136002** dest0); N_NIMCALL(void, rawmessage_196612_155036129)(Tmsgkind193002 msg0, NimStringDesc* arg0); N_NIMCALL(void, initlocexpr_541283_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* result0); N_NIMCALL(Ropeobj180006*, mangledynlibproc_540816_839829468)(Tsym294834* sym0); N_NIMCALL(NimStringDesc*, HEX24_180856_2381377266)(Ropeobj180006* r0); N_NIMCALL(void, symindynamiclibpartial_562071_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, genvarprototype_541236_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, genvarprototypeaux_546254_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, declarethreadvar_540676_839829468)(Tcgen531027* m0, Tsym294834* s0, NIM_BOOL isextern0); static N_INLINE(NIM_BOOL, emulatedthreadvars_534949_839829468)(void); static N_INLINE(NIM_BOOL, crossescppboundary_562754_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, putlocintodest_541258_839829468)(Tcproc531021* p0, Tloc294816* d0, Tloc294816* s0); N_NIMCALL(void, genassignment_541264_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0); N_NIMCALL(void, genrefassign_540311_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0); static N_INLINE(NIM_BOOL, usesnativegc_171177_2607990831)(void); N_NIMCALL(void, optasgnloc_551789_839829468)(Tloc294816* a0, Ttype294840* t0, Ropeobj180006* field0, Tloc294816* Result); N_NIMCALL(void, genoptasgntuple_552001_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0); N_NIMCALL(void, gengenericasgn_552167_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0); N_NIMCALL(NI, asgncomplexity_551751_839829468)(Tnode294802* n0); N_NIMCALL(void, genoptasgnobject_552084_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0, Tnode294802* t0); N_NIMCALL(void, genericAssign)(void* dest0, void* src0, TNimType* mt0); N_NIMCALL(void, localerror_198085_155036129)(Tlineinfo193336 info0, NimStringDesc* arg0); N_NIMCALL(NIM_BOOL, issimpleconst_534311_839829468)(Ttype294840* typ0); N_NIMCALL(void, putintodest_552468_839829468)(Tcproc531021* p0, Tloc294816* d0, Ttype294840* t0, Ropeobj180006* r0, Tstorageloc294812 s0); N_NIMCALL(void, gencomplexconst_560249_839829468)(Tcproc531021* p0, Tsym294834* sym0, Tloc294816* d0); N_NIMCALL(void, requestconstimpl_541240_839829468)(Tcproc531021* p0, Tsym294834* sym0); N_NIMCALL(Ropeobj180006*, genconstexpr_556849_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, tobitset_342001_452470228)(Tnode294802* s0, Tbitset341004** b0); N_NIMCALL(Ropeobj180006*, genrawsetdata_551629_839829468)(Tbitset341004* cs0, NI size0); N_NIMCALL(NimStringDesc*, nsuToHex)(NI64 x0, NI len0); N_NIMCALL(NI64, bitsettoword_551578_839829468)(Tbitset341004* s0, NI size0); N_NIMCALL(Ropeobj180006*, genconstseq_561371_839829468)(Tcproc531021* p0, Tnode294802* n0, Ttype294840* t0); N_NIMCALL(void, appcg_534640_839829468)(Tcgen531027* m0, Tcfilesection531005 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(Ropeobj180006*, genconstsimplelist_561299_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Ropeobj180006*, gennamedconstexpr_561284_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, accessthreadlocalvar_534945_839829468)(Tcproc531021* p0, Tsym294834* s0); static N_INLINE(Ropeobj180006**, procsec_531194_3723162438)(Tcproc531021* p0, Tcprocsection531011 s0); static N_INLINE(NIM_BOOL, isemptytype_299441_850551059)(Ttype294840* t0); N_NIMCALL(void, putdataintodest_552436_839829468)(Tcproc531021* p0, Tloc294816* d0, Ttype294840* t0, Ropeobj180006* r0); N_NIMCALL(void, genlinedir_534823_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(Ropeobj180006*, sourceline_194065_155036129)(Tlineinfo193336 i0); N_NIMCALL(NIM_BOOL, freshlineinfo_534818_839829468)(Tcproc531021* p0, Tlineinfo193336 info0); N_NIMCALL(void, genmagicexpr_559033_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0); N_NIMCALL(void, genandor_556311_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0); N_NIMCALL(Ropeobj180006*, getlabel_541217_839829468)(Tcproc531021* p0); N_NIMCALL(void, fixlabel_541230_839829468)(Tcproc531021* p0, Ropeobj180006* labl0); N_NIMCALL(void, unaryarith_554646_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0); N_NIMCALL(void, unaryarithoverflow_553633_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0); N_NIMCALL(void, binaryfloatarith_558729_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0); N_NIMCALL(void, binaryarith_553819_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0); N_NIMCALL(void, geneqproc_554214_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, binaryarithoverflow_553262_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0); N_NIMCALL(Ropeobj180006*, binaryarithoverflowraw_553235_839829468)(Tcproc531021* p0, Ttype294840* t0, Tloc294816* a0, Tloc294816* b0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj180006*, rdcharloc_540227_839829468)(Tloc294816* a0); N_NIMCALL(NI64, lastord_322004_3876443242)(Ttype294840* t0); N_NIMCALL(void, genrepr_557339_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(Ropeobj180006*, lenfield_541305_839829468)(Tcproc531021* p0); N_NIMCALL(void, gcusage_556439_839829468)(Tnode294802* n0); N_NIMCALL(void, message_198095_155036129)(Tlineinfo193336 info0, Tmsgkind193002 msg0, NimStringDesc* arg0); N_NIMCALL(NimStringDesc*, rendertree_313044_382274130)(Tnode294802* n0, Trenderflag313004Set renderflags0); N_NIMCALL(void, gengettypeinfo_557383_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genswap_557638_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, unaryexpr_553209_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, binarystmt_552501_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genstrconcat_556452_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genstrappend_556554_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genseqelemappend_556683_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genstrequals_558667_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, binaryexpr_552549_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genisnil_554620_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, gendollar_557391_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genof_557331_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genof_557201_839829468)(Tcproc531021* p0, Tnode294802* x0, Ttype294840* typ0, Tloc294816* d0); N_NIMCALL(void, globalerror_198071_155036129)(Tlineinfo193336 info0, Tmsgkind193002 msg0, NimStringDesc* arg0); N_NIMCALL(Ropeobj180006*, genofhelper_557140_839829468)(Tcproc531021* p0, Ttype294840* dest0, Ropeobj180006* a0); N_NIMCALL(void, gennew_556782_839829468)(Tcproc531021* p0, Tnode294802* e0); N_NIMCALL(void, rawgennew_556741_839829468)(Tcproc531021* p0, Tloc294816* a0, Ropeobj180006* sizeexpr_556745_839829468); N_NIMCALL(void, gennewfinalize_557111_839829468)(Tcproc531021* p0, Tnode294802* e0); N_NIMCALL(void, gennewseq_556824_839829468)(Tcproc531021* p0, Tnode294802* e0); N_NIMCALL(void, gennewseqaux_556795_839829468)(Tcproc531021* p0, Tloc294816* dest0, Ropeobj180006* length0); N_NIMCALL(void, gennewseqofcap_556836_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, gensomecast_558481_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(Ropeobj180006*, getclosuretype_537685_839829468)(Tcgen531027* m0, Ttype294840* t0, Tclosuretypekind537681 kind0); N_NIMCALL(void, genord_558475_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, unaryexprchar_553222_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, genarraylen_557415_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0); N_NIMCALL(void, unarystmt_552527_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gensetlengthstr_557632_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, gensetlengthseq_557500_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, gensetop_558419_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0); N_NIMCALL(void, binarystmtinexcl_557858_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(Ropeobj180006*, rdsetelemloc_557662_839829468)(Tloc294816* a0, Ttype294840* settype0); N_NIMCALL(void, binaryexprchar_552809_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, geninop_558009_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, fewcmps_557803_839829468)(Tnode294802* s0); N_NIMCALL(void, geninexpraux_555496_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* a0, Tloc294816* b0, Tloc294816* d0); N_NIMCALL(void, binaryexprin_557837_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* a0, Tloc294816* b0, Tloc294816* d0, NimStringDesc* frmt0); N_NIMCALL(void, gencall_545632_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genclosurecall_542452_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0); N_NIMCALL(Ropeobj180006*, genarg_541787_839829468)(Tcproc531021* p0, Tnode294802* n_541790_839829468, Tsym294834* param0, Tnode294802* call0); static N_INLINE(Ropeobj180006*, genargstringtocstring_541776_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Ropeobj180006*, openarrayloc_541665_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Tnode294802*, skipconv_330882_3876443242)(Tnode294802* n0); N_NIMCALL(Tmagic294524, getmagic_320502_2616423590)(Tnode294802* op0); N_NIMCALL(Ropeobj180006*, genargnoparam_541938_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Ropeobj180006*, getrawproctype_542459_839829468)(Tcproc531021* p0, Ttype294840* t0); N_NIMCALL(NIM_BOOL, leftappearsonrightside_541329_839829468)(Tnode294802* le0, Tnode294802* ri0); N_NIMCALL(Tanalysisresult475003, ispartof_475340_788060399)(Tnode294802* a0, Tnode294802* b0); static N_INLINE(NIM_BOOL, hasnoinit_541383_839829468)(Tnode294802* call0); N_NIMCALL(void, resetloc_540350_839829468)(Tcproc531021* p0, Tloc294816* loc0); N_NIMCALL(Ropeobj180006*, addcomma_542464_839829468)(Ropeobj180006* r0); N_NIMCALL(void, geninfixcall_543929_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, contains_110056_4286263276)(NimStringDesc* s0, char136Set chars0); N_NIMCALL(Ropeobj180006*, genpatterncall_543699_839829468)(Tcproc531021* p0, Tnode294802* ri_543702_839829468, NimStringDesc* pat0, Ttype294840* typ_543704_839829468); N_NIMCALL(Ropeobj180006*, genotherarg_541277_839829468)(Tcproc531021* p0, Tnode294802* ri0, NI i0, Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, genthisarg_543475_839829468)(Tcproc531021* p0, Tnode294802* ri_543478_839829468, NI i0, Ttype294840* typ0); N_NIMCALL(Tnode294802*, skipaddrderef_543433_839829468)(Tnode294802* node0); N_NIMCALL(void, fixupcall_541410_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0, Ropeobj180006* callee0, Ropeobj180006* params0); N_NIMCALL(void, gennamedparamcall_544616_839829468)(Tcproc531021* p0, Tnode294802* ri0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, contains_110046_4286263276)(NimStringDesc* s0, NIM_CHAR c0); N_NIMCALL(void, genprefixcall_541960_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0); static N_INLINE(void, poststmtactions_534942_839829468)(Tcproc531021* p0); N_NIMCALL(void, genreset_556731_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, genecho_556369_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(NimStringDesc*, nsuRepeatStr)(NimStringDesc* s0, NI n0); N_NIMCALL(void, genarrtoseq_557046_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(void, genseqconstr_557004_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(void, localerror_198080_155036129)(Tlineinfo193336 info0, Tmsgkind193002 msg0, NimStringDesc* arg0); N_NIMCALL(Tnode294802*, wrapprocforspawn_437501_2218250499)(Tsym294834* owner0, Tnode294802* spawnexpr0, Ttype294840* rettype0, Tnode294802* barrier0, Tnode294802* dest0); N_NIMCALL(Tnode294802*, liftparallel_480822_1773027539)(Tsym294834* owner0, Tnode294802* n0); N_NIMCALL(void, gendeepcopy_552374_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0); N_NIMCALL(NIM_BOOL, isdeepconstexpr_320566_2616423590)(Tnode294802* n0); N_NIMCALL(Ropeobj180006*, gensetnode_551664_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, gensetconstr_559496_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(NimStringDesc*, nimInt64ToStr)(NI64 x0); N_NIMCALL(void, exprcomplexconst_560684_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genarrayconstr_560207_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, handleconstexpr_556853_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, gentupleconstr_559618_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genobjconstr_556903_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(Tsym294834*, lookupfieldagain_555154_839829468)(Tcproc531021* p0, Ttype294840* ty_555157_839829468, Tsym294834* field0, Ropeobj180006** r0); N_NIMCALL(void, genfieldcheck_555504_839829468)(Tcproc531021* p0, Tnode294802* e0, Ropeobj180006* obj0, Tsym294834* field0, Ttype294840* origty0); N_NIMCALL(Tnode294802*, newstrnode_295677_850551059)(Tnodekind294020 kind0, NimStringDesc* strval0); N_NIMCALL(void, gencast_558538_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genconv_558633_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, comparetypes_328214_3876443242)(Ttype294840* x0, Ttype294840* y0, Tdistinctcompare326427 cmp0, Ttypecmpflag326429Set flags0); N_NIMCALL(void, genaddr_555051_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); static N_INLINE(NIM_BOOL, iscppref_554807_839829468)(Tcproc531021* p0, Ttype294840* typ0); N_NIMCALL(void, genbracketexpr_556277_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genarrayelem_556093_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, isconstexpr_320510_2616423590)(Tnode294802* n0); N_NIMCALL(void, genopenarrayelem_556169_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0); N_NIMCALL(void, genseqelem_556205_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0); N_NIMCALL(void, gencstringelem_556144_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0); N_NIMCALL(void, gentupleelem_555124_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genderef_545921_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NIM_BOOL enforcederef0); N_NIMCALL(void, genrecordfield_555448_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(Ttype294840*, genrecordfieldaux_555096_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tloc294816* a0); N_NIMCALL(void, gencheckedrecordfield_556046_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genblock_548083_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(NI, startblock_545978_839829468)(Tcproc531021* p0, NimStringDesc* start0, Ropeobj180006** args0, NI args0Len0); N_NIMCALL(void, endblock_546060_839829468)(Tcproc531021* p0); N_NIMCALL(void, endblock_546035_839829468)(Tcproc531021* p0, Ropeobj180006* blockend0); N_NIMCALL(Ropeobj180006*, blockbody_546025_839829468)(Tblock531019* b0); N_NIMCALL(void, genstmtlistexpr_560402_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genif_546982_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, downconv_560581_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(NI, inheritancediff_328252_3876443242)(Ttype294840* a0, Ttype294840* b0); N_NIMCALL(void, upconv_560431_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genrangechck_558591_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0, NimStringDesc* magic0); N_NIMCALL(void, convstrtocstr_558643_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, convcstrtostr_558655_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, genclosure_559836_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); static N_INLINE(NIM_BOOL, isconstclosure_559810_839829468)(Tnode294802* n0); static N_INLINE(NIM_BOOL, isroutine_299324_850551059)(Tsym294834* s0); N_NIMCALL(void, genwhilestmt_547985_839829468)(Tcproc531021* p0, Tnode294802* t0); static N_INLINE(Ropeobj180006*, assignlabel_546020_839829468)(Tblock531019* b0); N_NIMCALL(NIM_BOOL, stmtscontainpragma_530083_2036603609)(Tnode294802* n0, Tspecialword277003 w0); N_NIMCALL(void, gencomputedgoto_547744_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, genvarstmt_546854_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, gensinglevar_546276_839829468)(Tcproc531021* p0, Tnode294802* a0); N_NIMCALL(void, gengotovar_546258_839829468)(Tcproc531021* p0, Tnode294802* value0); N_NIMCALL(void, assignglobalvar_540819_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(void, varindynamiclib_540812_839829468)(Tcgen531027* m0, Tsym294834* sym0); N_NIMCALL(void, registergcroot_545762_839829468)(Tcproc531021* p0, Tsym294834* v0); N_NIMCALL(Ropeobj180006*, gentraverseprocforglobal_540032_839829468)(Tcgen531027* m0, Tsym294834* s0); static N_INLINE(NIM_BOOL, isassignedimmediately_545781_839829468)(Tnode294802* n0); N_NIMCALL(NIM_BOOL, containshiddenpointer_322120_3876443242)(Ttype294840* typ0); static N_INLINE(void, loadinto_545928_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* a0); N_NIMCALL(void, genasgncall_545695_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0); N_NIMCALL(void, genclosurevar_546832_839829468)(Tcproc531021* p0, Tnode294802* a0); N_NIMCALL(void, genvartuple_545794_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Tnode294802*, lowertupleunpacking_435037_2218250499)(Tnode294802* n0, Tsym294834* owner0); N_NIMCALL(void, genconststmt_546909_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(NIM_BOOL, containscompiletimeonly_330721_3876443242)(Ttype294840* t0); static N_INLINE(NIM_BOOL, emitlazily_534248_839829468)(Tsym294834* s0); N_NIMCALL(void, gencase_549827_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(void, genstringcase_549417_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(NI, nextpoweroftwo_101629_1009420244)(NI x0); N_NIMCALL(void, gencasestringbranch_549100_839829468)(Tcproc531021* p0, Tnode294802* b0, Tloc294816* e0, Ropeobj180006* labl0, Ropeobj180006** branches0, NI branches0Len0); N_NIMCALL(NI64, hashstring_530100_2036603609)(NimStringDesc* s0); N_NIMCALL(Ropeobj180006*, gencasesecondpass_548965_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NI labid0, NI until0); N_NIMCALL(void, exprblock_546103_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, gencasegeneric_549087_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0); N_NIMCALL(Ropeobj180006*, genifforcaseuntil_549021_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc294816* a0); N_NIMCALL(void, gencasegenericbranch_548910_839829468)(Tcproc531021* p0, Tnode294802* b0, Tloc294816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj180006* labl0); N_NIMCALL(void, gengotoforcase_547673_839829468)(Tcproc531021* p0, Tnode294802* casestmt0); N_NIMCALL(void, genordinalcase_549725_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(NI, ifswitchsplitpoint_549616_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(NIM_BOOL, branchhastoobigrange_549576_839829468)(Tnode294802* b0); N_NIMCALL(void, genreturnstmt_547617_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(void, blockleaveactions_547442_839829468)(Tcproc531021* p0, NI howmanytrys0, NI howmanyexcepts0); static N_INLINE(Tnode294802*, pop_320246_1689653243)(Tnodeseq294796** s0); N_NIMCALL(void, genbreakstmt_548444_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(void, genasgn_551239_839829468)(Tcproc531021* p0, Tnode294802* e0, NIM_BOOL fastasgn0); N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_551080_839829468)(Tcproc531021* p0, Tnode294802* asgn0); N_NIMCALL(void, asgnfielddiscriminant_551209_839829468)(Tcproc531021* p0, Tnode294802* e0); N_NIMCALL(void, gendiscriminantcheck_551144_839829468)(Tcproc531021* p0, Tloc294816* a0, Tloc294816* tmp0, Ttype294840* objtype0, Tsym294834* field0); N_NIMCALL(Ropeobj180006*, discriminatortabledecl_538094_839829468)(Tcgen531027* m0, Ttype294840* objtype0, Tsym294834* d0); N_NIMCALL(void, genasmstmt_550659_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(Ropeobj180006*, genasmoremitstmt_550529_839829468)(Tcproc531021* p0, Tnode294802* t0, NIM_BOOL isasmstmt0); N_NIMCALL(NimStringDesc*, resizeString)(NimStringDesc* dest0, NI addlen0); N_NIMCALL(void, gentrycpp_549866_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); static N_INLINE(void, gensimpleblock_546095_839829468)(Tcproc531021* p0, Tnode294802* stmts0); N_NIMCALL(void, gentry_550114_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(NIM_BOOL, isdefined_202011_1967573533)(NimStringDesc* symbol0); N_NIMCALL(void, line_534695_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* r0); static N_INLINE(Ropeobj180006*, pop_180530_1689653243)(TY193350** s0); N_NIMCALL(void, genraisestmt_548828_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(NimStringDesc*, getraisefrmt_548824_839829468)(Tcproc531021* p0); N_NIMCALL(void, gentypesection_540184_839829468)(Tcgen531027* m0, Tnode294802* n0); N_NIMCALL(void, genpragma_551039_839829468)(Tcproc531021* p_551041_839829468, Tnode294802* n0); N_NIMCALL(Tspecialword277003, whichpragma_320911_2616423590)(Tnode294802* n0); N_NIMCALL(void, genemit_550839_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(Tcfilesection531005, determinesection_550819_839829468)(Tnode294802* n0); N_NIMCALL(NIM_BOOL, nsuStartsWith)(NimStringDesc* s0, NimStringDesc* prefix0); N_NIMCALL(void, genbreakpoint_550862_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(void, genwatchpoint_551016_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(Tsym294834*, skipgenericowner_299280_850551059)(Tsym294834* s0); N_NIMCALL(void, genparforstmt_548208_839829468)(Tcproc531021* p0, Tnode294802* t0); N_NIMCALL(void, genstate_546117_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, gengotostate_546144_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, genbreakstate_546229_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(void, registermoduletomain_564243_839829468)(Tsym294834* m0); N_NIMCALL(Ropeobj180006*, getinitname_564235_839829468)(Tsym294834* m0); N_NIMCALL(Ropeobj180006*, getsomeinitname_563904_839829468)(Tsym294834* m0, NimStringDesc* suffix0); N_NIMCALL(Ropeobj180006*, getdatinitname_564239_839829468)(Tsym294834* m0); N_NIMCALL(Tnode294802*, generatemethoddispatchers_434151_3853300031)(void); N_NIMCALL(void, genmainproc_563729_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, genfilenames_563688_839829468)(Tcgen531027* m0); N_NIMCALL(void, finishmodule_565420_839829468)(Tcgen531027* m0); N_NIMCALL(void, updatecachedmodule_565813_839829468)(Tcgen531027* m0); N_NIMCALL(NIM_BOOL, mergerequired_532832_2760143328)(Tcgen531027* m0); N_NIMCALL(void, mergefiles_533241_2760143328)(NimStringDesc* cfilename0, Tcgen531027* m0); N_NIMCALL(void, geninitcode_564286_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, gensectionstart_532081_2760143328)(Tcprocsection531011 ps0); N_NIMCALL(Ropeobj180006*, gensectionend_532116_2760143328)(Tcprocsection531011 ps0); N_NIMCALL(Ropeobj180006*, gensectionstart_532015_2760143328)(Tcfilesection531005 fs0); N_NIMCALL(Ropeobj180006*, gensectionend_532050_2760143328)(Tcfilesection531005 fs0); N_NIMCALL(void, finishtypedescriptions_537842_839829468)(Tcgen531027* m0); N_NIMCALL(Ropeobj180006*, genmodule_564491_839829468)(Tcgen531027* m0, NimStringDesc* cfile0); N_NIMCALL(Ropeobj180006*, getfileheader_563683_839829468)(NimStringDesc* cfile0); N_NIMCALL(Ropeobj180006*, getcopyright_563665_839829468)(NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, getcompilecfilecmd_276284_2528170400)(NimStringDesc* cfilename0, NIM_BOOL isexternal0); static N_INLINE(void, addinttypes_563659_839829468)(Ropeobj180006** result0); N_NIMCALL(Ropeobj180006*, genmergeinfo_532203_2760143328)(Tcgen531027* m0); N_NIMCALL(void, generatethreadlocalstorage_540717_839829468)(Tcgen531027* m0); N_NIMCALL(void, generateheaders_562104_839829468)(Tcgen531027* m0); N_NIMCALL(NimStringDesc*, nsuReplaceChar)(NimStringDesc* s0, NIM_CHAR sub0, NIM_CHAR by0); N_NIMCALL(void, writerope_180836_2381377266)(Ropeobj180006* head0, NimStringDesc* filename0, NIM_BOOL usewarning0); N_NIMCALL(void, addfiletocompile_275863_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, addfiletolink_275872_2528170400)(NimStringDesc* filename0); N_NIMCALL(void, writemodule_565637_839829468)(Tcgen531027* m0, NIM_BOOL pending0); N_NIMCALL(void, generatethreadvarssize_540771_839829468)(Tcgen531027* m0); N_NIMCALL(NIM_BOOL, shouldrecompile_565621_839829468)(Ropeobj180006* code0, NimStringDesc* cfile0); N_NIMCALL(NimStringDesc*, toobjfile_275859_2528170400)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, writeropeifnotequal_181511_2381377266)(Ropeobj180006* r0, NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosexistsFile)(NimStringDesc* filename0); N_NIMCALL(NIM_BOOL, nosfileNewer)(NimStringDesc* a0, NimStringDesc* b0); N_NIMCALL(void, writemapping_276789_2528170400)(Ropeobj180006* gsymbolmapping0); N_NIMCALL(void, writeheader_565149_839829468)(Tcgen531027* m0); N_NIMCALL(void, nossplitFile)(NimStringDesc* path0, TY129506* Result); N_NIMCALL(void, resetmodule_564763_839829468)(Tcgen531027* m0); N_NIMCALL(void, nullify_564833_839829468)(Ropeobj180006** arr0); N_NIMCALL(void, nullify_564858_839829468)(Ropeobj180006** arr0); STRING_LITERAL(T839829468_4, "\011", 1); STRING_LITERAL(T839829468_10, "compiler/cgen.nim", 17); NIM_CONST TY205018 T839829468_9 = {((NimStringDesc*) &T839829468_10), ((NI) 1158)} ; STRING_LITERAL(T839829468_11, "T", 1); STRING_LITERAL(T839829468_12, "_", 1); STRING_LITERAL(T839829468_13, "added pending module twice: ", 28); STRING_LITERAL(T839829468_14, ".h", 2); STRING_LITERAL(T839829468_15, ".cpp", 4); STRING_LITERAL(T839829468_16, ".m", 2); STRING_LITERAL(T839829468_17, ".c", 2); STRING_LITERAL(T839829468_18, "0", 1); STRING_LITERAL(T839829468_19, "$", 1); STRING_LITERAL(T839829468_20, "ropes: invalid format string $", 30); STRING_LITERAL(T839829468_21, "$N#line $2 $1$N", 15); STRING_LITERAL(T839829468_22, "N_LIB_IMPORT ", 13); STRING_LITERAL(T839829468_23, "N_LIB_EXPORT ", 13); STRING_LITERAL(T839829468_24, "static ", 7); STRING_LITERAL(T839829468_25, "mapType", 7); STRING_LITERAL(T839829468_26, "void", 4); STRING_LITERAL(T839829468_27, "getTypeDescAux: t == nil", 24); STRING_LITERAL(T839829468_28, "TY", 2); STRING_LITERAL(T839829468_29, "getTypeName: ", 13); STRING_LITERAL(T839829468_30, "void*", 5); STRING_LITERAL(T839829468_31, "NimStringDesc", 13); STRING_LITERAL(T839829468_32, "NimStringDesc*", 14); STRING_LITERAL(T839829468_33, "NCSTRING", 8); STRING_LITERAL(T839829468_34, "NIM_BOOL", 8); STRING_LITERAL(T839829468_35, "NIM_CHAR", 8); STRING_LITERAL(T839829468_36, "NI", 2); STRING_LITERAL(T839829468_37, "NI8", 3); STRING_LITERAL(T839829468_38, "NI16", 4); STRING_LITERAL(T839829468_39, "NI32", 4); STRING_LITERAL(T839829468_40, "NI64", 4); STRING_LITERAL(T839829468_41, "NF", 2); STRING_LITERAL(T839829468_42, "NF32", 4); STRING_LITERAL(T839829468_43, "NF64", 4); STRING_LITERAL(T839829468_44, "NF128", 5); STRING_LITERAL(T839829468_45, "NU", 2); STRING_LITERAL(T839829468_46, "NU8", 3); STRING_LITERAL(T839829468_47, "NU16", 4); STRING_LITERAL(T839829468_48, "NU32", 4); STRING_LITERAL(T839829468_49, "NU64", 4); NIM_CONST TY535943 Numericaltypetostr_535941_839829468 = {((NimStringDesc*) &T839829468_36), ((NimStringDesc*) &T839829468_37), ((NimStringDesc*) &T839829468_38), ((NimStringDesc*) &T839829468_39), ((NimStringDesc*) &T839829468_40), ((NimStringDesc*) &T839829468_41), ((NimStringDesc*) &T839829468_42), ((NimStringDesc*) &T839829468_43), ((NimStringDesc*) &T839829468_44), ((NimStringDesc*) &T839829468_45), ((NimStringDesc*) &T839829468_46), ((NimStringDesc*) &T839829468_47), ((NimStringDesc*) &T839829468_48), ((NimStringDesc*) &T839829468_49)} ; STRING_LITERAL(T839829468_50, "tyStatic for getSimpleTypeDesc", 30); STRING_LITERAL(T839829468_51, "cannot generate C type for: ", 28); STRING_LITERAL(T839829468_52, "&", 1); STRING_LITERAL(T839829468_53, "*", 1); STRING_LITERAL(T839829468_54, "$1 $2;$n", 8); STRING_LITERAL(T839829468_55, "typedef $1 $2 $2;$n", 19); STRING_LITERAL(T839829468_56, "union", 5); STRING_LITERAL(T839829468_57, "struct", 6); STRING_LITERAL(T839829468_58, "getTypeForward(", 15); STRING_LITERAL(T839829468_59, "typedef NI32 $1;$n", 18); STRING_LITERAL(T839829468_60, "typedef NU8 $1;$n", 17); STRING_LITERAL(T839829468_61, "typedef NU16 $1;$n", 18); STRING_LITERAL(T839829468_62, "typedef NI64 $1;$n", 18); STRING_LITERAL(T839829468_63, "getTypeDescAux: enum", 20); STRING_LITERAL(T839829468_64, "typedef $1_PTR($2, $3) $4;$n", 28); STRING_LITERAL(T839829468_65, "N_NIMCALL", 9); STRING_LITERAL(T839829468_66, "N_STDCALL", 9); STRING_LITERAL(T839829468_67, "N_CDECL", 7); STRING_LITERAL(T839829468_68, "N_SAFECALL", 10); STRING_LITERAL(T839829468_69, "N_SYSCALL", 9); STRING_LITERAL(T839829468_70, "N_INLINE", 8); STRING_LITERAL(T839829468_71, "N_NOINLINE", 10); STRING_LITERAL(T839829468_72, "N_FASTCALL", 10); STRING_LITERAL(T839829468_73, "N_CLOSURE", 9); STRING_LITERAL(T839829468_74, "N_NOCONV", 8); NIM_CONST TY294016 Callingconvtostr_535587_839829468 = {((NimStringDesc*) &T839829468_65), ((NimStringDesc*) &T839829468_66), ((NimStringDesc*) &T839829468_67), ((NimStringDesc*) &T839829468_68), ((NimStringDesc*) &T839829468_69), ((NimStringDesc*) &T839829468_70), ((NimStringDesc*) &T839829468_71), ((NimStringDesc*) &T839829468_72), ((NimStringDesc*) &T839829468_73), ((NimStringDesc*) &T839829468_74)} ; STRING_LITERAL(T839829468_75, "typedef struct {$nN_NIMCALL_PTR($2, ClPrc) $3;$nvoid* ClEnv;$n}" " $1;$n", 69); STRING_LITERAL(T839829468_76, "struct $2 : #TGenericSeq {$n", 28); STRING_LITERAL(T839829468_77, "struct $2 {$n #TGenericSeq Sup;$n", 34); STRING_LITERAL(T839829468_78, " $1 data[SEQ_DECL_SIZE];$n};$n", 31); STRING_LITERAL(T839829468_79, "TGenericSeq", 11); STRING_LITERAL(T839829468_80, "typedef $1 $2[$3];$n", 20); STRING_LITERAL(T839829468_81, "invalid apostrophe type parameter index", 39); STRING_LITERAL(T839829468_82, "<", 1); STRING_LITERAL(T839829468_83, " COMMA ", 7); STRING_LITERAL(T839829468_84, "> ", 2); extern NIM_CONST TY275427 Cc_275413_2528170400; STRING_LITERAL(T839829468_85, " {$n", 4); STRING_LITERAL(T839829468_86, " {$n#TNimType* m_type;$n", 24); STRING_LITERAL(T839829468_87, " : public $1 {$n", 16); STRING_LITERAL(T839829468_88, " {$n $1 Sup;$n", 15); STRING_LITERAL(T839829468_89, "genRecordFieldsAux", 18); STRING_LITERAL(T839829468_90, "$1.$2", 5); STRING_LITERAL(T839829468_91, "S", 1); STRING_LITERAL(T839829468_92, "struct {", 8); STRING_LITERAL(T839829468_93, "} $1;$n", 7); STRING_LITERAL(T839829468_94, "genRecordFieldsAux(record case branch)", 38); STRING_LITERAL(T839829468_95, "union{$n$1} $2;$n", 17); STRING_LITERAL(T839829468_96, "mangleRecFieldName", 18); STRING_LITERAL(T839829468_97, "$1 $2[SEQ_DECL_SIZE];$n", 23); STRING_LITERAL(T839829468_98, "$1 $2:$3;$n", 11); STRING_LITERAL(T839829468_99, "genRecordFieldsAux()", 20); STRING_LITERAL(T839829468_100, "char dummy;$n", 13); STRING_LITERAL(T839829468_101, "};", 2); STRING_LITERAL(T839829468_102, "$1 $2 {$n", 9); STRING_LITERAL(T839829468_103, "$1 Field$2;$n", 13); STRING_LITERAL(T839829468_104, "char dummy;", 11); STRING_LITERAL(T839829468_105, "Set", 3); STRING_LITERAL(T839829468_106, "typedef NU$2 $1;$n", 18); STRING_LITERAL(T839829468_107, "typedef NU8 $1[$2];$n", 21); STRING_LITERAL(T839829468_108, "getTypeDescAux(", 15); STRING_LITERAL(T839829468_109, "genProcParams", 13); STRING_LITERAL(T839829468_110, ", ", 2); STRING_LITERAL(T839829468_111, " ", 1); STRING_LITERAL(T839829468_112, ", NI $1Len$2", 12); STRING_LITERAL(T839829468_113, " Result", 7); STRING_LITERAL(T839829468_114, "void* ClEnv", 11); STRING_LITERAL(T839829468_115, "...", 3); STRING_LITERAL(T839829468_116, "void)", 5); STRING_LITERAL(T839829468_117, ")", 1); STRING_LITERAL(T839829468_118, "(", 1); STRING_LITERAL(T839829468_119, "$1($2, $3)$4", 12); STRING_LITERAL(T839829468_120, "proc has no result symbol", 25); STRING_LITERAL(T839829468_121, " register", 9); STRING_LITERAL(T839829468_122, " volatile", 9); STRING_LITERAL(T839829468_123, "$1 = $2;$n", 10); STRING_LITERAL(T839829468_124, "(*$1)", 5); STRING_LITERAL(T839829468_125, ";", 1); STRING_LITERAL(T839829468_126, "FR.s[$1].address = (void*)$3; FR.s[$1].typ = $4; FR.s[$1].name " "= $2;$n", 70); STRING_LITERAL(T839829468_127, "NTI$1", 5); STRING_LITERAL(T839829468_128, "(&", 2); STRING_LITERAL(T839829468_129, "TNimType", 8); STRING_LITERAL(T839829468_130, "TNimNode", 8); STRING_LITERAL(T839829468_131, "extern TNimType $1; /* $2 */$n", 30); STRING_LITERAL(T839829468_132, "0", 1); STRING_LITERAL(T839829468_133, "void*", 5); STRING_LITERAL(T839829468_134, "$1.size = sizeof($2);$n$1.kind = $3;$n$1.base = $4;$n", 53); STRING_LITERAL(T839829468_135, "$1.flags = $2;$n", 16); STRING_LITERAL(T839829468_136, "TNimType $1; /* $2 */$n", 23); STRING_LITERAL(T839829468_137, "genTypeInfo(", 12); STRING_LITERAL(T839829468_138, "$1[$2]", 6); STRING_LITERAL(T839829468_139, "static TNimNode* $1[$2];$n", 26); STRING_LITERAL(T839829468_140, "$1[$2] = &$3;$n", 15); STRING_LITERAL(T839829468_141, "$1.kind = 1;$n$1.offset = offsetof($2, Field$3);$n$1.typ = $4;$" "n$1.name = \"Field$3\";$n", 86); STRING_LITERAL(T839829468_142, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n", 45); STRING_LITERAL(T839829468_143, "$1.len = $2; $1.kind = 2;$n", 27); STRING_LITERAL(T839829468_144, "$1.node = &$2;$n", 16); STRING_LITERAL(T839829468_145, "#nimGCvisit((void*)$1, op);$n", 29); STRING_LITERAL(T839829468_146, "N_NIMCALL(void, $1)(void* p, NI op)", 35); STRING_LITERAL(T839829468_147, "$1 a;$n", 7); STRING_LITERAL(T839829468_148, "a = ($1)p;$n", 12); STRING_LITERAL(T839829468_149, "LOC", 3); STRING_LITERAL(T839829468_150, "$1 = ($2)0;$n", 13); STRING_LITERAL(T839829468_151, "<string.h>", 10); STRING_LITERAL(T839829468_152, "memset((void*)$1, 0, sizeof($2));$n", 35); STRING_LITERAL(T839829468_153, ".Sup", 4); STRING_LITERAL(T839829468_154, "$1.m_type = $2;$n", 17); STRING_LITERAL(T839829468_155, "#objectInit($1, $2);$n", 22); STRING_LITERAL(T839829468_156, "for ($1 = 0; $1 < $2->$3; $1++) {$n", 35); STRING_LITERAL(T839829468_157, "len", 3); STRING_LITERAL(T839829468_158, "Sup.len", 7); STRING_LITERAL(T839829468_159, "for ($1 = 0; $1 < $2; $1++) {$n", 31); STRING_LITERAL(T839829468_160, "}$n", 3); STRING_LITERAL(T839829468_161, "$1.Sup", 6); STRING_LITERAL(T839829468_162, "genTraverseProc", 15); STRING_LITERAL(T839829468_163, "switch ($1.$2) {$n", 18); STRING_LITERAL(T839829468_164, "case $1 ... $2:$n", 17); STRING_LITERAL(T839829468_165, "genLiteral: ty is nil", 21); STRING_LITERAL(T839829468_166, "(-2147483647 -1)", 16); STRING_LITERAL(T839829468_167, "IL64($1)", 8); STRING_LITERAL(T839829468_168, "(IL64(-9223372036854775807) - IL64(1))", 38); STRING_LITERAL(T839829468_169, "NIM_TRUE", 8); STRING_LITERAL(T839829468_170, "NIM_FALSE", 9); STRING_LITERAL(T839829468_171, "ULL", 3); STRING_LITERAL(T839829468_172, "(($1) $2)", 9); STRING_LITERAL(T839829468_173, "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n", 45); STRING_LITERAL(T839829468_174, "NIM_NIL", 7); STRING_LITERAL(T839829468_175, "((#NimStringDesc*) NIM_NIL)", 27); STRING_LITERAL(T839829468_176, "((#NimStringDesc*) &$1)", 23); STRING_LITERAL(T839829468_177, "STRING_LITERAL($1, $2, $3);$n", 29); STRING_LITERAL(T839829468_178, "((#NimStringDesc*) &$1$2)", 25); STRING_LITERAL(T839829468_179, "genLiteral(", 11); STRING_LITERAL(T839829468_180, "case $1:$n", 10); STRING_LITERAL(T839829468_181, "default:$n", 10); STRING_LITERAL(T839829468_182, "break;$n", 8); STRING_LITERAL(T839829468_183, "} $n", 4); STRING_LITERAL(T839829468_184, "genTraverseProc()", 17); STRING_LITERAL(T839829468_185, "$1.Field$2", 10); STRING_LITERAL(T839829468_186, "$1.ClEnv", 8); STRING_LITERAL(T839829468_187, "$1->data[$2]", 12); STRING_LITERAL(T839829468_188, "a", 1); STRING_LITERAL(T839829468_189, "(*a)", 4); STRING_LITERAL(T839829468_190, "$1 {$n$2$3$4}$n", 15); STRING_LITERAL(T839829468_191, "$1;$n", 5); STRING_LITERAL(T839829468_192, "$1.marker = $2;$n", 17); STRING_LITERAL(T839829468_193, "$1.len = $2; $1.kind = 0;$n$3.node = &$1;$n", 43); STRING_LITERAL(T839829468_194, "$1.offset = $2;$n", 17); STRING_LITERAL(T839829468_195, "NI $1;$n", 8); STRING_LITERAL(T839829468_196, "static char* NIM_CONST $1[$2] = {$n$3};$n", 41); STRING_LITERAL(T839829468_197, "for ($1 = 0; $1 < $2; $1++) {$n$3[$1+$4].kind = 1;$n$3[$1+$4].o" "ffset = $1;$n$3[$1+$4].name = $5[$1];$n$6[$1] = &$3[$1+$4];$n}$n", 127); STRING_LITERAL(T839829468_198, "$1.len = $2; $1.kind = 2; $1.sons = &$3[0];$n$4.node = &$1;$n", 61); STRING_LITERAL(T839829468_199, "$1.flags = 1<<2;$n", 18); STRING_LITERAL(T839829468_200, "anonymous obj with discriminator", 32); STRING_LITERAL(T839829468_201, "NimDT_$1_$2", 11); STRING_LITERAL(T839829468_202, "$1.kind = 3;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n$1.sons = &$6[0];$n$1.len = $7;$n", 107); STRING_LITERAL(T839829468_203, "TNimNode* $1[$2];$n", 19); STRING_LITERAL(T839829468_204, "genObjectFields; nkOfBranch broken", 34); STRING_LITERAL(T839829468_205, "genObjectFields(nkRecCase)", 26); STRING_LITERAL(T839829468_206, "$1.kind = 1;$n$1.offset = offsetof($2, $3);$n$1.typ = $4;$n$1.n" "ame = $5;$n", 74); STRING_LITERAL(T839829468_207, "genObjectFields", 15); STRING_LITERAL(T839829468_208, "$1.deepcopy =(void* (N_RAW_NIMCALL*)(void*))$2;$n", 49); STRING_LITERAL(T839829468_209, "\011return $1;$n", 13); STRING_LITERAL(T839829468_210, "Result", 6); STRING_LITERAL(T839829468_211, "closure generation failed", 25); STRING_LITERAL(T839829468_212, "$1 = ($2) ClEnv;$n", 18); STRING_LITERAL(T839829468_213, "__declspec(noreturn) ", 21); STRING_LITERAL(T839829468_214, "__declspec(naked) ", 18); STRING_LITERAL(T839829468_215, "$N$1 {$n$2$3$4}$N$N", 19); STRING_LITERAL(T839829468_216, "$N$1 {$N", 8); STRING_LITERAL(T839829468_217, "struct {$1} GCFRAME;$n", 22); STRING_LITERAL(T839829468_218, "nimFrame", 8); STRING_LITERAL(T839829468_219, "VarSlot", 7); STRING_LITERAL(T839829468_220, "\011nimfrs($1, $2, $3, $4)$N", 25); STRING_LITERAL(T839829468_221, "\011nimfr($1, $2)$N", 16); STRING_LITERAL(T839829468_222, "\011#nimProfile();$n", 17); STRING_LITERAL(T839829468_223, "{", 1); STRING_LITERAL(T839829468_224, "\011}BeforeRet: ;$n", 16); STRING_LITERAL(T839829468_225, "if (((NU)&GCFRAME) < 4096) #nimGCFrame(&GCFRAME);$n", 51); STRING_LITERAL(T839829468_226, "\011#popFrame();$n", 15); STRING_LITERAL(T839829468_227, "}$N", 3); STRING_LITERAL(T839829468_228, "static void* $1;$n", 18); STRING_LITERAL(T839829468_229, "||", 2); STRING_LITERAL(T839829468_230, "($1 = #nimLoadLibrary((#NimStringDesc*) &$2))$n", 47); STRING_LITERAL(T839829468_231, "if (!($1)) #nimLoadLibraryError((#NimStringDesc*) &$2);$n", 57); STRING_LITERAL(T839829468_232, "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", 60); STRING_LITERAL(T839829468_233, "loadDynamicLib", 14); STRING_LITERAL(T839829468_234, "Dl_$1", 5); STRING_LITERAL(T839829468_235, "\011$1 = ($2) ($3$4));$n", 21); NIM_CONST TY205018 T839829468_236 = {((NimStringDesc*) &T839829468_10), ((NI) 535)} ; STRING_LITERAL(T839829468_237, "wrong index: ", 13); STRING_LITERAL(T839829468_238, "\011$1 = ($2) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_239, "$2 $1;$n", 8); STRING_LITERAL(T839829468_240, "extern ", 7); STRING_LITERAL(T839829468_241, "NIM_THREADVAR ", 14); STRING_LITERAL(T839829468_242, " $1;$n", 6); STRING_LITERAL(T839829468_243, "cgsym: ", 7); STRING_LITERAL(T839829468_244, ": ", 2); STRING_LITERAL(T839829468_245, "extern $1 $2;$n", 15); STRING_LITERAL(T839829468_246, "extern \"C\" ", 11); STRING_LITERAL(T839829468_247, " __attribute__((naked))", 23); STRING_LITERAL(T839829468_248, " __attribute__((noreturn))", 26); STRING_LITERAL(T839829468_249, "#asgnRef((void**) $1, $2);$n", 28); STRING_LITERAL(T839829468_250, "#asgnRefNoCycle((void**) $1, $2);$n", 35); STRING_LITERAL(T839829468_251, "#unsureAsgnRef((void**) $1, $2);$n", 34); STRING_LITERAL(T839829468_252, "#genericSeqAssign($1, $2, $3);$n", 32); STRING_LITERAL(T839829468_253, "$1 = #copyString($2);$n", 23); STRING_LITERAL(T839829468_254, "$3 = $1; $1 = #copyStringRC1($2);$n", 35); STRING_LITERAL(T839829468_255, "if ($1) #nimGCunrefNoCycle($1);$n", 33); STRING_LITERAL(T839829468_256, "#unsureAsgnRef((void**) $1, #copyString($2));$n", 47); STRING_LITERAL(T839829468_257, ".", 1); STRING_LITERAL(T839829468_258, "ClEnv", 5); STRING_LITERAL(T839829468_259, "$1.ClPrc = $2.ClPrc;$n", 22); STRING_LITERAL(T839829468_260, "Field$1", 7); STRING_LITERAL(T839829468_261, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n", 53); STRING_LITERAL(T839829468_262, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n", 50); STRING_LITERAL(T839829468_263, "#genericAssign((void*)$1, (void*)$2, $3);$n", 43); STRING_LITERAL(T839829468_265, "compiler/ccgexprs.nim", 21); NIM_CONST TY205018 T839829468_264 = {((NimStringDesc*) &T839829468_265), ((NI) 320)} ; STRING_LITERAL(T839829468_266, "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 60); STRING_LITERAL(T839829468_267, "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len0);$n", 63); STRING_LITERAL(T839829468_268, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_269, "genAssignment: ", 15); STRING_LITERAL(T839829468_270, "request to generate code for .compileTime proc: ", 48); STRING_LITERAL(T839829468_271, "expr: proc not init ", 20); STRING_LITERAL(T839829468_272, "NIM_CONST $1 $2 = $3;$n", 23); STRING_LITERAL(T839829468_273, "{$n", 3); STRING_LITERAL(T839829468_274, "0x$1,$n", 7); STRING_LITERAL(T839829468_275, "0x$1, ", 6); STRING_LITERAL(T839829468_276, "0x$1}$n", 7); STRING_LITERAL(T839829468_277, "{{$1, $1}", 9); STRING_LITERAL(T839829468_278, ", {", 3); STRING_LITERAL(T839829468_279, ",$n", 3); STRING_LITERAL(T839829468_280, "}", 1); STRING_LITERAL(T839829468_281, "NIM_CONST struct {$n #TGenericSeq Sup;$n $1 data[$2];$n} $3 =" " $4;$n", 69); STRING_LITERAL(T839829468_282, "(($1)&$2)", 9); STRING_LITERAL(T839829468_283, "$1,$n", 5); STRING_LITERAL(T839829468_284, "extern NIM_CONST $1 $2;$n", 25); STRING_LITERAL(T839829468_285, "expr: var not init ", 19); STRING_LITERAL(T839829468_286, "\011NimThreadVars* NimTV;$n", 24); STRING_LITERAL(T839829468_287, "\011NimTV = (NimThreadVars*) #GetThreadLocalVars();$n", 50); STRING_LITERAL(T839829468_288, "NimTV->", 7); STRING_LITERAL(T839829468_289, "expr: temp not init ", 20); STRING_LITERAL(T839829468_290, "expr: param not init ", 21); STRING_LITERAL(T839829468_291, "expr(", 5); STRING_LITERAL(T839829468_292, "); unknown symbol", 17); STRING_LITERAL(T839829468_293, "//", 2); STRING_LITERAL(T839829468_294, "#endb($1, $2);$n", 16); STRING_LITERAL(T839829468_295, "nimln($1, $2);$n", 16); STRING_LITERAL(T839829468_296, "LA", 2); STRING_LITERAL(T839829468_297, "if ($1) goto $2;$n", 18); STRING_LITERAL(T839829468_298, "if (!($1)) goto $2;$n", 21); STRING_LITERAL(T839829468_299, "$1: ;$n", 7); STRING_LITERAL(T839829468_300, "!($1)", 5); STRING_LITERAL(T839829468_301, "$1", 2); STRING_LITERAL(T839829468_302, "($3)((NU$2) ~($1))", 18); STRING_LITERAL(T839829468_303, "-($1)", 5); STRING_LITERAL(T839829468_304, "($1 > 0? ($1) : -($1))", 22); STRING_LITERAL(T839829468_305, "(($3)(NU)(NU8)($1))", 19); STRING_LITERAL(T839829468_306, "(($3)(NU64)(NU8)($1))", 21); STRING_LITERAL(T839829468_307, "(($3)(NU)(NU16)($1))", 20); STRING_LITERAL(T839829468_308, "(($3)(NU64)(NU16)($1))", 22); STRING_LITERAL(T839829468_309, "(($3)(NU64)(NU32)($1))", 22); STRING_LITERAL(T839829468_310, "(($3)(NU64)(NU)($1))", 20); STRING_LITERAL(T839829468_311, "(($3)(NU8)(NU)($1))", 19); STRING_LITERAL(T839829468_312, "(($3)(NU16)(NU)($1))", 20); STRING_LITERAL(T839829468_313, "(($3)(NU32)(NU64)($1))", 22); STRING_LITERAL(T839829468_314, "((double) ($1))", 15); STRING_LITERAL(T839829468_315, "float64ToInt32($1)", 18); STRING_LITERAL(T839829468_316, "float64ToInt64($1)", 18); NIM_CONST TY554655 unarithtab_554653_839829468 = {((NimStringDesc*) &T839829468_300), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_302), ((NimStringDesc*) &T839829468_301), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304), ((NimStringDesc*) &T839829468_305), ((NimStringDesc*) &T839829468_306), ((NimStringDesc*) &T839829468_307), ((NimStringDesc*) &T839829468_308), ((NimStringDesc*) &T839829468_309), ((NimStringDesc*) &T839829468_310), ((NimStringDesc*) &T839829468_311), ((NimStringDesc*) &T839829468_312), ((NimStringDesc*) &T839829468_313), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_314), ((NimStringDesc*) &T839829468_315), ((NimStringDesc*) &T839829468_316)} ; STRING_LITERAL(T839829468_317, "if ($1 == $2) #raiseOverflow();$n", 33); STRING_LITERAL(T839829468_318, "((NI$2)-($1))", 13); NIM_CONST TY553642 opr_553640_839829468 = {((NimStringDesc*) &T839829468_318), ((NimStringDesc*) &T839829468_303), ((NimStringDesc*) &T839829468_304)} ; STRING_LITERAL(T839829468_319, "(($4)($2) $1 ($4)($3))", 22); STRING_LITERAL(T839829468_320, "+", 1); STRING_LITERAL(T839829468_321, "-", 1); STRING_LITERAL(T839829468_322, "/", 1); NIM_CONST TY558765 opr_558763_839829468 = {((NimStringDesc*) &T839829468_320), ((NimStringDesc*) &T839829468_321), ((NimStringDesc*) &T839829468_53), ((NimStringDesc*) &T839829468_322)} ; STRING_LITERAL(T839829468_323, "#nanCheck($1);$n", 16); STRING_LITERAL(T839829468_324, "#infCheck($1);$n", 16); STRING_LITERAL(T839829468_325, "(($4)($1) + ($4)($2))", 21); STRING_LITERAL(T839829468_326, "(($4)($1) - ($4)($2))", 21); STRING_LITERAL(T839829468_327, "(($4)($1) * ($4)($2))", 21); STRING_LITERAL(T839829468_328, "(($4)($1) / ($4)($2))", 21); STRING_LITERAL(T839829468_329, "($4)((NU$3)($1) >> (NU$3)($2))", 30); STRING_LITERAL(T839829468_330, "($4)((NU$3)($1) << (NU$3)($2))", 30); STRING_LITERAL(T839829468_331, "($4)($1 & $2)", 13); STRING_LITERAL(T839829468_332, "($4)($1 | $2)", 13); STRING_LITERAL(T839829468_333, "($4)($1 ^ $2)", 13); STRING_LITERAL(T839829468_334, "(($1 <= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_335, "(($1 >= $2) ? $1 : $2)", 22); STRING_LITERAL(T839829468_336, "($4)((NU$3)($1) + (NU$3)($2))", 29); STRING_LITERAL(T839829468_337, "($4)((NU$3)($1) - (NU$3)($2))", 29); STRING_LITERAL(T839829468_338, "($4)((NU$3)($1) * (NU$3)($2))", 29); STRING_LITERAL(T839829468_339, "($4)((NU$3)($1) / (NU$3)($2))", 29); STRING_LITERAL(T839829468_340, "($4)((NU$3)($1) % (NU$3)($2))", 29); STRING_LITERAL(T839829468_341, "($1 == $2)", 10); STRING_LITERAL(T839829468_342, "($1 <= $2)", 10); STRING_LITERAL(T839829468_343, "($1 < $2)", 9); STRING_LITERAL(T839829468_344, "((NU$3)($1) <= (NU$3)($2))", 26); STRING_LITERAL(T839829468_345, "((NU$3)($1) < (NU$3)($2))", 25); STRING_LITERAL(T839829468_346, "((NU64)($1) <= (NU64)($2))", 26); STRING_LITERAL(T839829468_347, "((NU64)($1) < (NU64)($2))", 25); STRING_LITERAL(T839829468_348, "((NU8)($1) == (NU8)($2))", 24); STRING_LITERAL(T839829468_349, "((NU8)($1) <= (NU8)($2))", 24); STRING_LITERAL(T839829468_350, "((NU8)($1) < (NU8)($2))", 23); STRING_LITERAL(T839829468_351, "($1 != $2)", 10); NIM_CONST TY553828 binarithtab_553826_839829468 = {((NimStringDesc*) &T839829468_325), ((NimStringDesc*) &T839829468_326), ((NimStringDesc*) &T839829468_327), ((NimStringDesc*) &T839829468_328), ((NimStringDesc*) &T839829468_329), ((NimStringDesc*) &T839829468_330), ((NimStringDesc*) &T839829468_331), ((NimStringDesc*) &T839829468_332), ((NimStringDesc*) &T839829468_333), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_334), ((NimStringDesc*) &T839829468_335), ((NimStringDesc*) &T839829468_336), ((NimStringDesc*) &T839829468_337), ((NimStringDesc*) &T839829468_338), ((NimStringDesc*) &T839829468_339), ((NimStringDesc*) &T839829468_340), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_344), ((NimStringDesc*) &T839829468_345), ((NimStringDesc*) &T839829468_346), ((NimStringDesc*) &T839829468_347), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_348), ((NimStringDesc*) &T839829468_349), ((NimStringDesc*) &T839829468_350), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_341), ((NimStringDesc*) &T839829468_342), ((NimStringDesc*) &T839829468_343), ((NimStringDesc*) &T839829468_351)} ; STRING_LITERAL(T839829468_352, "($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", 46); STRING_LITERAL(T839829468_353, "($#)($# + $#)", 13); STRING_LITERAL(T839829468_354, "($#)($# - $#)", 13); STRING_LITERAL(T839829468_355, "($#)($# * $#)", 13); STRING_LITERAL(T839829468_356, "($#)($# / $#)", 13); STRING_LITERAL(T839829468_357, "($#)($# % $#)", 13); NIM_CONST TY553281 opr_553279_839829468 = {((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354), ((NimStringDesc*) &T839829468_355), ((NimStringDesc*) &T839829468_356), ((NimStringDesc*) &T839829468_357), ((NimStringDesc*) &T839829468_353), ((NimStringDesc*) &T839829468_354)} ; STRING_LITERAL(T839829468_358, "((NU8)($1))", 11); STRING_LITERAL(T839829468_359, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", 43); STRING_LITERAL(T839829468_360, "$# = #addInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_361, "$# = #subInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_362, "$# = #mulInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_363, "$# = #divInt64($#, $#);$n", 25); STRING_LITERAL(T839829468_364, "$# = #modInt64($#, $#);$n", 25); NIM_CONST TY553281 prc64_553274_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361), ((NimStringDesc*) &T839829468_362), ((NimStringDesc*) &T839829468_363), ((NimStringDesc*) &T839829468_364), ((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; STRING_LITERAL(T839829468_365, "$# = #addInt($#, $#);$n", 23); STRING_LITERAL(T839829468_366, "$# = #subInt($#, $#);$n", 23); STRING_LITERAL(T839829468_367, "$# = #mulInt($#, $#);$n", 23); STRING_LITERAL(T839829468_368, "$# = #divInt($#, $#);$n", 23); STRING_LITERAL(T839829468_369, "$# = #modInt($#, $#);$n", 23); NIM_CONST TY553281 prc_553269_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366), ((NimStringDesc*) &T839829468_367), ((NimStringDesc*) &T839829468_368), ((NimStringDesc*) &T839829468_369), ((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_370, "($#)($#)", 8); STRING_LITERAL(T839829468_371, "#reprInt((NI64)$1)", 18); STRING_LITERAL(T839829468_372, "#reprFloat($1)", 14); STRING_LITERAL(T839829468_373, "#reprBool($1)", 13); STRING_LITERAL(T839829468_374, "#reprChar($1)", 13); STRING_LITERAL(T839829468_375, "#reprEnum((NI)$1, $2)", 21); STRING_LITERAL(T839829468_376, "#reprStr($1)", 12); STRING_LITERAL(T839829468_377, "#reprSet($1, $2)", 16); STRING_LITERAL(T839829468_378, "$1, $1Len0", 10); STRING_LITERAL(T839829468_379, "$1->data, $1->$2", 16); STRING_LITERAL(T839829468_380, "$1, $2", 6); STRING_LITERAL(T839829468_381, "genRepr()", 9); STRING_LITERAL(T839829468_382, "#reprOpenArray($1, $2)", 22); STRING_LITERAL(T839829468_383, "#reprAny($1, $2)", 16); STRING_LITERAL(T839829468_384, "\'repr\' doesn\'t support \'void\' type", 34); STRING_LITERAL(T839829468_385, "($1 - 1)", 8); STRING_LITERAL(T839829468_386, "#subInt($1, 1)", 14); STRING_LITERAL(T839829468_387, "binaryStmt", 10); STRING_LITERAL(T839829468_388, "$1 += $2;$n", 11); STRING_LITERAL(T839829468_389, "$1 -= $2;$n", 11); NIM_CONST TY559052 opr_559050_839829468 = {((NimStringDesc*) &T839829468_388), ((NimStringDesc*) &T839829468_389)} ; NIM_CONST TY559052 fun64_559055_839829468 = {((NimStringDesc*) &T839829468_360), ((NimStringDesc*) &T839829468_361)} ; NIM_CONST TY559052 fun_559060_839829468 = {((NimStringDesc*) &T839829468_365), ((NimStringDesc*) &T839829468_366)} ; STRING_LITERAL(T839829468_390, "#appendChar($1, $2);$n", 22); STRING_LITERAL(T839829468_391, "$1->$2 + ", 9); STRING_LITERAL(T839829468_392, "#appendString($1, $2);$n", 24); STRING_LITERAL(T839829468_393, "$1 = #rawNewString($2$3);$n", 27); STRING_LITERAL(T839829468_394, "$1 = #addChar($1, $2);$n", 24); STRING_LITERAL(T839829468_395, "$1 = #resizeString($1, $2$3);$n", 31); STRING_LITERAL(T839829468_396, "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n", 47); STRING_LITERAL(T839829468_397, "$1 = ($2) #incrSeqV2($1, sizeof($3));$n", 39); STRING_LITERAL(T839829468_398, "$1->data[$1->$2]", 16); STRING_LITERAL(T839829468_399, "++$1->$2;$n", 11); STRING_LITERAL(T839829468_400, "(($1) && ($1)->$2 == 0)", 23); STRING_LITERAL(T839829468_401, "#eqStrings($1, $2)", 18); STRING_LITERAL(T839829468_402, "(#cmpStrings($1, $2) <= 0)", 26); STRING_LITERAL(T839829468_403, "(#cmpStrings($1, $2) < 0)", 25); STRING_LITERAL(T839829468_404, "$1.ClPrc == 0", 13); STRING_LITERAL(T839829468_405, "$1 == 0", 7); STRING_LITERAL(T839829468_406, "#nimIntToStr($1)", 16); STRING_LITERAL(T839829468_407, "#nimInt64ToStr($1)", 18); STRING_LITERAL(T839829468_408, "#nimBoolToStr($1)", 17); STRING_LITERAL(T839829468_409, "#nimCharToStr($1)", 17); STRING_LITERAL(T839829468_410, "#nimFloatToStr($1)", 18); STRING_LITERAL(T839829468_411, "#cstrToNimstr($1)", 17); STRING_LITERAL(T839829468_412, "no \'of\' operator available for pure objects", 43); STRING_LITERAL(T839829468_413, "(($1) && ($2))", 14); STRING_LITERAL(T839829468_414, "$1.m_type == $2", 15); STRING_LITERAL(T839829468_415, "Nim_OfCheck_CACHE", 17); STRING_LITERAL(T839829468_416, "static TNimType* $#[2];$n", 25); STRING_LITERAL(T839829468_417, "#isObjWithCache($#.m_type, $#, $#)", 34); STRING_LITERAL(T839829468_418, "($1)", 4); STRING_LITERAL(T839829468_419, "sizeof($1)", 10); STRING_LITERAL(T839829468_420, "if ($1) #nimGCunref($1);$n", 26); STRING_LITERAL(T839829468_421, "($1) #newObjRC1($2, $3)", 23); STRING_LITERAL(T839829468_422, "($1) #newObj($2, $3)", 20); STRING_LITERAL(T839829468_423, "$1->finalizer = (void*)$2;$n", 28); STRING_LITERAL(T839829468_424, "($1) #newObj($2, sizeof($3))", 28); STRING_LITERAL(T839829468_425, "($1) #newSeqRC1($2, $3)", 23); STRING_LITERAL(T839829468_426, "($1) #newSeq($2, $3)", 20); STRING_LITERAL(T839829468_427, "($1)#nimNewSeqOfCap($2, $3)", 27); STRING_LITERAL(T839829468_428, "((NI)sizeof($1))", 16); STRING_LITERAL(T839829468_429, "(*($1*) ($2))", 13); STRING_LITERAL(T839829468_430, "(($1) ($2))", 11); STRING_LITERAL(T839829468_431, "($1Len0-1)", 10); STRING_LITERAL(T839829468_432, "$1Len0", 6); STRING_LITERAL(T839829468_433, "($1 ? (strlen($1)-1) : -1)", 26); STRING_LITERAL(T839829468_434, "($1 ? strlen($1) : 0)", 21); STRING_LITERAL(T839829468_435, "($1 ? ($1->Sup.len-1) : -1)", 27); STRING_LITERAL(T839829468_436, "($1 ? $1->Sup.len : 0)", 22); STRING_LITERAL(T839829468_437, "($1 ? ($1->len-1) : -1)", 23); STRING_LITERAL(T839829468_438, "($1 ? $1->len : 0)", 18); STRING_LITERAL(T839829468_439, "genArrayLen()", 13); STRING_LITERAL(T839829468_440, "($1->Sup.len)", 13); STRING_LITERAL(T839829468_441, "$1->len", 7); STRING_LITERAL(T839829468_442, "unaryStmt", 9); STRING_LITERAL(T839829468_443, "#nimGCref($1);$n", 16); STRING_LITERAL(T839829468_444, "#nimGCunref($1);$n", 18); STRING_LITERAL(T839829468_445, "$1 = #setLengthStr($1, $2);$n", 29); STRING_LITERAL(T839829468_446, "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n", 54); STRING_LITERAL(T839829468_447, "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n", 46); STRING_LITERAL(T839829468_448, "($1- $2)", 8); STRING_LITERAL(T839829468_449, "$1 |= ((", 8); STRING_LITERAL(T839829468_450, ")1)<<(($2)%(sizeof(", 19); STRING_LITERAL(T839829468_451, ")*8));$n", 8); STRING_LITERAL(T839829468_452, "$1 &= ~(((", 10); STRING_LITERAL(T839829468_453, ")1) << (($2) % (sizeof(", 23); STRING_LITERAL(T839829468_454, ")*8)));$n", 9); STRING_LITERAL(T839829468_455, "#countBits32($1)", 16); STRING_LITERAL(T839829468_456, "#countBits64($1)", 16); STRING_LITERAL(T839829468_457, "(($1 & ~ $2 ==0)&&($1 != $2))", 29); STRING_LITERAL(T839829468_458, "(($1 & ~ $2)==0)", 16); STRING_LITERAL(T839829468_459, "($1 & $2)", 9); STRING_LITERAL(T839829468_460, "($1 | $2)", 9); STRING_LITERAL(T839829468_461, "($1 & ~ $2)", 11); STRING_LITERAL(T839829468_462, "($1 ^ $2)", 9); STRING_LITERAL(T839829468_463, "fewCmps", 7); STRING_LITERAL(T839829468_464, "$1 >= $2 && $1 <= $3", 20); STRING_LITERAL(T839829468_465, "$1 == $2", 8); STRING_LITERAL(T839829468_466, " || ", 4); STRING_LITERAL(T839829468_467, "(($1 &(1U<<((NU)($2)&7U)))!=0)", 30); STRING_LITERAL(T839829468_468, "(($1 &(1U<<((NU)($2)&15U)))!=0)", 31); STRING_LITERAL(T839829468_469, "(($1 &(1U<<((NU)($2)&31U)))!=0)", 31); STRING_LITERAL(T839829468_470, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)", 36); STRING_LITERAL(T839829468_471, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)", 43); STRING_LITERAL(T839829468_472, "genSetOp()", 10); STRING_LITERAL(T839829468_473, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n", 34); STRING_LITERAL(T839829468_474, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n", 36); STRING_LITERAL(T839829468_475, "#cardSet($1, ", 13); STRING_LITERAL(T839829468_476, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$n", 88); STRING_LITERAL(T839829468_477, "for ($1 = 0; $1 < $2; $1++) { $n $3 = (($4[$1] & ~ $5[$1]) == " "0);$n if (!$3) break;}$nif ($3) $3 = (memcmp($4, $5, $2) != 0);" "$n", 129); STRING_LITERAL(T839829468_478, "|", 1); STRING_LITERAL(T839829468_479, "& ~", 3); STRING_LITERAL(T839829468_480, "^", 1); NIM_CONST TY558428 lookupopr_558426_839829468 = {((NimStringDesc*) &T839829468_476), ((NimStringDesc*) &T839829468_477), ((NimStringDesc*) &T839829468_52), ((NimStringDesc*) &T839829468_478), ((NimStringDesc*) &T839829468_479), ((NimStringDesc*) &T839829468_480)} ; STRING_LITERAL(T839829468_481, "(memcmp($1, $2, ", 16); STRING_LITERAL(T839829468_482, ")==0)", 5); STRING_LITERAL(T839829468_483, "for ($1 = 0; $1 < $2; $1++) $n $3[$1] = $4[$1] $6 $5[$1];$n", 60); STRING_LITERAL(T839829468_484, "genSetOp", 8); STRING_LITERAL(T839829468_485, "$1->data", 8); STRING_LITERAL(T839829468_486, "($1)+($2), ($3)-($2)+1", 22); STRING_LITERAL(T839829468_487, "(*$1)->data+($2), ($3)-($2)+1", 29); STRING_LITERAL(T839829468_488, "$1->data+($2), ($3)-($2)+1", 26); STRING_LITERAL(T839829468_489, "openArrayLoc: ", 14); STRING_LITERAL(T839829468_490, "", 0); STRING_LITERAL(T839829468_491, "(*$1)->data, (*$1)->$2", 22); STRING_LITERAL(T839829468_492, "$1.ClPrc($3$1.ClEnv)", 20); STRING_LITERAL(T839829468_493, "$1.ClEnv? $1.ClPrc($3$1.ClEnv):(($4)($1.ClPrc))($2)", 51); STRING_LITERAL(T839829468_494, "$1 = 0;$n", 9); STRING_LITERAL(T839829468_495, "#chckNil((void*)$1);$n", 22); STRING_LITERAL(T839829468_496, "#genericReset((void*)$1, $2);$n", 31); STRING_LITERAL(T839829468_497, ";$n", 3); STRING_LITERAL(T839829468_499, "compiler/ccgcalls.nim", 21); NIM_CONST TY205018 T839829468_498 = {((NimStringDesc*) &T839829468_499), ((NI) 423)} ; static NIM_CONST char136Set T839829468_500 = { 0x00, 0x00, 0x00, 0x00, 0x88, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} ; STRING_LITERAL(T839829468_501, "wrong argument count", 20); STRING_LITERAL(T839829468_502, "call expression expected for C++ pattern", 40); NIM_CONST TY205018 T839829468_503 = {((NimStringDesc*) &T839829468_499), ((NI) 328)} ; STRING_LITERAL(T839829468_504, "->", 2); STRING_LITERAL(T839829468_505, ");$n", 4); STRING_LITERAL(T839829468_506, "[", 1); NIM_CONST TY205018 T839829468_507 = {((NimStringDesc*) &T839829468_499), ((NI) 472)} ; STRING_LITERAL(T839829468_508, "varargs for objective C method?", 31); STRING_LITERAL(T839829468_509, "Result: ", 8); STRING_LITERAL(T839829468_510, "];$n", 4); STRING_LITERAL(T839829468_511, "]", 1); NIM_CONST TY205018 T839829468_512 = {((NimStringDesc*) &T839829468_265), ((NI) 925)} ; STRING_LITERAL(T839829468_513, "<stdio.h>", 9); STRING_LITERAL(T839829468_514, ", \"nil\"", 7); STRING_LITERAL(T839829468_515, ", $1? ($1)->data:\"nil\"", 22); STRING_LITERAL(T839829468_516, "printf($1$2);$n", 15); STRING_LITERAL(T839829468_517, "%s", 2); STRING_LITERAL(T839829468_518, "fflush(stdout);$n", 17); STRING_LITERAL(T839829468_519, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n", 45); STRING_LITERAL(T839829468_520, "#genericSeqDeepCopy($1, $2, $3);$n", 34); STRING_LITERAL(T839829468_521, "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len0, $3);$n", 62); STRING_LITERAL(T839829468_522, "genDeepCopy: ", 13); STRING_LITERAL(T839829468_523, "genMagicExpr: ", 14); STRING_LITERAL(T839829468_524, "static NIM_CONST $1 $2 = $3;$n", 30); STRING_LITERAL(T839829468_525, "memset($1, 0, sizeof($1));$n", 28); STRING_LITERAL(T839829468_526, "for ($1 = $3; $1 <= $4; $1++) $n$2[(NU)($1)>>3] |=(1U<<((NU)($1" ")&7U));$n", 72); STRING_LITERAL(T839829468_527, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n", 40); STRING_LITERAL(T839829468_528, "for ($1 = $3; $1 <= $4; $1++) $n$2 |=((", 39); STRING_LITERAL(T839829468_529, ")(1)<<(($1)%(sizeof(", 20); STRING_LITERAL(T839829468_530, "$1 |=((", 7); STRING_LITERAL(T839829468_531, ")(1)<<(($2)%(sizeof(", 20); STRING_LITERAL(T839829468_532, "genCheckedRecordField", 21); STRING_LITERAL(T839829468_533, "genObjConstr", 12); STRING_LITERAL(T839829468_534, "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n", 52); STRING_LITERAL(T839829468_535, "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n", 55); STRING_LITERAL(T839829468_536, "LOC$1.source", 12); STRING_LITERAL(T839829468_537, "union { $1 source; $2 dest; } LOC$3;$n", 38); STRING_LITERAL(T839829468_538, "LOC$#.dest", 10); STRING_LITERAL(T839829468_539, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n", 46); STRING_LITERAL(T839829468_540, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n", 45); STRING_LITERAL(T839829468_541, "$1[($2)- $3]", 12); STRING_LITERAL(T839829468_542, "if ((NU)($1) >= (NU)($2Len0)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_543, "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n", 50); STRING_LITERAL(T839829468_544, "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n", 51); STRING_LITERAL(T839829468_545, "genTupleElem", 12); STRING_LITERAL(T839829468_546, ".Field$1", 8); STRING_LITERAL(T839829468_547, "expr(nkBracketExpr, ", 20); STRING_LITERAL(T839829468_548, "genDeref ", 9); STRING_LITERAL(T839829468_549, "genRecordFieldAux", 17); STRING_LITERAL(T839829468_550, "genRecordField 3", 16); STRING_LITERAL(T839829468_551, ".$1", 3); STRING_LITERAL(T839829468_552, "} $1: ;$n", 9); STRING_LITERAL(T839829468_553, "FR.len-=$1;$n", 13); STRING_LITERAL(T839829468_554, "FR.len+=$1;$n", 13); STRING_LITERAL(T839829468_555, "if (!$1) goto $2;$n", 19); STRING_LITERAL(T839829468_556, "goto $1;$n", 10); STRING_LITERAL(T839829468_557, "genIf()", 7); STRING_LITERAL(T839829468_558, "->Sup", 5); STRING_LITERAL(T839829468_559, "$1 = &$2;$n", 11); STRING_LITERAL(T839829468_560, "if ($1) #chckObj($2.m_type, $3);$n", 34); STRING_LITERAL(T839829468_561, "#chckObj($1.m_type, $2);$n", 26); STRING_LITERAL(T839829468_562, "(($1)#$5($2, $3, $4))", 21); STRING_LITERAL(T839829468_563, "chckRangeF", 10); STRING_LITERAL(T839829468_564, "chckRange64", 11); STRING_LITERAL(T839829468_565, "chckRange", 9); STRING_LITERAL(T839829468_566, "CNSTCLOSURE", 11); STRING_LITERAL(T839829468_567, "closure to closure created", 26); STRING_LITERAL(T839829468_568, "$1.ClPrc = $2; $1.ClEnv = $3;$n", 31); STRING_LITERAL(T839829468_569, "while (1) {$n", 13); STRING_LITERAL(T839829468_570, "case statement must be exhaustive for computed goto", 51); STRING_LITERAL(T839829468_571, "case statement has too many cases for computed goto", 51); STRING_LITERAL(T839829468_572, "case statement has to start at 0 for computed goto", 50); STRING_LITERAL(T839829468_573, "no case statement found for computed goto", 41); STRING_LITERAL(T839829468_574, "TMP$1", 5); STRING_LITERAL(T839829468_575, "static void* $#[$#] = {", 23); STRING_LITERAL(T839829468_576, "&&TMP$#, ", 9); STRING_LITERAL(T839829468_577, "&&TMP$#};$n", 11); STRING_LITERAL(T839829468_578, "goto *$#[$#];$n", 15); STRING_LITERAL(T839829468_579, "range notation not available for computed goto", 46); STRING_LITERAL(T839829468_580, "TMP$#:$n", 8); STRING_LITERAL(T839829468_581, "#nimProfile();$n", 16); STRING_LITERAL(T839829468_582, "\'goto\' target must be a literal value", 37); STRING_LITERAL(T839829468_583, "goto NIMSTATE_$#;$n", 19); STRING_LITERAL(T839829468_584, "$1 = ($2*) #nimGetProcAddr($3, $4);$n", 37); STRING_LITERAL(T839829468_585, "$2* $1;$n", 9); STRING_LITERAL(T839829468_586, "#dbgRegisterGlobal($1, &$2, $3);$n", 34); STRING_LITERAL(T839829468_587, "#nimGCvisit((void*)$1, 0);$n", 28); STRING_LITERAL(T839829468_588, "N_NIMCALL(void, $1)(void)", 25); STRING_LITERAL(T839829468_589, "#nimRegisterGlobalMarker($1);$n", 31); STRING_LITERAL(T839829468_590, "$#($#);$n", 9); STRING_LITERAL(T839829468_591, "$# = $#;$n", 10); STRING_LITERAL(T839829468_592, "genVarTuple", 11); STRING_LITERAL(T839829468_593, "genConstStmt", 12); STRING_LITERAL(T839829468_594, "for statement not eliminated", 28); STRING_LITERAL(T839829468_595, "if (#eqStrings($1, $2)) goto $3;$n", 34); STRING_LITERAL(T839829468_596, "switch (#hashString($1) & $2) {$n", 33); STRING_LITERAL(T839829468_597, "case $1: $n$2break;$n", 21); STRING_LITERAL(T839829468_598, "goto LA$1;$n", 12); STRING_LITERAL(T839829468_599, "LA$1: ;$n", 9); STRING_LITERAL(T839829468_600, "if ($1 >= $2 && $1 <= $3) goto $4;$n", 36); STRING_LITERAL(T839829468_601, "if ($1 == $2) goto $3;$n", 24); STRING_LITERAL(T839829468_602, "NIMSTATE_$#:$n", 14); STRING_LITERAL(T839829468_603, "switch ($1) {$n", 15); STRING_LITERAL(T839829468_604, "default: __assume(0);$n", 23); STRING_LITERAL(T839829468_605, "#popSafePoint();$n", 18); STRING_LITERAL(T839829468_606, "#popCurrentException();$n", 25); STRING_LITERAL(T839829468_607, "if ($1.status != 0) #popCurrentException();$n", 45); STRING_LITERAL(T839829468_608, "goto BeforeRet;$n", 17); STRING_LITERAL(T839829468_609, "no loop to break", 16); STRING_LITERAL(T839829468_610, "extern $1", 9); STRING_LITERAL(T839829468_611, "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n", 62); STRING_LITERAL(T839829468_612, "genAsmOrEmitStmt()", 18); STRING_LITERAL(T839829468_613, "\"", 1); STRING_LITERAL(T839829468_614, "\\n\"\012", 4); STRING_LITERAL(T839829468_615, "Exception", 9); STRING_LITERAL(T839829468_616, "E_Base", 6); STRING_LITERAL(T839829468_617, "try {$n", 7); STRING_LITERAL(T839829468_618, "} catch (NimException& $1) {$n", 30); STRING_LITERAL(T839829468_619, "#setFrame((TFrame*)&FR);$n", 26); STRING_LITERAL(T839829468_620, "else ", 5); STRING_LITERAL(T839829468_621, "#isObj($1.exp->m_type, $2)", 26); STRING_LITERAL(T839829468_622, "if ($1) ", 8); STRING_LITERAL(T839829468_623, "throw;$n", 8); STRING_LITERAL(T839829468_624, "<setjmp.h>", 10); STRING_LITERAL(T839829468_625, "#TSafePoint $1;$n", 17); STRING_LITERAL(T839829468_626, "#pushSafePoint(&$1);$n", 22); STRING_LITERAL(T839829468_627, "nimStdSetjmp", 12); STRING_LITERAL(T839829468_628, "$1.status = setjmp($1.context);$n", 33); STRING_LITERAL(T839829468_629, "nimSigSetjmp", 12); STRING_LITERAL(T839829468_630, "$1.status = sigsetjmp($1.context, 0);$n", 39); STRING_LITERAL(T839829468_631, "nimRawSetjmp", 12); STRING_LITERAL(T839829468_632, "$1.status = _setjmp($1.context);$n", 34); STRING_LITERAL(T839829468_633, "if ($1.status == 0) {$n", 23); STRING_LITERAL(T839829468_634, "else {$n", 8); STRING_LITERAL(T839829468_635, "else", 4); STRING_LITERAL(T839829468_636, "$1.status = 0;$n", 16); STRING_LITERAL(T839829468_637, "#isObj(#getCurrentException()->Sup.m_type, $1)", 46); STRING_LITERAL(T839829468_638, "#isObj(#getCurrentException()->m_type, $1)", 42); STRING_LITERAL(T839829468_639, "if ($1) {$n", 11); STRING_LITERAL(T839829468_640, "if ($1.status != 0) #reraiseException();$n", 42); STRING_LITERAL(T839829468_641, "#raiseException((#Exception*)$1, $2);$n", 39); STRING_LITERAL(T839829468_642, "#reraiseException();$n", 22); STRING_LITERAL(T839829468_643, "/*TYPESECTION*/", 15); STRING_LITERAL(T839829468_644, "/*VARSECTION*/", 14); STRING_LITERAL(T839829468_645, "/*INCLUDESECTION*/", 18); STRING_LITERAL(T839829468_646, "bp", 2); STRING_LITERAL(T839829468_647, "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", 57); STRING_LITERAL(T839829468_648, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n", 47); STRING_LITERAL(T839829468_649, "#pragma omp parallel for $4$nfor ($1 = $2; $1 <= $3; ++$1)", 58); STRING_LITERAL(T839829468_651, "compiler/ccgstmts.nim", 21); NIM_CONST TY205018 T839829468_650 = {((NimStringDesc*) &T839829468_651), ((NI) 145)} ; STRING_LITERAL(T839829468_652, "STATE$1: ;$n", 12); STRING_LITERAL(T839829468_653, "case -1: goto BeforeRet;$n", 26); STRING_LITERAL(T839829468_654, "case $1: goto STATE$1;$n", 24); STRING_LITERAL(T839829468_655, "if (((NI*) $1)[0] < 0) break;$n", 31); STRING_LITERAL(T839829468_656, "if ((((NI*) $1.ClEnv)[0]) < 0) break;$n", 39); STRING_LITERAL(T839829468_657, "); unknown node kind", 20); NIM_CONST TY205018 T839829468_658 = {((NimStringDesc*) &T839829468_651), ((NI) 1122)} ; STRING_LITERAL(T839829468_659, "Init000", 7); STRING_LITERAL(T839829468_660, "DatInit000", 10); STRING_LITERAL(T839829468_661, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", 41); STRING_LITERAL(T839829468_662, "\011$1();$N", 8); STRING_LITERAL(T839829468_663, "N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDECL(void, NimMa" "in)(void) {$N\011void (*volatile inner)();$N\011PreMain();$N\011inner = N" "imMainInner;$N$2\011(*inner)();$N}$N$N", 162); STRING_LITERAL(T839829468_664, "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N " " HINSTANCE hPrevInstance, $N LP" "STR lpCmdLine, int nCmdShow) {$N\011NimMain();$N\011return nim_program" "_result;$N}$N$N", 206); STRING_LITERAL(T839829468_665, "N_LIB_EXPORT N_CDECL(void, NimMainInner)(void) {$N$1}$N$NN_CDEC" "L(void, NimMain)(void) {$N\011void (*volatile inner)();$N\011PreMain()" ";$N\011inner = NimMainInner;$N$2\011(*inner)();$N}$N$N", 175); STRING_LITERAL(T839829468_666, "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N " " LPVOID lpvReserved) {$N\011if(fwdreason == DLL_PROC" "ESS_ATTACH) {$N\011NimMain();$N}$N\011return 1;$N}$N$N", 175); STRING_LITERAL(T839829468_667, "<windows.h>", 11); STRING_LITERAL(T839829468_668, "void NIM_POSIX_INIT NimMainInit(void) {$N\011NimMain();$N}$N$N", 59); STRING_LITERAL(T839829468_669, "int cmdCount;$Nchar** cmdLine;$Nchar** gEnv;$NN_CDECL(void, Nim" "MainInner)(void) {$N$1}$N$NN_CDECL(void, NimMain)(void) {$N\011void" " (*volatile inner)();$N\011PreMain();$N\011inner = NimMainInner;$N$2\011(" "*inner)();$N}$N$N", 208); STRING_LITERAL(T839829468_670, "int main(void) {$N\011NimMain();$N\011return 0;$N}$N$N", 48); STRING_LITERAL(T839829468_671, "int main(int argc, char** args, char** env) {$N\011cmdLine = args;" "$N\011cmdCount = argc;$N\011gEnv = env;$N\011NimMain();$N\011return nim_prog" "ram_result;$N}$N$N", 145); STRING_LITERAL(T839829468_672, "dbgRegisterBreakpoint", 21); STRING_LITERAL(T839829468_673, "dbgRegisterFilename", 19); STRING_LITERAL(T839829468_674, "dbgRegisterFilename($1);$N", 26); STRING_LITERAL(T839829468_675, "\011#initStackBottomWith((void *)&inner);$N", 40); STRING_LITERAL(T839829468_676, "void PreMainInner() {$N\011systemInit000();$N$1$2$3}$N$Nvoid PreMa" "in() {$N\011void (*volatile inner)();$N\011systemDatInit000();$N\011inner" " = PreMainInner;$N$4$5\011(*inner)();$N}$N$N", 168); STRING_LITERAL(T839829468_677, "\011#initThreadVarsEmulation();$N", 30); STRING_LITERAL(T839829468_678, "still forwarded: ", 17); STRING_LITERAL(T839829468_679, "NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N", 42); STRING_LITERAL(T839829468_680, "static #TNimNode $1[$2];$n", 26); STRING_LITERAL(T839829468_681, "static #TNimType $1[$2];$n", 26); STRING_LITERAL(T839829468_682, "\011TFrame FR; FR.len = 0;$N", 25); STRING_LITERAL(T839829468_683, "}$N$N", 5); STRING_LITERAL(T839829468_684, "N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N", 46); STRING_LITERAL(T839829468_685, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N", 131); STRING_LITERAL(T839829468_686, "0.15.0", 6); STRING_LITERAL(T839829468_687, "/* Generated by Nim Compiler v$1 */$N/* (c) 2016 Andreas Rump" "f */$N/* The generated code is subject to the original license. " "*/$N/* Compiled for: $2, $3, $4 */$N/* Command for C compiler:$n" " $5 */$N", 201); extern NIM_CONST TY178082 Os_178068_4151366050; extern NIM_CONST TY178510 Cpu_178496_4151366050; STRING_LITERAL(T839829468_688, "#define NIM_INTBITS $1", 22); STRING_LITERAL(T839829468_689, "typedef struct {$1} NimThreadVars;$n", 36); STRING_LITERAL(T839829468_690, "#include \"nimbase.h\"", 20); STRING_LITERAL(T839829468_691, "#include \"$1\"$N", 15); STRING_LITERAL(T839829468_692, "#include $1$N", 13); STRING_LITERAL(T839829468_693, "extern \"C\"", 10); STRING_LITERAL(T839829468_694, "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n", 61); STRING_LITERAL(T839829468_695, "__$1__", 6); STRING_LITERAL(T839829468_696, "#ifndef $1$n#define $1$n", 24); STRING_LITERAL(T839829468_697, "N_CDECL(void, NimMain)(void);$n", 31); STRING_LITERAL(T839829468_698, "#endif /* $1 */$n", 17); Tcgen531027* generatedheader_534201_839829468; extern TNimType NTI531015; /* BModule */ Ropeobj180006* indent_534655_839829468; extern TNimType NTI180004; /* Rope */ extern Gcheap49818 gch_49858_1689653243; Ropeobj180006* nimtv_540656_839829468; Ttypeseq294836* nimtvdeps_540674_839829468; extern TNimType NTI294836; /* TTypeSeq */ Intset270030 nimtvdeclared_540675_839829468; extern TNimType NTI270030; /* IntSet */ NI breakpointid_550860_839829468; Ropeobj180006* gbreakpoints_550861_839829468; extern TY531153* gmodules_531170_3723162438; extern TNimType NTI531027; /* TCGen */ extern Debuginfo205009 gdebuginfo_205470_1926258066; extern Toption171009Set goptions_171128_2607990831; extern TNimType NTI294804; /* TSymSeq */ extern Tglobaloption171013Set gglobaloptions_171130_2607990831; extern NimStringDesc* headerfile_171138_2607990831; extern NimStringDesc* gprojectfull_171211_2607990831; extern Tcommands171076 gcmd_171132_2607990831; extern NI gerrorcounter_194069_155036129; extern Ropeobj180006* rnl_180903_2381377266; extern NI gforwardedprocscounter_531171_3723162438; extern TNimType NTI294244; /* TTypeKind */ extern TNimType NTI205017; /* seq[(string, int)] */ extern Tsystemcc275002 ccompiler_275431_2528170400; extern NimStringDesc* tnl_178644_4151366050; extern NI floatsize_178642_4151366050; extern Tgcmode171080 gselectedgc_171133_2607990831; extern TNimType NTI294020; /* TNodeKind */ extern TNimType NTI136002; /* seq[string] */ extern TNimType NTI294435; /* TSymKind */ extern TNimType NTI294816; /* TLoc */ extern NI intsize_178641_4151366050; extern TNimType NTI294524; /* TMagic */ extern TNimType NTI193350; /* seq[Rope] */ extern TNimType NTI294796; /* TNodeSeq */ extern Ropeobj180006* mainmodprocs_531148_3723162438; extern Ropeobj180006* maindatinit_531151_3723162438; extern Ropeobj180006* mainmodinit_531149_3723162438; extern Ropeobj180006* othermodsinit_531150_3723162438; extern Tsystemos178004 targetos_178629_4151366050; extern TY193612* fileinfos_193629_155036129; extern Tsystemcpu178452 targetcpu_178627_4151366050; extern Ropeobj180006* gmapping_531152_3723162438; N_NIMCALL(void, T839829468_2)(void) { nimGCvisit((void*)generatedheader_534201_839829468, 0); } N_NIMCALL(void, T839829468_3)(void) { nimGCvisit((void*)indent_534655_839829468, 0); } static N_INLINE(Cell47305*, usrtocell_51440_1689653243)(void* usr0) { Cell47305* result0; result0 = (Cell47305*)0; result0 = ((Cell47305*) ((NI)((NU64)(((NI) (usr0))) - (NU64)(((NI)sizeof(Cell47305)))))); return result0; } static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47305* c0) { addzct_51417_1689653243((&gch_49858_1689653243.zct), c0); } static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0) { { Cell47305* c0; if (!!((src0 == NIM_NIL))) goto LA3; c0 = usrtocell_51440_1689653243(src0); (*c0).refcount += ((NI) 8); } LA3: ; { Cell47305* c0; if (!!(((*dest0) == NIM_NIL))) goto LA7; c0 = usrtocell_51440_1689653243((*dest0)); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA11; rtladdzct_52601_1689653243(c0); } LA11: ; } LA7: ; (*dest0) = src0; } N_NIMCALL(void, T839829468_5)(void) { nimGCvisit((void*)nimtv_540656_839829468, 0); } N_NIMCALL(void, T839829468_6)(void) { nimGCvisit((void*)nimtvdeps_540674_839829468, 0); } static N_INLINE(void, nimGCunrefNoCycle)(void* p0) { Cell47305* c0; c0 = usrtocell_51440_1689653243(p0); { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52601_1689653243(c0); } LA3: ; } N_NIMCALL(void, T839829468_7)(void) { nimGCvisit((void*)nimtvdeclared_540675_839829468.head, 0); nimGCvisit((void*)nimtvdeclared_540675_839829468.data, 0); } N_NIMCALL(void, T839829468_8)(void) { nimGCvisit((void*)gbreakpoints_550861_839829468, 0); } N_NIMCALL(Tcgen531027*, getcgenmodule_534226_839829468)(Tsym294834* s0) { Tcgen531027* result0; result0 = (Tcgen531027*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (((NI) 0) <= (*s0).position); if (!(LOC3)) goto LA4; LOC3 = ((*s0).position < (gmodules_531170_3723162438 ? gmodules_531170_3723162438->Sup.len : 0)); LA4: ; if (!LOC3) goto LA5; result0 = gmodules_531170_3723162438->data[(*s0).position]; } goto LA1; LA5: ; { result0 = NIM_NIL; } LA1: ; return result0; } static N_INLINE(void, copymem_7485_1689653243)(void* dest0, void* source0, NI size0) { void* LOC1; LOC1 = (void*)0; LOC1 = memcpy(dest0, source0, ((size_t) (size0))); } static N_INLINE(void, appendString)(NimStringDesc* dest0, NimStringDesc* src0) { copymem_7485_1689653243(((void*) ((&(*dest0).data[((*dest0).Sup.len)- 0]))), ((void*) ((*src0).data)), ((NI) ((NI)((*src0).Sup.len + ((NI) 1))))); (*dest0).Sup.len += (*src0).Sup.len; } N_NIMCALL(NU32, hashowner_534977_839829468)(Tsym294834* s0) { NU32 result0; Tsym294834* m0; Tsym294834* p0; result0 = (NU32)0; m0 = s0; { while (1) { if (!!(((*m0).kind == ((Tsymkind294435) 6)))) goto LA2; m0 = (*m0).owner; } LA2: ; } p0 = (*m0).owner; result0 = register_205121_1926258066((&gdebuginfo_205470_1926258066), (*(*p0).name).s, (*(*m0).name).s); return result0; } static N_INLINE(void, incref_53419_1689653243)(Cell47305* c0) { (*c0).refcount = (NI)((NU64)((*c0).refcount) + (NU64)(((NI) 8))); } static N_INLINE(void, decref_53001_1689653243)(Cell47305* c0) { { (*c0).refcount -= ((NI) 8); if (!((NU64)((*c0).refcount) < (NU64)(((NI) 8)))) goto LA3; rtladdzct_52601_1689653243(c0); } LA3: ; } static N_INLINE(void, asgnRef)(void** dest0, void* src0) { { Cell47305* LOC5; if (!!((src0 == NIM_NIL))) goto LA3; LOC5 = (Cell47305*)0; LOC5 = usrtocell_51440_1689653243(src0); incref_53419_1689653243(LOC5); } LA3: ; { Cell47305* LOC10; if (!!(((*dest0) == NIM_NIL))) goto LA8; LOC10 = (Cell47305*)0; LOC10 = usrtocell_51440_1689653243((*dest0)); decref_53001_1689653243(LOC10); } LA8: ; (*dest0) = src0; } N_NIMCALL(Toption171009Set, initprocoptions_564635_839829468)(Tcgen531027* m0) { Toption171009Set result0; memset((void*)(&result0), 0, sizeof(result0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 13))&31U)))!=0)) goto LA3; result0 = (goptions_171128_2607990831 & ~ 32768); } goto LA1; LA3: ; { result0 = goptions_171128_2607990831; } LA1: ; return result0; } N_NIMCALL(Tcproc531021*, newpreinitproc_564625_839829468)(Tcgen531027* m0) { Tcproc531021* result0; result0 = (Tcproc531021*)0; result0 = newproc_531206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 100000); return result0; } N_NIMCALL(Tcproc531021*, newpostinitproc_564630_839829468)(Tcgen531027* m0) { Tcproc531021* result0; result0 = (Tcproc531021*)0; result0 = newproc_531206_3723162438(NIM_NIL, m0); (*result0).labels = ((NI) 200000); return result0; } N_NIMCALL(Ropeobj180006*, gettempname_535598_839829468)(Tcgen531027* m0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = rope_180401_2381377266(((NI64) ((*m0).labels))); result0 = HEX26_180418_2381377266((*m0).tmpbase, LOC1); (*m0).labels += ((NI) 1); return result0; } N_NIMCALL(Tcgen531027*, rawnewmodule_564663_839829468)(Tsym294834* module0, NimStringDesc* filename0) { Tcgen531027* result0; NimStringDesc* LOC1; NU32 LOC2; NimStringDesc* LOC3; NimStringDesc* LOC4; NimStringDesc* LOC5; result0 = (Tcgen531027*)0; result0 = (Tcgen531027*) newObj((&NTI531015), sizeof(Tcgen531027)); (*result0).Sup.Sup.m_type = (&NTI531027); LOC1 = (NimStringDesc*)0; LOC2 = (NU32)0; LOC2 = hashowner_534977_839829468(module0); LOC3 = (NimStringDesc*)0; LOC3 = HEX24_8401_1689653243(((NU64) (LOC2))); LOC1 = rawNewString(LOC3->Sup.len + 2); appendString(LOC1, ((NimStringDesc*) &T839829468_11)); appendString(LOC1, LOC3); appendString(LOC1, ((NimStringDesc*) &T839829468_12)); asgnRefNoCycle((void**) (&(*result0).tmpbase), rope_180277_2381377266(LOC1)); initlinkedlist_148031_3771138726((&(*result0).headerfiles)); initintset_270885_2627731572((&(*result0).declaredthings)); initintset_270885_2627731572((&(*result0).declaredprotos)); LOC4 = (NimStringDesc*)0; LOC4 = (*result0).cfilename; (*result0).cfilename = copyStringRC1(filename0); if (LOC4) nimGCunrefNoCycle(LOC4); LOC5 = (NimStringDesc*)0; LOC5 = (*result0).filename; (*result0).filename = copyStringRC1(filename0); if (LOC5) nimGCunrefNoCycle(LOC5); initidtable_298019_850551059((&(*result0).typecache)); initidtable_298019_850551059((&(*result0).forwtypecache)); asgnRefNoCycle((void**) (&(*result0).module), module0); initintset_270885_2627731572((&(*result0).typeinfomarker)); asgnRef((void**) (&(*result0).initproc), newproc_531206_3723162438(NIM_NIL, result0)); (*(*result0).initproc).options = initprocoptions_564635_839829468(result0); asgnRef((void**) (&(*result0).preinitproc), newpreinitproc_564625_839829468(result0)); asgnRef((void**) (&(*result0).postinitproc), newpostinitproc_564630_839829468(result0)); initnodetable_298085_850551059((&(*result0).datacache)); if ((*result0).typestack) nimGCunrefNoCycle((*result0).typestack); (*result0).typestack = (Ttypeseq294836*) newSeqRC1((&NTI294836), 0); if ((*result0).forwardedprocs) nimGCunrefNoCycle((*result0).forwardedprocs); (*result0).forwardedprocs = (Tsymseq294804*) newSeqRC1((&NTI294804), 0); asgnRefNoCycle((void**) (&(*result0).typenodesname), gettempname_535598_839829468(result0)); asgnRefNoCycle((void**) (&(*result0).nimtypesname), gettempname_535598_839829468(result0)); { if (!(((*module0).flags &(1U<<((NU)(((Tsymflag294184) 13))&31U)))!=0)) goto LA8; (*result0).flags |= ((NU8)1)<<((((Codegenflag531025) 0))%(sizeof(NU8)*8)); (*(*result0).preinitproc).options &= ~(((NU32)1) << ((((Toption171009) 15)) % (sizeof(NU32)*8))); (*(*result0).postinitproc).options &= ~(((NU32)1) << ((((Toption171009) 15)) % (sizeof(NU32)*8))); } LA8: ; return result0; } N_NIMCALL(Tcgen531027*, rawnewmodule_565038_839829468)(Tsym294834* module0) { Tcgen531027* result0; NimStringDesc* LOC1; result0 = (Tcgen531027*)0; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_194261_155036129(((NI32) ((*module0).position))); result0 = rawnewmodule_564663_839829468(module0, LOC1); return result0; } N_NIMCALL(Tcgen531027*, newmodule_565044_839829468)(Tsym294834* module0) { Tcgen531027* result0; result0 = (Tcgen531027*)0; { Tcgen531027* LOC3; NimStringDesc* LOC6; LOC3 = (Tcgen531027*)0; LOC3 = getcgenmodule_534226_839829468(module0); if (!!((LOC3 == NIM_NIL))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_198185_1689653243(T839829468_9); internalerror_198113_155036129(LOC6); } LA4: ; result0 = rawnewmodule_565038_839829468(module0); { if (!((gmodules_531170_3723162438 ? gmodules_531170_3723162438->Sup.len : 0) <= (*module0).position)) goto LA9; gmodules_531170_3723162438 = (TY531153*) setLengthSeq(&(gmodules_531170_3723162438)->Sup, sizeof(Tcgen531027*), ((NI) ((NI)((*module0).position + ((NI) 1))))); } LA9: ; asgnRef((void**) (&gmodules_531170_3723162438->data[(*module0).position]), result0); { if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 2))&63U)))!=0)) goto LA13; { NimStringDesc* LOC19; NimStringDesc* LOC20; if (!(((*module0).flags &(1U<<((NU)(((Tsymflag294184) 25))&31U)))!=0)) goto LA17; LOC19 = (NimStringDesc*)0; LOC20 = (NimStringDesc*)0; LOC20 = tofilename_194257_155036129(((NI32) ((*module0).position))); LOC19 = rawNewString(LOC20->Sup.len + 28); appendString(LOC19, ((NimStringDesc*) &T839829468_13)); appendString(LOC19, LOC20); internalerror_198113_155036129(LOC19); } LA17: ; } LA13: ; return result0; } N_NIMCALL(Tpasscontext343002*, myopen_565112_839829468)(Tsym294834* module0) { Tpasscontext343002* result0; Tcgen531027* LOC1; result0 = (Tpasscontext343002*)0; LOC1 = (Tcgen531027*)0; LOC1 = newmodule_565044_839829468(module0); result0 = &LOC1->Sup; { NIM_BOOL LOC4; NimStringDesc* f0; NimStringDesc* LOC13; NimStringDesc* LOC14; LOC4 = (NIM_BOOL)0; LOC4 = ((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 27))&63U)))!=0); if (!(LOC4)) goto LA5; LOC4 = (generatedheader_534201_839829468 == NIM_NIL); LA5: ; if (!LOC4) goto LA6; { if (!(((NI) 0) < (headerfile_171138_2607990831 ? headerfile_171138_2607990831->Sup.len : 0))) goto LA10; f0 = headerfile_171138_2607990831; } goto LA8; LA10: ; { f0 = gprojectfull_171211_2607990831; } LA8: ; LOC13 = (NimStringDesc*)0; LOC13 = completecfilepath_275854_2528170400(f0, NIM_TRUE); LOC14 = (NimStringDesc*)0; LOC14 = noschangeFileExt(LOC13, ((NimStringDesc*) &T839829468_14)); asgnRef((void**) (&generatedheader_534201_839829468), rawnewmodule_564663_839829468(module0, LOC14)); (*generatedheader_534201_839829468).flags |= ((NU8)1)<<((((Codegenflag531025) 3))%(sizeof(NU8)*8)); } LA6: ; return result0; } N_NIMCALL(NimStringDesc*, getcfile_565201_839829468)(Tcgen531027* m0) { NimStringDesc* result0; NimStringDesc* ext0; NimStringDesc* LOC13; NimStringDesc* LOC14; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; ext0 = copyString(((NimStringDesc*) &T839829468_15)); } goto LA1; LA5: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (gcmd_171132_2607990831 == ((Tcommands171076) 3)); if (LOC8) goto LA9; LOC8 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 28))&31U)))!=0); LA9: ; if (!LOC8) goto LA10; ext0 = copyString(((NimStringDesc*) &T839829468_16)); } goto LA1; LA10: ; { ext0 = copyString(((NimStringDesc*) &T839829468_17)); } LA1: ; LOC13 = (NimStringDesc*)0; LOC13 = withpackagename_172073_2607990831((*m0).cfilename); LOC14 = (NimStringDesc*)0; LOC14 = completecfilepath_275854_2528170400(LOC13, NIM_TRUE); result0 = noschangeFileExt(LOC14, ext0); return result0; } N_NIMCALL(Tpasscontext343002*, myopencached_565246_839829468)(Tsym294834* module0, Trodreader334021* rd0) { Tpasscontext343002* result0; Tcgen531027* m0; NimStringDesc* LOC1; result0 = (Tpasscontext343002*)0; m0 = newmodule_565044_839829468(module0); LOC1 = (NimStringDesc*)0; LOC1 = getcfile_565201_839829468(m0); readmergeinfo_532613_2760143328(LOC1, m0); result0 = &m0->Sup; return result0; } static N_INLINE(NIM_BOOL, skipcodegen_343085_2355241294)(Tnode294802* n0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((NI) 0) < gerrorcounter_194069_155036129); return result0; } N_NIMCALL(void, fillloc_534282_839829468)(Tloc294816* a0, Tlockind294808 k0, Ttype294840* typ0, Ropeobj180006* r0, Tstorageloc294812 s0) { { if (!((*a0).k == ((Tlockind294808) 0))) goto LA3; (*a0).k = k0; unsureAsgnRef((void**) (&(*a0).t), typ0); (*a0).s = s0; { if (!((*a0).r == NIM_NIL)) goto LA7; unsureAsgnRef((void**) (&(*a0).r), r0); } LA7: ; } LA3: ; } N_NIMCALL(NIM_BOOL, iskeyword_534960_839829468)(Tident201010* w0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; switch ((*w0).Sup.id) { case ((NI) 200) ... ((NI) 262): case ((NI) 4) ... ((NI) 70): case ((NI) 138): { result0 = NIM_TRUE; goto BeforeRet; } break; default: { result0 = NIM_FALSE; goto BeforeRet; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, manglename_535205_839829468)(Tsym294834* s0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = (*s0).loc.r; { NIM_BOOL keeporigname0; NIM_BOOL LOC5; NIM_BOOL LOC6; NIM_BOOL LOC9; NimStringDesc* LOC10; if (!(result0 == NIM_NIL)) goto LA3; LOC5 = (NIM_BOOL)0; LOC6 = (NIM_BOOL)0; LOC6 = ((2824 &(1U<<((NU)((*s0).kind)&31U)))!=0); if (!(LOC6)) goto LA7; LOC6 = ((IL64(2149580812) & (*s0).flags) == 0); LA7: ; LOC5 = LOC6; if (!(LOC5)) goto LA8; LOC9 = (NIM_BOOL)0; LOC9 = iskeyword_534960_839829468((*s0).name); LOC5 = !(LOC9); LA8: ; keeporigname0 = LOC5; LOC10 = (NimStringDesc*)0; LOC10 = mangle_530847_2036603609((*(*s0).name).s); result0 = rope_180277_2381377266(LOC10); { if (!keeporigname0) goto LA13; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_18)); } goto LA11; LA13: ; { TY535289 LOC16; Ropeobj180006* LOC17; Ropeobj180006* LOC18; TY535289 LOC19; Ropeobj180006* LOC20; NU32 LOC21; Ropeobj180006* LOC22; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj180006*)0; LOC17 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_12), LOC16, 0); add_180482_2381377266(&result0, LOC17); LOC18 = (Ropeobj180006*)0; LOC18 = rope_180401_2381377266(((NI64) ((*s0).Sup.id))); add_180482_2381377266(&result0, LOC18); memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ropeobj180006*)0; LOC20 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_12), LOC19, 0); add_180482_2381377266(&result0, LOC20); LOC21 = (NU32)0; LOC21 = hashowner_534977_839829468(s0); LOC22 = (Ropeobj180006*)0; LOC22 = rope_180401_2381377266(((NI64) (LOC21))); add_180482_2381377266(&result0, LOC22); } LA11: ; asgnRefNoCycle((void**) (&(*s0).loc.r), result0); } LA3: ; return result0; } N_NIMCALL(void, fillprocloc_541201_839829468)(Tsym294834* sym0) { { Ropeobj180006* LOC5; if (!((*sym0).loc.k == ((Tlockind294808) 0))) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = manglename_535205_839829468(sym0); fillloc_534282_839829468((&(*sym0).loc), ((Tlockind294808) 7), (*sym0).typ, LOC5, ((Tstorageloc294812) 2)); } LA3: ; } N_NIMCALL(void, useheader_534369_839829468)(Tcgen531027* m0, Tsym294834* sym0) { { NimStringDesc* LOC5; NIM_BOOL LOC6; if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 6))&15U)))!=0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = getstr_299230_850551059((*(*sym0).annex).path); LOC6 = (NIM_BOOL)0; LOC6 = includestr_148249_3771138726((&(*m0).headerfiles), LOC5); } LA3: ; } static N_INLINE(void, appendChar)(NimStringDesc* dest0, NIM_CHAR c0) { (*dest0).data[((*dest0).Sup.len)- 0] = c0; (*dest0).data[((NI)((*dest0).Sup.len + ((NI) 1)))- 0] = 0; (*dest0).Sup.len += ((NI) 1); } N_NIMCALL(NIM_BOOL, isactivated_563431_839829468)(Tsym294834* prc0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = !(((*prc0).typ == NIM_NIL)); return result0; } N_NIMCALL(void, addforwardedproc_534203_839829468)(Tcgen531027* m0, Tsym294834* prc0) { (*m0).forwardedprocs = (Tsymseq294804*) incrSeqV2(&((*m0).forwardedprocs)->Sup, sizeof(Tsym294834*)); asgnRefNoCycle((void**) (&(*m0).forwardedprocs->data[(*m0).forwardedprocs->Sup.len]), prc0); ++(*m0).forwardedprocs->Sup.len; gforwardedprocscounter_531171_3723162438 += ((NI) 1); } N_NIMCALL(void, genclinedir_534725_839829468)(Ropeobj180006** r0, NimStringDesc* filename0, NI line0) { { TY534811 LOC5; NimStringDesc* LOC6; if (!((goptions_171128_2607990831 &(1U<<((NU)(((Toption171009) 10))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NimStringDesc*)0; LOC6 = makesinglelinecstring_530835_2036603609(filename0); LOC5[0] = rope_180277_2381377266(LOC6); LOC5[1] = rope_180401_2381377266(((NI64) (line0))); addf_181205_2381377266(r0, ((NimStringDesc*) &T839829468_21), LOC5, 2); } LA3: ; } static N_INLINE(NI, tolinenumber_194415_155036129)(Tlineinfo193336 info0) { NI result0; result0 = (NI)0; result0 = ((NI) (info0.line)); return result0; } N_NIMCALL(NI, safelinenm_534721_839829468)(Tlineinfo193336 info0) { NI result0; result0 = (NI)0; result0 = tolinenumber_194415_155036129(info0); { if (!(result0 < ((NI) 0))) goto LA3; result0 = ((NI) 0); } LA3: ; return result0; } N_NIMCALL(void, genclinedir_534813_839829468)(Ropeobj180006** r0, Tlineinfo193336 info0) { NimStringDesc* LOC1; NI LOC2; LOC1 = (NimStringDesc*)0; LOC1 = tofullpath_194261_155036129(info0.fileindex); LOC2 = (NI)0; LOC2 = safelinenm_534721_839829468(info0); genclinedir_534725_839829468(r0, LOC1, LOC2); } N_NIMCALL(Tctypekind531007, mapsettype_535389_839829468)(Ttype294840* typ0) { Tctypekind531007 result0; NI64 LOC1; result0 = (Tctypekind531007)0; LOC1 = (NI64)0; LOC1 = getsize_322135_3876443242(typ0); switch (((NI) (LOC1))) { case ((NI) 1): { result0 = ((Tctypekind531007) 4); } break; case ((NI) 2): { result0 = ((Tctypekind531007) 5); } break; case ((NI) 4): { result0 = ((Tctypekind531007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind531007) 7); } break; default: { result0 = ((Tctypekind531007) 17); } break; } return result0; } N_NIMCALL(Tctypekind531007, maptype_535394_839829468)(Ttype294840* typ0) { Tctypekind531007 result0; result0 = (Tctypekind531007)0; switch ((*typ0).kind) { case ((Ttypekind294244) 0): case ((Ttypekind294244) 7): { result0 = ((Tctypekind531007) 0); } break; case ((Ttypekind294244) 1): { result0 = ((Tctypekind531007) 2); } break; case ((Ttypekind294244) 2): { result0 = ((Tctypekind531007) 1); } break; case ((Ttypekind294244) 19): { result0 = mapsettype_535389_839829468(typ0); } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 4): case ((Ttypekind294244) 16): case ((Ttypekind294244) 48): { result0 = ((Tctypekind531007) 17); } break; case ((Ttypekind294244) 17): case ((Ttypekind294244) 18): { result0 = ((Tctypekind531007) 19); } break; case ((Ttypekind294244) 10): case ((Ttypekind294244) 11): case ((Ttypekind294244) 12): case ((Ttypekind294244) 13): case ((Ttypekind294244) 15): case ((Ttypekind294244) 46): case ((Ttypekind294244) 47): case ((Ttypekind294244) 49): case ((Ttypekind294244) 8): { Ttype294840* LOC8; LOC8 = (Ttype294840*)0; LOC8 = lastson_297377_850551059(typ0); result0 = maptype_535394_839829468(LOC8); } break; case ((Ttypekind294244) 14): { { NI64 LOC12; LOC12 = (NI64)0; LOC12 = firstord_322001_3876443242(typ0); if (!(LOC12 < IL64(0))) goto LA13; result0 = ((Tctypekind531007) 6); } goto LA10; LA13: ; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = getsize_322135_3876443242(typ0); switch (((NI) (LOC16))) { case ((NI) 1): { result0 = ((Tctypekind531007) 13); } break; case ((NI) 2): { result0 = ((Tctypekind531007) 14); } break; case ((NI) 4): { result0 = ((Tctypekind531007) 6); } break; case ((NI) 8): { result0 = ((Tctypekind531007) 7); } break; default: { internalerror_198113_155036129(((NimStringDesc*) &T839829468_25)); } break; } } LA10: ; } break; case ((Ttypekind294244) 20): { result0 = maptype_535394_839829468((*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind294244) 21): case ((Ttypekind294244) 23): case ((Ttypekind294244) 22): { Ttype294840* base0; Ttype294840* LOC24; LOC24 = (Ttype294840*)0; LOC24 = lastson_297377_850551059(typ0); base0 = skiptypes_298099_850551059(LOC24, IL64(211106232576256)); switch ((*base0).kind) { case ((Ttypekind294244) 27): case ((Ttypekind294244) 4): case ((Ttypekind294244) 16): case ((Ttypekind294244) 48): { result0 = ((Tctypekind531007) 18); } break; default: { result0 = ((Tctypekind531007) 20); } break; } } break; case ((Ttypekind294244) 26): { result0 = ((Tctypekind531007) 20); } break; case ((Ttypekind294244) 24): { result0 = ((Tctypekind531007) 22); } break; case ((Ttypekind294244) 25): { { if (!!(((*typ0).callconv == ((Tcallingconvention294002) 8)))) goto LA32; result0 = ((Tctypekind531007) 23); } goto LA30; LA32: ; { result0 = ((Tctypekind531007) 19); } LA30: ; } break; case ((Ttypekind294244) 28): { result0 = ((Tctypekind531007) 21); } break; case ((Ttypekind294244) 29): { result0 = ((Tctypekind531007) 24); } break; case ((Ttypekind294244) 31) ... ((Ttypekind294244) 44): { result0 = ((Tctypekind531007) ((NI)(((NI) ((NI)(((NI) ((*typ0).kind)) - ((NI) 31)))) + ((NI) 3)))); } break; case ((Ttypekind294244) 59): { { Ttype294840* LOC43; if (!!(((*typ0).n == NIM_NIL))) goto LA41; LOC43 = (Ttype294840*)0; LOC43 = lastson_297377_850551059(typ0); result0 = maptype_535394_839829468(LOC43); } goto LA39; LA41: ; { internalerror_198113_155036129(((NimStringDesc*) &T839829468_25)); } LA39: ; } break; default: { internalerror_198113_155036129(((NimStringDesc*) &T839829468_25)); } break; } return result0; } N_NIMCALL(NIM_BOOL, isimportedcpptype_535478_839829468)(Ttype294840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, needscomplexassignment_535511_839829468)(Ttype294840* typ0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = containsgarbagecollectedref_322117_3876443242(typ0); return result0; } static N_INLINE(NIM_BOOL, isobjlackingtypefield_535515_839829468)(Ttype294840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; NIM_BOOL LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*typ0).kind == ((Ttypekind294244) 17)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 2))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = ((*typ0).sons->data[((NI) 0)] == NIM_NIL); LA5: ; LOC3 = LOC4; if (LOC3) goto LA6; LOC3 = ispureobject_322138_3876443242(typ0); LA6: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NIM_BOOL, isinvalidreturntype_535550_839829468)(Ttype294840* rettype0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!(rettype0 == NIM_NIL)) goto LA3; result0 = NIM_TRUE; } goto LA1; LA3: ; { Tctypekind531007 LOC6; LOC6 = (Tctypekind531007)0; LOC6 = maptype_535394_839829468(rettype0); switch (LOC6) { case ((Tctypekind531007) 17): { Ttype294840* LOC8; LOC8 = (Ttype294840*)0; LOC8 = skiptypes_298099_850551059(rettype0, IL64(211106232576256)); result0 = !(((14680064 &((NU64)1<<((NU)((*LOC8).kind)&63U)))!=0)); } break; case ((Tctypekind531007) 19): { Ttype294840* t0; NIM_BOOL LOC16; NIM_BOOL LOC18; NIM_BOOL LOC20; t0 = skiptypes_298099_850551059(rettype0, IL64(211106232576256)); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = isimportedcpptype_535478_839829468(rettype0); if (LOC12) goto LA13; LOC12 = isimportedcpptype_535478_839829468(t0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; goto BeforeRet; } LA14: ; LOC16 = (NIM_BOOL)0; LOC16 = needscomplexassignment_535511_839829468(t0); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = ((*t0).kind == ((Ttypekind294244) 17)); if (!(LOC18)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = isobjlackingtypefield_535515_839829468(t0); LOC18 = !(LOC20); LA19: ; LOC16 = LOC18; LA17: ; result0 = LOC16; } break; default: { result0 = NIM_FALSE; } break; } } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, typename_535292_839829468)(Ttype294840* typ0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NimStringDesc* LOC5; if (!!(((*typ0).sym == NIM_NIL))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_530847_2036603609((*(*(*typ0).sym).name).s); result0 = rope_180277_2381377266(LOC5); } goto LA1; LA3: ; { TY535289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_28), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, gettypename_535313_839829468)(Ttype294840* typ0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*typ0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*typ0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*(*typ0).sym).loc.r; } goto LA1; LA5: ; { { Ropeobj180006* LOC12; Ropeobj180006* LOC13; if (!((*typ0).loc.r == NIM_NIL)) goto LA10; LOC12 = (Ropeobj180006*)0; LOC12 = typename_535292_839829468(typ0); LOC13 = (Ropeobj180006*)0; LOC13 = rope_180401_2381377266(((NI64) ((*typ0).Sup.id))); asgnRefNoCycle((void**) (&(*typ0).loc.r), HEX26_180418_2381377266(LOC12, LOC13)); } LA10: ; result0 = (*typ0).loc.r; } LA1: ; { NimStringDesc* LOC18; if (!(result0 == NIM_NIL)) goto LA16; LOC18 = (NimStringDesc*)0; LOC18 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI294244))->Sup.len + 13); appendString(LOC18, ((NimStringDesc*) &T839829468_29)); appendString(LOC18, reprEnum((NI)(*typ0).kind, (&NTI294244))); internalerror_198113_155036129(LOC18); } LA16: ; return result0; } N_NIMCALL(Ropeobj180006*, typenameorliteral_535898_839829468)(Ttype294840* t0, NimStringDesc* literal0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = !(((*t0).sym == NIM_NIL)); if (!(LOC4)) goto LA5; LOC4 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA6; LOC3 = ((*(*t0).sym).magic == ((Tmagic294524) 0)); LA6: ; if (!LOC3) goto LA7; result0 = gettypename_535313_839829468(t0); } goto LA1; LA7: ; { result0 = rope_180277_2381377266(literal0); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, getsimpletypedesc_535936_839829468)(Tcgen531027* m0, Ttype294840* typ0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; switch ((*typ0).kind) { case ((Ttypekind294244) 26): { result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_30)); } break; case ((Ttypekind294244) 28): { Ropeobj180006* LOC3; LOC3 = (Ropeobj180006*)0; LOC3 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_31)); result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_32)); } break; case ((Ttypekind294244) 29): { result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_33)); } break; case ((Ttypekind294244) 1): { result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_34)); } break; case ((Ttypekind294244) 2): { result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_35)); } break; case ((Ttypekind294244) 5): { result0 = typenameorliteral_535898_839829468(typ0, ((NimStringDesc*) &T839829468_18)); } break; case ((Ttypekind294244) 31) ... ((Ttypekind294244) 44): { result0 = typenameorliteral_535898_839829468(typ0, Numericaltypetostr_535941_839829468[((*typ0).kind)- 31]); } break; case ((Ttypekind294244) 13): case ((Ttypekind294244) 20): case ((Ttypekind294244) 15): { result0 = getsimpletypedesc_535936_839829468(m0, (*typ0).sons->data[((NI) 0)]); } break; case ((Ttypekind294244) 59): { { Ttype294840* LOC15; if (!!(((*typ0).n == NIM_NIL))) goto LA13; LOC15 = (Ttype294840*)0; LOC15 = lastson_297377_850551059(typ0); result0 = getsimpletypedesc_535936_839829468(m0, LOC15); } goto LA11; LA13: ; { internalerror_198113_155036129(((NimStringDesc*) &T839829468_50)); } LA11: ; } break; case ((Ttypekind294244) 11): { Ttype294840* LOC18; LOC18 = (Ttype294840*)0; LOC18 = lastson_297377_850551059(typ0); result0 = getsimpletypedesc_535936_839829468(m0, LOC18); } break; default: { result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj180006*, cachegettype_535593_839829468)(Tidtable294850 tab0, Ttype294840* key0) { Ropeobj180006* result0; Tidobj201004* LOC1; TNimObject* LOC2; result0 = (Ropeobj180006*)0; LOC1 = (Tidobj201004*)0; LOC1 = &key0->Sup; LOC2 = (TNimObject*)0; LOC2 = idtableget_301086_2984716966(tab0, LOC1); result0 = ((Ropeobj180006*) (LOC2)); return result0; } N_NIMCALL(Ropeobj180006*, gettypepre_535972_839829468)(Tcgen531027* m0, Ttype294840* typ0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!(typ0 == NIM_NIL)) goto LA3; result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_26)); } goto LA1; LA3: ; { result0 = getsimpletypedesc_535936_839829468(m0, typ0); { if (!(result0 == NIM_NIL)) goto LA8; result0 = cachegettype_535593_839829468((*m0).typecache, typ0); } LA8: ; } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, isimportedtype_535451_839829468)(Ttype294840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = !(((*t0).sym == NIM_NIL)); if (!(LOC1)) goto LA2; LOC1 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(NimStringDesc*, getforwardstructformat_536015_839829468)(Tcgen531027* m0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; result0 = copyString(((NimStringDesc*) &T839829468_54)); } goto LA1; LA5: ; { result0 = copyString(((NimStringDesc*) &T839829468_55)); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, structorunion_536001_839829468)(Ttype294840* t0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag294431) 1))&31U)))!=0)) goto LA3; result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_56)); } goto LA1; LA3: ; { result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_57)); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, gettypeforward_536039_839829468)(Tcgen531027* m0, Ttype294840* typ0) { Ropeobj180006* result0; { result0 = (Ropeobj180006*)0; result0 = cachegettype_535593_839829468((*m0).forwtypecache, typ0); { if (!!((result0 == NIM_NIL))) goto LA3; goto BeforeRet; } LA3: ; result0 = gettypepre_535972_839829468(m0, typ0); { if (!!((result0 == NIM_NIL))) goto LA7; goto BeforeRet; } LA7: ; switch ((*typ0).kind) { case ((Ttypekind294244) 24): case ((Ttypekind294244) 18): case ((Ttypekind294244) 17): { Tidobj201004* LOC17; TNimObject* LOC18; result0 = gettypename_535313_839829468(typ0); { NIM_BOOL LOC12; NimStringDesc* LOC15; TY534811 LOC16; LOC12 = (NIM_BOOL)0; LOC12 = isimportedtype_535451_839829468(typ0); if (!!(LOC12)) goto LA13; LOC15 = (NimStringDesc*)0; LOC15 = getforwardstructformat_536015_839829468(m0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = structorunion_536001_839829468(typ0); LOC16[1] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 2))- 0], LOC15, LOC16, 2); } LA13: ; LOC17 = (Tidobj201004*)0; LOC17 = &typ0->Sup; LOC18 = (TNimObject*)0; LOC18 = &result0->Sup; idtableput_301094_2984716966((&(*m0).forwtypecache), LOC17, LOC18); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI294244))->Sup.len + 16); appendString(LOC20, ((NimStringDesc*) &T839829468_58)); appendString(LOC20, reprEnum((NI)(*typ0).kind, (&NTI294244))); appendChar(LOC20, 41); internalerror_198113_155036129(LOC20); } break; } }BeforeRet: ; return result0; } N_NIMCALL(void, pushtype_535958_839829468)(Tcgen531027* m0, Ttype294840* typ0) { (*m0).typestack = (Ttypeseq294836*) incrSeqV2(&((*m0).typestack)->Sup, sizeof(Ttype294840*)); asgnRefNoCycle((void**) (&(*m0).typestack->data[(*m0).typestack->Sup.len]), typ0); ++(*m0).typestack->Sup.len; } N_NIMCALL(Ropeobj180006*, gettypedescweak_536079_839829468)(Tcgen531027* m0, Ttype294840* t0, Intset270030* check0) { Ropeobj180006* result0; Ttype294840* etb0; result0 = (Ropeobj180006*)0; etb0 = skiptypes_298099_850551059(t0, IL64(211106232576256)); switch ((*etb0).kind) { case ((Ttypekind294244) 17): case ((Ttypekind294244) 18): { { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = isimportedcpptype_535478_839829468(etb0); if (!(LOC4)) goto LA5; LOC4 = ((*t0).kind == ((Ttypekind294244) 11)); LA5: ; if (!LOC4) goto LA6; result0 = gettypedescaux_535505_839829468(m0, t0, check0); } goto LA2; LA6: ; { Ttype294840* x0; x0 = getuniquetype_530640_2036603609(etb0); result0 = gettypeforward_536039_839829468(m0, x0); pushtype_535958_839829468(m0, x0); } LA2: ; } break; case ((Ttypekind294244) 24): { Ttype294840* x0; Ropeobj180006* LOC10; x0 = getuniquetype_530640_2036603609(etb0); LOC10 = (Ropeobj180006*)0; LOC10 = gettypeforward_536039_839829468(m0, x0); result0 = HEX26_180447_2381377266(LOC10, ((NimStringDesc*) &T839829468_53)); pushtype_535958_839829468(m0, x0); } break; default: { result0 = gettypedescaux_535505_839829468(m0, t0, check0); } break; } return result0; } static N_INLINE(NI, len_295081_850551059)(Tnode294802* n0) { NI result0; result0 = (NI)0; { if (!(*n0).kindU.S6.sons == 0) goto LA3; result0 = ((NI) 0); } goto LA1; LA3: ; { result0 = ((*n0).kindU.S6.sons ? (*n0).kindU.S6.sons->Sup.len : 0); } LA1: ; return result0; } N_NIMCALL(void, appcg_534632_839829468)(Tcgen531027* m0, Ropeobj180006** c0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006* LOC1; LOC1 = (Ropeobj180006*)0; LOC1 = ropecg_534407_839829468(m0, frmt0, args0, args0Len0); add_180482_2381377266(c0, LOC1); } N_NIMCALL(NIM_BOOL, scancppgenericslot_536827_839829468)(NimStringDesc* pat0, NI* cursor0, NI* outidx0, NI* outstars0) { NIM_BOOL result0; NI begin0; { result0 = (NIM_BOOL)0; (*cursor0) += ((NI) 1); begin0 = (*cursor0); { while (1) { if (!((NU8)(pat0->data[(*cursor0)]) == (NU8)(42))) goto LA2; (*cursor0) += ((NI) 1); } LA2: ; } { if (!(((NU8)(pat0->data[(*cursor0)])) >= ((NU8)(48)) && ((NU8)(pat0->data[(*cursor0)])) <= ((NU8)(57)))) goto LA5; (*outidx0) = ((NI) ((NI)(((NI) (((NU8)(pat0->data[(*cursor0)])))) - ((NI) 48)))); (*outstars0) = (NI)((*cursor0) - begin0); (*cursor0) += ((NI) 1); result0 = NIM_TRUE; goto BeforeRet; } goto LA3; LA5: ; { result0 = NIM_FALSE; goto BeforeRet; } LA3: ; }BeforeRet: ; return result0; } N_NIMCALL(Ttype294840*, resolvestarsincpptype_536891_839829468)(Ttype294840* typ0, NI idx0, NI stars0) { Ttype294840* result0; result0 = (Ttype294840*)0; { NI LOC3; LOC3 = (NI)0; LOC3 = len_297339_850551059(typ0); if (!(LOC3 <= idx0)) goto LA4; internalerror_198113_155036129(((NimStringDesc*) &T839829468_81)); } LA4: ; result0 = (*typ0).sons->data[idx0]; { NI i_536906_839829468; NI res_536931_839829468; i_536906_839829468 = (NI)0; res_536931_839829468 = ((NI) 1); { while (1) { if (!(res_536931_839829468 <= stars0)) goto LA8; i_536906_839829468 = res_536931_839829468; { NIM_BOOL LOC11; NI LOC13; LOC11 = (NIM_BOOL)0; LOC11 = !((result0 == NIM_NIL)); if (!(LOC11)) goto LA12; LOC13 = (NI)0; LOC13 = len_297339_850551059(result0); LOC11 = (((NI) 0) < LOC13); LA12: ; if (!LOC11) goto LA14; { if (!((*result0).kind == ((Ttypekind294244) 11))) goto LA18; result0 = (*result0).sons->data[((NI) 1)]; } goto LA16; LA18: ; { result0 = elemtype_322394_3876443242(result0); } LA16: ; } LA14: ; res_536931_839829468 += ((NI) 1); } LA8: ; } } return result0; } N_NIMCALL(NimStringDesc*, manglefield_534973_839829468)(Tident201010* name0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = mangle_530847_2036603609((*name0).s); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = iskeyword_534960_839829468(name0); if (!LOC3) goto LA4; result0->data[((NI) 0)] = nsuToUpperAsciiChar(result0->data[((NI) 0)]); } LA4: ; return result0; } N_NIMCALL(Ropeobj180006*, manglerecfieldname_536361_839829468)(Tsym294834* field0, Ttype294840* rectype0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*rectype0).sym == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = !(((96 & (*(*rectype0).sym).flags) == 0)); LA4: ; if (!LOC3) goto LA5; result0 = (*field0).loc.r; } goto LA1; LA5: ; { NimStringDesc* LOC8; LOC8 = (NimStringDesc*)0; LOC8 = manglefield_534973_839829468((*field0).name); result0 = rope_180277_2381377266(LOC8); } LA1: ; { if (!(result0 == NIM_NIL)) goto LA11; internalerror_198100_155036129((*field0).info, ((NimStringDesc*) &T839829468_96)); } LA11: ; return result0; } N_NIMCALL(Ropeobj180006*, genrecordfieldsaux_536421_839829468)(Tcgen531027* m0, Tnode294802* n0, Ropeobj180006* accessexpr0, Ttype294840* rectype0, Intset270030* check0) { Ropeobj180006* result0; Ropeobj180006* ae0; Ropeobj180006* uname0; Ropeobj180006* sname0; Ropeobj180006* a0; Tnode294802* k0; Tsym294834* field0; { result0 = (Ropeobj180006*)0; ae0 = (Ropeobj180006*)0; uname0 = (Ropeobj180006*)0; sname0 = (Ropeobj180006*)0; a0 = (Ropeobj180006*)0; k0 = (Tnode294802*)0; field0 = (Tsym294834*)0; result0 = NIM_NIL; switch ((*n0).kind) { case ((Tnodekind294020) 138): { { NI i_536447_839829468; NI HEX3Atmp_536620_839829468; NI LOC3; NI res_536623_839829468; i_536447_839829468 = (NI)0; HEX3Atmp_536620_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_297351_850551059(n0); HEX3Atmp_536620_839829468 = (NI)(LOC3 - ((NI) 1)); res_536623_839829468 = ((NI) 0); { while (1) { Ropeobj180006* LOC6; if (!(res_536623_839829468 <= HEX3Atmp_536620_839829468)) goto LA5; i_536447_839829468 = res_536623_839829468; LOC6 = (Ropeobj180006*)0; LOC6 = genrecordfieldsaux_536421_839829468(m0, (*n0).kindU.S6.sons->data[i_536447_839829468], accessexpr0, rectype0, check0); add_180482_2381377266(&result0, LOC6); res_536623_839829468 += ((NI) 1); } LA5: ; } } } break; case ((Tnodekind294020) 139): { Ropeobj180006* LOC12; NimStringDesc* LOC13; NimStringDesc* LOC14; Ropeobj180006* unionbody0; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)))) goto LA10; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_89)); } LA10: ; LOC12 = (Ropeobj180006*)0; LOC12 = genrecordfieldsaux_536421_839829468(m0, (*n0).kindU.S6.sons->data[((NI) 0)], accessexpr0, rectype0, check0); add_180482_2381377266(&result0, LOC12); LOC13 = (NimStringDesc*)0; LOC14 = (NimStringDesc*)0; LOC14 = mangle_530847_2036603609((*(*(*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); LOC13 = rawNewString(LOC14->Sup.len + 1); appendString(LOC13, LOC14); appendChar(LOC13, 85); uname0 = rope_180277_2381377266(LOC13); { TY534811 LOC19; if (!!((accessexpr0 == NIM_NIL))) goto LA17; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = accessexpr0; LOC19[1] = uname0; ae0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_90), LOC19, 2); } goto LA15; LA17: ; { ae0 = uname0; } LA15: ; unionbody0 = NIM_NIL; { NI i_536491_839829468; NI HEX3Atmp_536629_839829468; NI LOC22; NI res_536632_839829468; i_536491_839829468 = (NI)0; HEX3Atmp_536629_839829468 = (NI)0; LOC22 = (NI)0; LOC22 = sonslen_297351_850551059(n0); HEX3Atmp_536629_839829468 = (NI)(LOC22 - ((NI) 1)); res_536632_839829468 = ((NI) 1); { while (1) { if (!(res_536632_839829468 <= HEX3Atmp_536629_839829468)) goto LA24; i_536491_839829468 = res_536632_839829468; switch ((*(*n0).kindU.S6.sons->data[i_536491_839829468]).kind) { case ((Tnodekind294020) 85): case ((Tnodekind294020) 88): { k0 = lastson_297364_850551059((*n0).kindU.S6.sons->data[i_536491_839829468]); { Ropeobj180006* LOC30; TY534811 LOC31; Ropeobj180006* LOC32; if (!!(((*k0).kind == ((Tnodekind294020) 3)))) goto LA28; LOC30 = (Ropeobj180006*)0; LOC30 = rope_180401_2381377266(((NI64) (i_536491_839829468))); sname0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_91), LOC30); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = ae0; LOC31[1] = sname0; LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_90), LOC31, 2); a0 = genrecordfieldsaux_536421_839829468(m0, k0, LOC32, rectype0, check0); { TY180507 LOC37; if (!!((a0 == NIM_NIL))) goto LA35; add_180487_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_92)); add_180482_2381377266(&unionbody0, a0); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = sname0; addf_181205_2381377266(&unionbody0, ((NimStringDesc*) &T839829468_93), LOC37, 1); } LA35: ; } goto LA26; LA28: ; { Ropeobj180006* LOC39; LOC39 = (Ropeobj180006*)0; LOC39 = genrecordfieldsaux_536421_839829468(m0, k0, ae0, rectype0, check0); add_180482_2381377266(&unionbody0, LOC39); } LA26: ; } break; default: { internalerror_198113_155036129(((NimStringDesc*) &T839829468_94)); } break; } res_536632_839829468 += ((NI) 1); } LA24: ; } } { TY534811 LOC45; if (!!((unionbody0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = unionbody0; LOC45[1] = uname0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_95), LOC45, 2); } LA43: ; } break; case ((Tnodekind294020) 3): { field0 = (*n0).kindU.S4.sym; { if (!((*(*field0).typ).kind == ((Ttypekind294244) 62))) goto LA49; goto BeforeRet; } LA49: ; sname0 = manglerecfieldname_536361_839829468(field0, rectype0); { TY534811 LOC55; if (!!((accessexpr0 == NIM_NIL))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = accessexpr0; LOC55[1] = sname0; ae0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_90), LOC55, 2); } goto LA51; LA53: ; { ae0 = sname0; } LA51: ; fillloc_534282_839829468((&(*field0).loc), ((Tlockind294808) 5), (*field0).typ, ae0, ((Tstorageloc294812) 0)); { NIM_BOOL LOC59; Ttype294840* fieldtype0; LOC59 = (NIM_BOOL)0; LOC59 = isimportedcpptype_535478_839829468(rectype0); if (!!(LOC59)) goto LA60; fieldtype0 = skiptypes_298099_850551059((*field0).loc.t, IL64(211106232576256)); { NIM_BOOL LOC64; TY534811 LOC68; Ttype294840* LOC69; LOC64 = (NIM_BOOL)0; LOC64 = ((*fieldtype0).kind == ((Ttypekind294244) 16)); if (!(LOC64)) goto LA65; LOC64 = (((*fieldtype0).flags &(1U<<((NU)(((Ttypeflag294431) 0))&31U)))!=0); LA65: ; if (!LOC64) goto LA66; memset((void*)LOC68, 0, sizeof(LOC68)); LOC69 = (Ttype294840*)0; LOC69 = elemtype_322394_3876443242(fieldtype0); LOC68[0] = gettypedescaux_535505_839829468(m0, LOC69, check0); LOC68[1] = sname0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_97), LOC68, 2); } goto LA62; LA66: ; { TY534811 LOC73; if (!((*fieldtype0).kind == ((Ttypekind294244) 24))) goto LA71; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = gettypedescweak_536079_839829468(m0, (*field0).loc.t, check0); LOC73[1] = sname0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC73, 2); } goto LA62; LA71: ; { TY537238 LOC77; NimStringDesc* LOC78; if (!!(((*field0).kindU.S4.bitsize == ((NI) 0)))) goto LA75; memset((void*)LOC77, 0, sizeof(LOC77)); LOC77[0] = gettypedescaux_535505_839829468(m0, (*field0).loc.t, check0); LOC77[1] = sname0; LOC78 = (NimStringDesc*)0; LOC78 = nimIntToStr((*field0).kindU.S4.bitsize); LOC77[2] = rope_180277_2381377266(LOC78); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_98), LOC77, 3); } goto LA62; LA75: ; { TY534811 LOC80; memset((void*)LOC80, 0, sizeof(LOC80)); LOC80[0] = gettypedescaux_535505_839829468(m0, (*field0).loc.t, check0); LOC80[1] = sname0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_54), LOC80, 2); } LA62: ; } LA60: ; } break; default: { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_99)); } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, getrecordfields_536636_839829468)(Tcgen531027* m0, Ttype294840* typ0, Intset270030* check0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = genrecordfieldsaux_536421_839829468(m0, (*typ0).n, NIM_NIL, typ0, check0); return result0; } N_NIMCALL(Ropeobj180006*, getrecorddesc_536643_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0, Intset270030* check0) { Ropeobj180006* result0; NIM_BOOL hasfield0; Ropeobj180006* attribute0; TY537238 LOC6; Ropeobj180006* desc0; NimStringDesc* LOC46; result0 = (Ropeobj180006*)0; hasfield0 = NIM_FALSE; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 21))&31U)))!=0)) goto LA3; attribute0 = rope_180277_2381377266(Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field19); } goto LA1; LA3: ; { attribute0 = NIM_NIL; } LA1: ; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = structorunion_536001_839829468(typ0); LOC6[1] = name0; LOC6[2] = attribute0; result0 = ropecg_534407_839829468(m0, Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field18, LOC6, 3); { if (!((*typ0).kind == ((Ttypekind294244) 17))) goto LA9; { if (!((*typ0).sons->data[((NI) 0)] == NIM_NIL)) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; TY535289 LOC23; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = !(((*typ0).sym == NIM_NIL)); if (!(LOC18)) goto LA19; LOC18 = (((*(*typ0).sym).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0); LA19: ; LOC17 = LOC18; if (LOC17) goto LA20; LOC17 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 2))&31U)))!=0); LA20: ; if (!LOC17) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); appcg_534632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_85), LOC23, 0); } goto LA15; LA21: ; { TY534811 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = name0; LOC25[1] = attribute0; appcg_534632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_86), LOC25, 2); hasfield0 = NIM_TRUE; } LA15: ; } goto LA11; LA13: ; { NIM_BOOL LOC27; TY180507 LOC31; Ttype294840* LOC32; LOC27 = (NIM_BOOL)0; LOC27 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC27) goto LA28; LOC27 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA28: ; if (!LOC27) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ttype294840*)0; LOC32 = skiptypes_298099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC31[0] = gettypedescaux_535505_839829468(m0, LOC32, check0); appcg_534632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_87), LOC31, 1); hasfield0 = NIM_TRUE; } goto LA11; LA29: ; { TY180507 LOC34; Ttype294840* LOC35; memset((void*)LOC34, 0, sizeof(LOC34)); LOC35 = (Ttype294840*)0; LOC35 = skiptypes_298099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106247215360)); LOC34[0] = gettypedescaux_535505_839829468(m0, LOC35, check0); appcg_534632_839829468(m0, &result0, ((NimStringDesc*) &T839829468_88), LOC34, 1); hasfield0 = NIM_TRUE; } LA11: ; } goto LA7; LA9: ; { TY180507 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = name0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_85), LOC37, 1); } LA7: ; desc0 = getrecordfields_536636_839829468(m0, typ0, check0); { NIM_BOOL LOC40; TY535289 LOC44; LOC40 = (NIM_BOOL)0; LOC40 = (desc0 == NIM_NIL); if (!(LOC40)) goto LA41; LOC40 = !(hasfield0); LA41: ; if (!LOC40) goto LA42; memset((void*)LOC44, 0, sizeof(LOC44)); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_100), LOC44, 0); } goto LA38; LA42: ; { add_180482_2381377266(&result0, desc0); } LA38: ; LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(tnl_178644_4151366050->Sup.len + 2); appendString(LOC46, ((NimStringDesc*) &T839829468_101)); appendString(LOC46, tnl_178644_4151366050); add_180487_2381377266(&result0, LOC46); return result0; } N_NIMCALL(Ropeobj180006*, gettupledesc_536777_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0, Intset270030* check0) { Ropeobj180006* result0; TY534811 LOC1; Ropeobj180006* desc0; NimStringDesc* LOC13; result0 = (Ropeobj180006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = structorunion_536001_839829468(typ0); LOC1[1] = name0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_102), LOC1, 2); desc0 = NIM_NIL; { NI i_536799_839829468; NI HEX3Atmp_536820_839829468; NI LOC3; NI res_536823_839829468; i_536799_839829468 = (NI)0; HEX3Atmp_536820_839829468 = (NI)0; LOC3 = (NI)0; LOC3 = sonslen_297327_850551059(typ0); HEX3Atmp_536820_839829468 = (NI)(LOC3 - ((NI) 1)); res_536823_839829468 = ((NI) 0); { while (1) { TY534811 LOC6; if (!(res_536823_839829468 <= HEX3Atmp_536820_839829468)) goto LA5; i_536799_839829468 = res_536823_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = gettypedescaux_535505_839829468(m0, (*typ0).sons->data[i_536799_839829468], check0); LOC6[1] = rope_180401_2381377266(((NI64) (i_536799_839829468))); addf_181205_2381377266(&desc0, ((NimStringDesc*) &T839829468_103), LOC6, 2); res_536823_839829468 += ((NI) 1); } LA5: ; } } { NimStringDesc* LOC11; if (!(desc0 == NIM_NIL)) goto LA9; LOC11 = (NimStringDesc*)0; LOC11 = rawNewString(tnl_178644_4151366050->Sup.len + 11); appendString(LOC11, ((NimStringDesc*) &T839829468_104)); appendString(LOC11, tnl_178644_4151366050); add_180487_2381377266(&result0, LOC11); } goto LA7; LA9: ; { add_180482_2381377266(&result0, desc0); } LA7: ; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString(tnl_178644_4151366050->Sup.len + 2); appendString(LOC13, ((NimStringDesc*) &T839829468_101)); appendString(LOC13, tnl_178644_4151366050); add_180487_2381377266(&result0, LOC13); return result0; } N_NIMCALL(Ropeobj180006*, gettypedescaux_535505_839829468)(Tcgen531027* m0, Ttype294840* typ0, Intset270030* check0) { Ropeobj180006* result0; Ttype294840* t_536942_839829468; { result0 = (Ropeobj180006*)0; t_536942_839829468 = getuniquetype_530640_2036603609(typ0); { if (!(t_536942_839829468 == NIM_NIL)) goto LA3; internalerror_198113_155036129(((NimStringDesc*) &T839829468_27)); } LA3: ; { if (!!(((*t_536942_839829468).sym == NIM_NIL))) goto LA7; useheader_534369_839829468(m0, (*t_536942_839829468).sym); } LA7: ; result0 = gettypepre_535972_839829468(m0, t_536942_839829468); { if (!!((result0 == NIM_NIL))) goto LA11; goto BeforeRet; } LA11: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_270862_2627731572(check0, (*t_536942_839829468).Sup.id); if (!LOC15) goto LA16; { NIM_BOOL LOC20; NimStringDesc* LOC24; NimStringDesc* LOC25; LOC20 = (NIM_BOOL)0; LOC20 = isimportedcpptype_535478_839829468(typ0); if (LOC20) goto LA21; LOC20 = isimportedcpptype_535478_839829468(t_536942_839829468); LA21: ; if (!!(LOC20)) goto LA22; LOC24 = (NimStringDesc*)0; LOC25 = (NimStringDesc*)0; LOC25 = typetostring_322017_3876443242(typ0, ((Tprefereddesc322011) 0)); LOC24 = rawNewString(LOC25->Sup.len + 28); appendString(LOC24, ((NimStringDesc*) &T839829468_51)); appendString(LOC24, LOC25); internalerror_198113_155036129(LOC24); } LA22: ; } LA16: ; switch ((*t_536942_839829468).kind) { case ((Ttypekind294244) 22): case ((Ttypekind294244) 21): case ((Ttypekind294244) 23): { NimStringDesc* star0; Ttype294840* et0; Ttype294840* LOC38; Ttype294840* etb0; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC33; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*t_536942_839829468).kind == ((Ttypekind294244) 23)); if (!(LOC30)) goto LA31; LOC30 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 18))&31U)))!=0)); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC33) goto LA34; LOC33 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA34: ; LOC29 = LOC33; LA32: ; if (!LOC29) goto LA35; star0 = copyString(((NimStringDesc*) &T839829468_52)); } goto LA27; LA35: ; { star0 = copyString(((NimStringDesc*) &T839829468_53)); } LA27: ; LOC38 = (Ttype294840*)0; LOC38 = skiptypes_298099_850551059(typ0, IL64(211106232576256)); et0 = lastson_297377_850551059(LOC38); etb0 = skiptypes_298099_850551059(et0, IL64(211106232576256)); { if (!((IL64(281475110993936) &((NU64)1<<((NU)((*etb0).kind)&63U)))!=0)) goto LA41; et0 = elemtype_322394_3876443242(etb0); etb0 = skiptypes_298099_850551059(et0, IL64(211106232576256)); star0->data[((NI) 0)] = 42; } LA41: ; switch ((*etb0).kind) { case ((Ttypekind294244) 17): case ((Ttypekind294244) 18): { { NIM_BOOL LOC46; Ropeobj180006* LOC50; LOC46 = (NIM_BOOL)0; LOC46 = isimportedcpptype_535478_839829468(etb0); if (!(LOC46)) goto LA47; LOC46 = ((*et0).kind == ((Ttypekind294244) 11)); LA47: ; if (!LOC46) goto LA48; LOC50 = (Ropeobj180006*)0; LOC50 = gettypedescaux_535505_839829468(m0, et0, check0); result0 = HEX26_180447_2381377266(LOC50, star0); } goto LA44; LA48: ; { Ttype294840* x0; Ropeobj180006* name0; Tidobj201004* LOC52; TNimObject* LOC53; x0 = getuniquetype_530640_2036603609(etb0); name0 = gettypeforward_536039_839829468(m0, x0); result0 = HEX26_180447_2381377266(name0, star0); LOC52 = (Tidobj201004*)0; LOC52 = &t_536942_839829468->Sup; LOC53 = (TNimObject*)0; LOC53 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC52, LOC53); pushtype_535958_839829468(m0, x0); } LA44: ; } break; case ((Ttypekind294244) 24): { Ttype294840* x0; Ropeobj180006* name0; Ropeobj180006* LOC55; Tidobj201004* LOC56; TNimObject* LOC57; x0 = getuniquetype_530640_2036603609(etb0); name0 = gettypeforward_536039_839829468(m0, x0); LOC55 = (Ropeobj180006*)0; LOC55 = HEX26_180447_2381377266(name0, ((NimStringDesc*) &T839829468_53)); result0 = HEX26_180447_2381377266(LOC55, star0); LOC56 = (Tidobj201004*)0; LOC56 = &t_536942_839829468->Sup; LOC57 = (TNimObject*)0; LOC57 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC56, LOC57); pushtype_535958_839829468(m0, x0); } break; default: { Ropeobj180006* LOC59; Tidobj201004* LOC60; TNimObject* LOC61; LOC59 = (Ropeobj180006*)0; LOC59 = gettypedescaux_535505_839829468(m0, et0, check0); result0 = HEX26_180447_2381377266(LOC59, star0); LOC60 = (Tidobj201004*)0; LOC60 = &t_536942_839829468->Sup; LOC61 = (TNimObject*)0; LOC61 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC60, LOC61); } break; } } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { Ropeobj180006* LOC63; Tidobj201004* LOC64; TNimObject* LOC65; LOC63 = (Ropeobj180006*)0; LOC63 = gettypedescweak_536079_839829468(m0, (*t_536942_839829468).sons->data[((NI) 0)], check0); result0 = HEX26_180447_2381377266(LOC63, ((NimStringDesc*) &T839829468_53)); LOC64 = (Tidobj201004*)0; LOC64 = &t_536942_839829468->Sup; LOC65 = (TNimObject*)0; LOC65 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC64, LOC65); } break; case ((Ttypekind294244) 20): case ((Ttypekind294244) 14): { Ttype294840* t0; { if (!((*t_536942_839829468).kind == ((Ttypekind294244) 20))) goto LA69; t0 = lastson_297377_850551059(t_536942_839829468); } goto LA67; LA69: ; { t0 = t_536942_839829468; } LA67: ; result0 = cachegettype_535593_839829468((*m0).typecache, t0); { if (!(result0 == NIM_NIL)) goto LA74; result0 = gettypename_535313_839829468(t0); { NIM_BOOL LOC78; NIM_BOOL LOC80; Tidobj201004* LOC84; TNimObject* LOC85; NI size0; NU32 owner0; LOC78 = (NIM_BOOL)0; LOC78 = isimportedcpptype_535478_839829468(t0); if (LOC78) goto LA79; LOC80 = (NIM_BOOL)0; LOC80 = (((*(*t0).sym).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0); if (!(LOC80)) goto LA81; LOC80 = ((*(*t0).sym).magic == ((Tmagic294524) 0)); LA81: ; LOC78 = LOC80; LA79: ; if (!!(LOC78)) goto LA82; LOC84 = (Tidobj201004*)0; LOC84 = &t0->Sup; LOC85 = (TNimObject*)0; LOC85 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC84, LOC85); size0 = (NI)0; { NI64 LOC88; TY180507 LOC91; LOC88 = (NI64)0; LOC88 = firstord_322001_3876443242(t0); if (!(LOC88 < IL64(0))) goto LA89; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC91, 1); size0 = ((NI) 4); } goto LA86; LA89: ; { NI64 LOC93; LOC93 = (NI64)0; LOC93 = getsize_322135_3876443242(t0); size0 = ((NI) (LOC93)); switch (size0) { case ((NI) 1): { TY180507 LOC95; memset((void*)LOC95, 0, sizeof(LOC95)); LOC95[0] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_60), LOC95, 1); } break; case ((NI) 2): { TY180507 LOC97; memset((void*)LOC97, 0, sizeof(LOC97)); LOC97[0] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_61), LOC97, 1); } break; case ((NI) 4): { TY180507 LOC99; memset((void*)LOC99, 0, sizeof(LOC99)); LOC99[0] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_59), LOC99, 1); } break; case ((NI) 8): { TY180507 LOC101; memset((void*)LOC101, 0, sizeof(LOC101)); LOC101[0] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_62), LOC101, 1); } break; default: { internalerror_198100_155036129((*(*t0).sym).info, ((NimStringDesc*) &T839829468_63)); } break; } } LA86: ; owner0 = hashowner_534977_839829468((*t0).sym); { NIM_BOOL LOC105; TY205017* vals0; Enumdesc205007 LOC114; LOC105 = (NIM_BOOL)0; LOC105 = hasenum_205230_1926258066((&gdebuginfo_205470_1926258066), (*(*(*t0).sym).name).s, ((NI) ((*(*t0).sym).info.line)), owner0); if (!!(LOC105)) goto LA106; vals0 = (TY205017*) newSeq((&NTI205017), 0); { NI i_537144_839829468; NI HEX3Atmp_537649_839829468; NI LOC109; NI res_537652_839829468; i_537144_839829468 = (NI)0; HEX3Atmp_537649_839829468 = (NI)0; LOC109 = (NI)0; LOC109 = len_295081_850551059((*t0).n); HEX3Atmp_537649_839829468 = (NI)(LOC109 - ((NI) 1)); res_537652_839829468 = ((NI) 0); { while (1) { Tsym294834* field0; TY205018 LOC112; NimStringDesc* LOC113; if (!(res_537652_839829468 <= HEX3Atmp_537649_839829468)) goto LA111; i_537144_839829468 = res_537652_839829468; field0 = (*(*(*t0).n).kindU.S6.sons->data[i_537144_839829468]).kindU.S4.sym; memset((void*)(&LOC112), 0, sizeof(LOC112)); LOC112.Field0 = copyString((*(*field0).name).s); LOC112.Field1 = (*field0).position; vals0 = (TY205017*) incrSeqV2(&(vals0)->Sup, sizeof(TY205018)); LOC113 = (NimStringDesc*)0; LOC113 = vals0->data[vals0->Sup.len].Field0; vals0->data[vals0->Sup.len].Field0 = copyStringRC1(LOC112.Field0); if (LOC113) nimGCunrefNoCycle(LOC113); vals0->data[vals0->Sup.len].Field1 = LOC112.Field1; ++vals0->Sup.len; res_537652_839829468 += ((NI) 1); } LA111: ; } } memset((void*)(&LOC114), 0, sizeof(LOC114)); memset((void*)(&LOC114), 0, sizeof(LOC114)); LOC114.size = size0; LOC114.owner = owner0; LOC114.id = (*(*t0).sym).Sup.id; LOC114.name = copyString((*(*(*t0).sym).name).s); genericSeqAssign((&LOC114.values), vals0, (&NTI205017)); registerenum_205419_1926258066((&gdebuginfo_205470_1926258066), (&LOC114)); } LA106: ; } LA82: ; } LA74: ; } break; case ((Ttypekind294244) 25): { Tidobj201004* LOC116; TNimObject* LOC117; Ropeobj180006* rettype0; Ropeobj180006* desc0; result0 = gettypename_535313_839829468(t_536942_839829468); LOC116 = (Tidobj201004*)0; LOC116 = &t_536942_839829468->Sup; LOC117 = (TNimObject*)0; LOC117 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC116, LOC117); rettype0 = (Ropeobj180006*)0; desc0 = (Ropeobj180006*)0; genprocparams_536115_839829468(m0, t_536942_839829468, &rettype0, &desc0, check0, NIM_TRUE, NIM_TRUE); { NIM_BOOL LOC120; LOC120 = (NIM_BOOL)0; LOC120 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC120)) goto LA121; { TY537235 LOC127; if (!!(((*t_536942_839829468).callconv == ((Tcallingconvention294002) 8)))) goto LA125; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rope_180277_2381377266(Callingconvtostr_535587_839829468[((*t_536942_839829468).callconv)- 0]); LOC127[1] = rettype0; LOC127[2] = result0; LOC127[3] = desc0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC127, 4); } goto LA123; LA125: ; { TY537238 LOC129; memset((void*)LOC129, 0, sizeof(LOC129)); LOC129[0] = result0; LOC129[1] = rettype0; LOC129[2] = desc0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC129, 3); } LA123: ; } LA121: ; } break; case ((Ttypekind294244) 24): { Tidobj201004* LOC144; Ropeobj180006* LOC145; TNimObject* LOC146; result0 = cachegettype_535593_839829468((*m0).forwtypecache, t_536942_839829468); { Tidobj201004* LOC142; TNimObject* LOC143; if (!(result0 == NIM_NIL)) goto LA133; result0 = gettypename_535313_839829468(t_536942_839829468); { NIM_BOOL LOC137; NimStringDesc* LOC140; TY534811 LOC141; LOC137 = (NIM_BOOL)0; LOC137 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC137)) goto LA138; LOC140 = (NimStringDesc*)0; LOC140 = getforwardstructformat_536015_839829468(m0); memset((void*)LOC141, 0, sizeof(LOC141)); LOC141[0] = structorunion_536001_839829468(t_536942_839829468); LOC141[1] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 2))- 0], LOC140, LOC141, 2); } LA138: ; LOC142 = (Tidobj201004*)0; LOC142 = &t_536942_839829468->Sup; LOC143 = (TNimObject*)0; LOC143 = &result0->Sup; idtableput_301094_2984716966((&(*m0).forwtypecache), LOC142, LOC143); } LA133: ; LOC144 = (Tidobj201004*)0; LOC144 = &t_536942_839829468->Sup; LOC145 = (Ropeobj180006*)0; LOC145 = HEX26_180447_2381377266(result0, ((NimStringDesc*) &T839829468_53)); LOC146 = (TNimObject*)0; LOC146 = &LOC145->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC144, LOC146); { NIM_BOOL LOC149; LOC149 = (NIM_BOOL)0; LOC149 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC149)) goto LA150; { Ttype294840* LOC154; NimStringDesc* LOC157; NimStringDesc* LOC158; TY534811 LOC166; LOC154 = (Ttype294840*)0; LOC154 = skiptypes_298099_850551059((*t_536942_839829468).sons->data[((NI) 0)], IL64(211106232576256)); if (!!(((*LOC154).kind == ((Ttypekind294244) 3)))) goto LA155; LOC157 = (NimStringDesc*)0; LOC158 = (NimStringDesc*)0; { NIM_BOOL LOC161; LOC161 = (NIM_BOOL)0; LOC161 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC161) goto LA162; LOC161 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA162: ; if (!LOC161) goto LA163; LOC158 = copyString(((NimStringDesc*) &T839829468_76)); } goto LA159; LA163: ; { LOC158 = copyString(((NimStringDesc*) &T839829468_77)); } LA159: ; LOC157 = rawNewString(LOC158->Sup.len + 31); appendString(LOC157, LOC158); appendString(LOC157, ((NimStringDesc*) &T839829468_78)); memset((void*)LOC166, 0, sizeof(LOC166)); LOC166[0] = gettypedescaux_535505_839829468(m0, (*t_536942_839829468).sons->data[((NI) 0)], check0); LOC166[1] = result0; appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 4))- 0], LOC157, LOC166, 2); } goto LA152; LA155: ; { result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_79)); } LA152: ; } LA150: ; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_53)); } break; case ((Ttypekind294244) 4): case ((Ttypekind294244) 16): { NI64 n0; Tidobj201004* LOC173; TNimObject* LOC174; n0 = lengthord_322007_3876443242(t_536942_839829468); { if (!(n0 <= IL64(0))) goto LA171; n0 = IL64(1); } LA171: ; result0 = gettypename_535313_839829468(t_536942_839829468); LOC173 = (Tidobj201004*)0; LOC173 = &t_536942_839829468->Sup; LOC174 = (TNimObject*)0; LOC174 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC173, LOC174); { NIM_BOOL LOC177; Ropeobj180006* foo0; TY537238 LOC180; LOC177 = (NIM_BOOL)0; LOC177 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC177)) goto LA178; foo0 = gettypedescaux_535505_839829468(m0, (*t_536942_839829468).sons->data[((NI) 1)], check0); memset((void*)LOC180, 0, sizeof(LOC180)); LOC180[0] = foo0; LOC180[1] = result0; LOC180[2] = rope_180401_2381377266(n0); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_80), LOC180, 3); } LA178: ; } break; case ((Ttypekind294244) 17): case ((Ttypekind294244) 18): { { NIM_BOOL LOC184; Ropeobj180006* cppname0; NI i0; NI chunkstart0; Ropeobj180006* LOC226; LOC184 = (NIM_BOOL)0; LOC184 = isimportedcpptype_535478_839829468(t_536942_839829468); if (!(LOC184)) goto LA185; LOC184 = ((*typ0).kind == ((Ttypekind294244) 11)); LA185: ; if (!LOC184) goto LA186; cppname0 = gettypename_535313_839829468(t_536942_839829468); i0 = ((NI) 0); chunkstart0 = ((NI) 0); { while (1) { if (!(i0 < ((*cppname0).data ? (*cppname0).data->Sup.len : 0))) goto LA189; { NI chunkend0; NI idx0; NI stars0; if (!((NU8)((*cppname0).data->data[i0]) == (NU8)(39))) goto LA192; chunkend0 = (i0 - 1); idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC196; NimStringDesc* LOC199; Ttype294840* typeinslot0; LOC196 = (NIM_BOOL)0; LOC196 = scancppgenericslot_536827_839829468((*cppname0).data, (&i0), (&idx0), (&stars0)); if (!LOC196) goto LA197; LOC199 = (NimStringDesc*)0; LOC199 = copyStrLast((*cppname0).data, chunkstart0, chunkend0); add_180487_2381377266(&result0, LOC199); chunkstart0 = i0; typeinslot0 = resolvestarsincpptype_536891_839829468(typ0, (NI)(idx0 + ((NI) 1)), stars0); { NIM_BOOL LOC202; TY535289 LOC206; Ropeobj180006* LOC207; LOC202 = (NIM_BOOL)0; LOC202 = (typeinslot0 == NIM_NIL); if (LOC202) goto LA203; LOC202 = ((*typeinslot0).kind == ((Ttypekind294244) 62)); LA203: ; if (!LOC202) goto LA204; memset((void*)LOC206, 0, sizeof(LOC206)); LOC207 = (Ropeobj180006*)0; LOC207 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_26), LOC206, 0); add_180482_2381377266(&result0, LOC207); } goto LA200; LA204: ; { Ropeobj180006* LOC209; LOC209 = (Ropeobj180006*)0; LOC209 = gettypedescaux_535505_839829468(m0, typeinslot0, check0); add_180482_2381377266(&result0, LOC209); } LA200: ; } LA197: ; } goto LA190; LA192: ; { i0 += ((NI) 1); } LA190: ; } LA189: ; } { NimStringDesc* LOC215; if (!!((chunkstart0 == ((NI) 0)))) goto LA213; LOC215 = (NimStringDesc*)0; LOC215 = copyStr((*cppname0).data, chunkstart0); add_180487_2381377266(&result0, LOC215); } goto LA211; LA213: ; { result0 = HEX26_180447_2381377266(cppname0, ((NimStringDesc*) &T839829468_82)); { NI i_537516_839829468; NI HEX3Atmp_537665_839829468; NI LOC218; NI res_537668_839829468; i_537516_839829468 = (NI)0; HEX3Atmp_537665_839829468 = (NI)0; LOC218 = (NI)0; LOC218 = len_297339_850551059(typ0); HEX3Atmp_537665_839829468 = (NI)(LOC218 - ((NI) 2)); res_537668_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC225; if (!(res_537668_839829468 <= HEX3Atmp_537665_839829468)) goto LA220; i_537516_839829468 = res_537668_839829468; { if (!(((NI) 1) < i_537516_839829468)) goto LA223; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_83)); } LA223: ; LOC225 = (Ropeobj180006*)0; LOC225 = gettypedescaux_535505_839829468(m0, (*typ0).sons->data[i_537516_839829468], check0); add_180482_2381377266(&result0, LOC225); res_537668_839829468 += ((NI) 1); } LA220: ; } } add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_84)); } LA211: ; LOC226 = (Ropeobj180006*)0; LOC226 = getrecorddesc_536643_839829468(m0, t_536942_839829468, result0, check0); } goto LA182; LA186: ; { Tidobj201004* LOC241; TNimObject* LOC242; Ropeobj180006* recdesc0; result0 = cachegettype_535593_839829468((*m0).forwtypecache, t_536942_839829468); { Tidobj201004* LOC239; TNimObject* LOC240; if (!(result0 == NIM_NIL)) goto LA230; result0 = gettypename_535313_839829468(t_536942_839829468); { NIM_BOOL LOC234; NimStringDesc* LOC237; TY534811 LOC238; LOC234 = (NIM_BOOL)0; LOC234 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC234)) goto LA235; LOC237 = (NimStringDesc*)0; LOC237 = getforwardstructformat_536015_839829468(m0); memset((void*)LOC238, 0, sizeof(LOC238)); LOC238[0] = structorunion_536001_839829468(t_536942_839829468); LOC238[1] = result0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 2))- 0], LOC237, LOC238, 2); } LA235: ; LOC239 = (Tidobj201004*)0; LOC239 = &t_536942_839829468->Sup; LOC240 = (TNimObject*)0; LOC240 = &result0->Sup; idtableput_301094_2984716966((&(*m0).forwtypecache), LOC239, LOC240); } LA230: ; LOC241 = (Tidobj201004*)0; LOC241 = &t_536942_839829468->Sup; LOC242 = (TNimObject*)0; LOC242 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC241, LOC242); { if (!!(((*t_536942_839829468).kind == ((Ttypekind294244) 18)))) goto LA245; recdesc0 = getrecorddesc_536643_839829468(m0, t_536942_839829468, result0, check0); } goto LA243; LA245: ; { recdesc0 = gettupledesc_536777_839829468(m0, t_536942_839829468, result0, check0); } LA243: ; { NIM_BOOL LOC250; LOC250 = (NIM_BOOL)0; LOC250 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC250)) goto LA251; add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], recdesc0); } LA251: ; } LA182: ; } break; case ((Ttypekind294244) 19): { Ttype294840* LOC254; Ropeobj180006* LOC255; Tidobj201004* LOC256; TNimObject* LOC257; LOC254 = (Ttype294840*)0; LOC254 = lastson_297377_850551059(t_536942_839829468); LOC255 = (Ropeobj180006*)0; LOC255 = gettypename_535313_839829468(LOC254); result0 = HEX26_180447_2381377266(LOC255, ((NimStringDesc*) &T839829468_105)); LOC256 = (Tidobj201004*)0; LOC256 = &t_536942_839829468->Sup; LOC257 = (TNimObject*)0; LOC257 = &result0->Sup; idtableput_301094_2984716966((&(*m0).typecache), LOC256, LOC257); { NIM_BOOL LOC260; NI s0; NI64 LOC263; LOC260 = (NIM_BOOL)0; LOC260 = isimportedtype_535451_839829468(t_536942_839829468); if (!!(LOC260)) goto LA261; LOC263 = (NI64)0; LOC263 = getsize_322135_3876443242(t_536942_839829468); s0 = ((NI) (LOC263)); switch (s0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { TY534811 LOC265; memset((void*)LOC265, 0, sizeof(LOC265)); LOC265[0] = result0; LOC265[1] = rope_180401_2381377266(((NI64) ((NI)(s0 * ((NI) 8))))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_106), LOC265, 2); } break; default: { TY534811 LOC267; NI64 LOC268; memset((void*)LOC267, 0, sizeof(LOC267)); LOC267[0] = result0; LOC268 = (NI64)0; LOC268 = getsize_322135_3876443242(t_536942_839829468); LOC267[1] = rope_180401_2381377266(LOC268); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_107), LOC267, 2); } break; } } LA261: ; } break; case ((Ttypekind294244) 11): case ((Ttypekind294244) 13): case ((Ttypekind294244) 15): case ((Ttypekind294244) 46): case ((Ttypekind294244) 47): case ((Ttypekind294244) 49): case ((Ttypekind294244) 8): { Ttype294840* LOC270; LOC270 = (Ttype294840*)0; LOC270 = lastson_297377_850551059(t_536942_839829468); result0 = gettypedescaux_535505_839829468(m0, LOC270, check0); } break; default: { NimStringDesc* LOC272; LOC272 = (NimStringDesc*)0; LOC272 = rawNewString(reprEnum((NI)(*t_536942_839829468).kind, (&NTI294244))->Sup.len + 16); appendString(LOC272, ((NimStringDesc*) &T839829468_108)); appendString(LOC272, reprEnum((NI)(*t_536942_839829468).kind, (&NTI294244))); appendChar(LOC272, 41); internalerror_198113_155036129(LOC272); result0 = NIM_NIL; } break; } excl_270841_2627731572(check0, (*t_536942_839829468).Sup.id); }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, iscompiletimeonly_330706_3876443242)(Ttype294840* t0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((IL64(576460752303423744) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); return result0; } N_NIMCALL(Tstorageloc294812, paramstorageloc_536098_839829468)(Tsym294834* param0) { Tstorageloc294812 result0; result0 = (Tstorageloc294812)0; { Ttype294840* LOC3; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059((*param0).typ, 8388864); if (!!(((IL64(281475110993936) &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0))) goto LA4; result0 = ((Tstorageloc294812) 2); } goto LA1; LA4: ; { result0 = ((Tstorageloc294812) 0); } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, ccgintroducedptr_535611_839829468)(Tsym294834* s0) { NIM_BOOL result0; Ttype294840* pt0; { result0 = (NIM_BOOL)0; pt0 = skiptypes_298099_850551059((*s0).typ, IL64(211106232576256)); { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag294431) 13))&31U)))!=0)) goto LA3; result0 = NIM_TRUE; goto BeforeRet; } goto LA1; LA3: ; { if (!(((*pt0).flags &(1U<<((NU)(((Ttypeflag294431) 12))&31U)))!=0)) goto LA6; result0 = NIM_FALSE; goto BeforeRet; } goto LA1; LA6: ; LA1: ; switch ((*pt0).kind) { case ((Ttypekind294244) 17): { { NIM_BOOL LOC11; NI64 LOC13; LOC11 = (NIM_BOOL)0; LOC11 = (((*s0).options &(1U<<((NU)(((Toption171009) 18))&31U)))!=0); if (LOC11) goto LA12; LOC13 = (NI64)0; LOC13 = getsize_322135_3876443242(pt0); LOC11 = (((NI64) ((NI)(floatsize_178642_4151366050 * ((NI) 2)))) < LOC13); LA12: ; if (!LOC11) goto LA14; result0 = NIM_TRUE; } goto LA9; LA14: ; { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = (((*pt0).flags &(1U<<((NU)(((Ttypeflag294431) 2))&31U)))!=0); if (!(LOC17)) goto LA18; LOC17 = ((*pt0).sons->data[((NI) 0)] == NIM_NIL); LA18: ; if (!LOC17) goto LA19; result0 = NIM_FALSE; } goto LA9; LA19: ; { result0 = NIM_TRUE; } LA9: ; } break; case ((Ttypekind294244) 18): { NIM_BOOL LOC23; NI64 LOC24; LOC23 = (NIM_BOOL)0; LOC24 = (NI64)0; LOC24 = getsize_322135_3876443242(pt0); LOC23 = (((NI64) ((NI)(floatsize_178642_4151366050 * ((NI) 2)))) < LOC24); if (LOC23) goto LA25; LOC23 = (((*s0).options &(1U<<((NU)(((Toption171009) 18))&31U)))!=0); LA25: ; result0 = LOC23; } break; default: { result0 = NIM_FALSE; } break; } }BeforeRet: ; return result0; } N_NIMCALL(Tctypekind531007, mapreturntype_535447_839829468)(Ttype294840* typ0) { Tctypekind531007 result0; result0 = (Tctypekind531007)0; result0 = maptype_535394_839829468(typ0); return result0; } N_NIMCALL(void, genprocparams_536115_839829468)(Tcgen531027* m0, Ttype294840* t0, Ropeobj180006** rettype0, Ropeobj180006** params0, Intset270030* check0, NIM_BOOL declareenvironment0, NIM_BOOL weakdep0) { unsureAsgnRef((void**) (&(*params0)), NIM_NIL); { NIM_BOOL LOC3; TY535289 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).sons->data[((NI) 0)] == NIM_NIL); if (LOC3) goto LA4; LOC3 = isinvalidreturntype_535550_839829468((*t0).sons->data[((NI) 0)]); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); unsureAsgnRef((void**) (&(*rettype0)), HEX25_180905_2381377266(((NimStringDesc*) &T839829468_26), LOC7, 0)); } goto LA1; LA5: ; { unsureAsgnRef((void**) (&(*rettype0)), gettypedescaux_535505_839829468(m0, (*t0).sons->data[((NI) 0)], check0)); } LA1: ; { NI i_536152_839829468; NI HEX3Atmp_536353_839829468; NI LOC10; NI res_536356_839829468; i_536152_839829468 = (NI)0; HEX3Atmp_536353_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = sonslen_297351_850551059((*t0).n); HEX3Atmp_536353_839829468 = (NI)(LOC10 - ((NI) 1)); res_536356_839829468 = ((NI) 1); { while (1) { if (!(res_536356_839829468 <= HEX3Atmp_536353_839829468)) goto LA12; i_536152_839829468 = res_536356_839829468; { Tsym294834* param0; Ropeobj180006* LOC29; Tstorageloc294812 LOC30; TY535289 LOC45; Ropeobj180006* LOC46; Ttype294840* arr0; NI j0; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_536152_839829468]).kind == ((Tnodekind294020) 3)))) goto LA16; internalerror_198100_155036129((*(*t0).n).info, ((NimStringDesc*) &T839829468_109)); } LA16: ; param0 = (*(*(*t0).n).kindU.S6.sons->data[i_536152_839829468]).kindU.S4.sym; { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = iscompiletimeonly_330706_3876443242((*param0).typ); if (!LOC20) goto LA21; goto LA13; } LA21: ; { TY535289 LOC27; Ropeobj180006* LOC28; if (!!(((*params0) == NIM_NIL))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj180006*)0; LOC28 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC27, 0); add_180482_2381377266(params0, LOC28); } LA25: ; LOC29 = (Ropeobj180006*)0; LOC29 = manglename_535205_839829468(param0); LOC30 = (Tstorageloc294812)0; LOC30 = paramstorageloc_536098_839829468(param0); fillloc_534282_839829468((&(*param0).loc), ((Tlockind294808) 4), (*param0).typ, LOC29, LOC30); { NIM_BOOL LOC33; Ropeobj180006* LOC36; TY535289 LOC37; Ropeobj180006* LOC38; LOC33 = (NIM_BOOL)0; LOC33 = ccgintroducedptr_535611_839829468(param0); if (!LOC33) goto LA34; LOC36 = (Ropeobj180006*)0; LOC36 = gettypedescweak_536079_839829468(m0, (*param0).typ, check0); add_180482_2381377266(params0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj180006*)0; LOC38 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_53), LOC37, 0); add_180482_2381377266(params0, LOC38); (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag294810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc294812) 0); } goto LA31; LA34: ; { Ropeobj180006* LOC42; if (!weakdep0) goto LA40; LOC42 = (Ropeobj180006*)0; LOC42 = gettypedescweak_536079_839829468(m0, (*param0).typ, check0); add_180482_2381377266(params0, LOC42); } goto LA31; LA40: ; { Ropeobj180006* LOC44; LOC44 = (Ropeobj180006*)0; LOC44 = gettypedescaux_535505_839829468(m0, (*param0).typ, check0); add_180482_2381377266(params0, LOC44); } LA31: ; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj180006*)0; LOC46 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_111), LOC45, 0); add_180482_2381377266(params0, LOC46); add_180482_2381377266(params0, (*param0).loc.r); arr0 = (*param0).typ; { if (!((*arr0).kind == ((Ttypekind294244) 23))) goto LA49; arr0 = (*arr0).sons->data[((NI) 0)]; } LA49: ; j0 = ((NI) 0); { while (1) { TY534811 LOC57; if (!((IL64(281475110928384) &((NU64)1<<((NU)((*arr0).kind)&63U)))!=0)) goto LA52; { if (!((*(*param0).typ).kind == ((Ttypekind294244) 23))) goto LA55; (*param0).loc.s = ((Tstorageloc294812) 0); } LA55: ; memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = (*param0).loc.r; LOC57[1] = rope_180401_2381377266(((NI64) (j0))); addf_181205_2381377266(params0, ((NimStringDesc*) &T839829468_112), LOC57, 2); j0 += ((NI) 1); arr0 = (*arr0).sons->data[((NI) 0)]; } LA52: ; } } LA13: ; res_536356_839829468 += ((NI) 1); } LA12: ; } } { NIM_BOOL LOC60; Ttype294840* arr0; TY535289 LOC76; LOC60 = (NIM_BOOL)0; LOC60 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); if (!(LOC60)) goto LA61; LOC60 = isinvalidreturntype_535550_839829468((*t0).sons->data[((NI) 0)]); LA61: ; if (!LOC60) goto LA62; arr0 = (*t0).sons->data[((NI) 0)]; { if (!!(((*params0) == NIM_NIL))) goto LA66; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA66: ; { Tctypekind531007 LOC70; Ropeobj180006* LOC73; LOC70 = (Tctypekind531007)0; LOC70 = mapreturntype_535447_839829468((*t0).sons->data[((NI) 0)]); if (!!((LOC70 == ((Tctypekind531007) 17)))) goto LA71; LOC73 = (Ropeobj180006*)0; LOC73 = gettypedescweak_536079_839829468(m0, arr0, check0); add_180482_2381377266(params0, LOC73); add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_53)); } goto LA68; LA71: ; { Ropeobj180006* LOC75; LOC75 = (Ropeobj180006*)0; LOC75 = gettypedescaux_535505_839829468(m0, arr0, check0); add_180482_2381377266(params0, LOC75); } LA68: ; memset((void*)LOC76, 0, sizeof(LOC76)); addf_181205_2381377266(params0, ((NimStringDesc*) &T839829468_113), LOC76, 0); } LA62: ; { NIM_BOOL LOC79; LOC79 = (NIM_BOOL)0; LOC79 = ((*t0).callconv == ((Tcallingconvention294002) 8)); if (!(LOC79)) goto LA80; LOC79 = declareenvironment0; LA80: ; if (!LOC79) goto LA81; { if (!!(((*params0) == NIM_NIL))) goto LA85; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA85: ; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_114)); } LA81: ; { if (!(((*t0).flags &(1U<<((NU)(((Ttypeflag294431) 0))&31U)))!=0)) goto LA89; { if (!!(((*params0) == NIM_NIL))) goto LA93; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_110)); } LA93: ; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_115)); } LA89: ; { if (!((*params0) == NIM_NIL)) goto LA97; add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_116)); } goto LA95; LA97: ; { add_180487_2381377266(params0, ((NimStringDesc*) &T839829468_117)); } LA95: ; unsureAsgnRef((void**) (&(*params0)), HEX26_180452_2381377266(((NimStringDesc*) &T839829468_118), (*params0))); } N_NIMCALL(Ropeobj180006*, genprocheader_537867_839829468)(Tcgen531027* m0, Tsym294834* prc0) { Ropeobj180006* result0; Ropeobj180006* rettype0; Ropeobj180006* params0; Intset270030 check0; Ropeobj180006* LOC13; result0 = (Ropeobj180006*)0; rettype0 = (Ropeobj180006*)0; params0 = (Ropeobj180006*)0; genclinedir_534813_839829468(&result0, (*prc0).info); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 5))&15U)))!=0)) goto LA3; { if (!(((*m0).flags &(1U<<((NU)(((Codegenflag531025) 3))&7U)))!=0)) goto LA7; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } goto LA5; LA7: ; { add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_23)); } LA5: ; } goto LA1; LA3: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention294002) 5))) goto LA11; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_24)); } goto LA1; LA11: ; LA1: ; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_270885_2627731572((&check0)); LOC13 = (Ropeobj180006*)0; LOC13 = manglename_535205_839829468(prc0); fillloc_534282_839829468((&(*prc0).loc), ((Tlockind294808) 7), (*prc0).typ, LOC13, ((Tstorageloc294812) 0)); genprocparams_536115_839829468(m0, (*prc0).typ, &rettype0, &params0, (&check0), NIM_TRUE, NIM_FALSE); { TY537235 LOC18; if (!(*prc0).constraint == 0) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_180277_2381377266(Callingconvtostr_535587_839829468[((*(*prc0).typ).callconv)- 0]); LOC18[1] = rettype0; LOC18[2] = (*prc0).loc.r; LOC18[3] = params0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_119), LOC18, 4); } goto LA14; LA16: ; { TY537238 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rettype0; LOC20[1] = (*prc0).loc.r; LOC20[2] = params0; result0 = HEX25_180905_2381377266((*(*prc0).constraint).kindU.S3.strval, LOC20, 3); } LA14: ; return result0; } static N_INLINE(Tnode294802*, HEX5BHEX5D_295238_850551059)(Tnode294802* n0, NI i0) { Tnode294802* result0; result0 = (Tnode294802*)0; result0 = (*n0).kindU.S6.sons->data[i0]; return result0; } N_NIMCALL(Tnode294802*, easyresultasgn_562191_839829468)(Tnode294802* n0) { Tnode294802* result0; { result0 = (Tnode294802*)0; switch ((*n0).kind) { case ((Tnodekind294020) 115): case ((Tnodekind294020) 126): { NI i0; i0 = ((NI) 0); { while (1) { NIM_BOOL LOC4; NI LOC5; Tnode294802* LOC7; LOC4 = (NIM_BOOL)0; LOC5 = (NI)0; LOC5 = len_295081_850551059(n0); LOC4 = (i0 < LOC5); if (!(LOC4)) goto LA6; LOC7 = (Tnode294802*)0; LOC7 = HEX5BHEX5D_295238_850551059(n0, i0); LOC4 = ((*LOC7).kind == ((Tnodekind294020) 1) || (*LOC7).kind >= ((Tnodekind294020) 79) && (*LOC7).kind <= ((Tnodekind294020) 81) || (*LOC7).kind == ((Tnodekind294020) 84) || (*LOC7).kind == ((Tnodekind294020) 98) || (*LOC7).kind == ((Tnodekind294020) 101) || (*LOC7).kind == ((Tnodekind294020) 125)); LA6: ; if (!LOC4) goto LA3; i0 += ((NI) 1); } LA3: ; } { NI LOC10; Tnode294802* LOC13; LOC10 = (NI)0; LOC10 = len_295081_850551059(n0); if (!(i0 < LOC10)) goto LA11; LOC13 = (Tnode294802*)0; LOC13 = HEX5BHEX5D_295238_850551059(n0, i0); result0 = easyresultasgn_562191_839829468(LOC13); } LA11: ; } break; case ((Tnodekind294020) 73): case ((Tnodekind294020) 74): { { NIM_BOOL LOC17; Tnode294802* LOC18; Tnode294802* LOC20; LOC17 = (NIM_BOOL)0; LOC18 = (Tnode294802*)0; LOC18 = HEX5BHEX5D_295238_850551059(n0, ((NI) 0)); LOC17 = ((*LOC18).kind == ((Tnodekind294020) 3)); if (!(LOC17)) goto LA19; LOC20 = (Tnode294802*)0; LOC20 = HEX5BHEX5D_295238_850551059(n0, ((NI) 0)); LOC17 = (((Tsymkind294435) 11) == (*(*LOC20).kindU.S4.sym).kind); LA19: ; if (!LOC17) goto LA21; (*n0).flags |= ((NU16)1)<<((((Tnodeflag294427) 14))%(sizeof(NU16)*8)); result0 = HEX5BHEX5D_295238_850551059(n0, ((NI) 1)); goto BeforeRet; } LA21: ; } break; case ((Tnodekind294020) 109): { { NI LOC26; Tnode294802* LOC29; LOC26 = (NI)0; LOC26 = len_295081_850551059(n0); if (!(((NI) 0) < LOC26)) goto LA27; LOC29 = (Tnode294802*)0; LOC29 = HEX5BHEX5D_295238_850551059(n0, ((NI) 0)); result0 = easyresultasgn_562191_839829468(LOC29); { if (!!((result0 == NIM_NIL))) goto LA32; (*n0).flags |= ((NU16)1)<<((((Tnodeflag294427) 14))%(sizeof(NU16)*8)); } LA32: ; } LA27: ; } break; default: { } break; } }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, gettypedesc_537673_839829468)(Tcgen531027* m0, Ttype294840* typ0) { Ropeobj180006* result0; Intset270030 check0; result0 = (Ropeobj180006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_270885_2627731572((&check0)); result0 = gettypedescaux_535505_839829468(m0, typ0, (&check0)); return result0; } N_NIMCALL(Ropeobj180006*, localvardecl_540532_839829468)(Tcproc531021* p0, Tsym294834* s0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { Ropeobj180006* LOC5; if (!((*s0).loc.k == ((Tlockind294808) 0))) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = manglename_535205_839829468(s0); fillloc_534282_839829468((&(*s0).loc), ((Tlockind294808) 2), (*s0).typ, LOC5, ((Tstorageloc294812) 2)); { if (!((*s0).kind == ((Tsymkind294435) 9))) goto LA8; (*s0).loc.flags |= ((NU16)1)<<((((Tlocflag294810) 2))%(sizeof(NU16)*8)); } LA8: ; } LA3: ; result0 = gettypedesc_537673_839829468((*p0).module, (*s0).loc.t); { if (!(*s0).constraint == 0) goto LA12; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 8))&31U)))!=0)) goto LA16; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_121)); } LA16: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 7))&31U)))!=0)) goto LA20; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_122)); } LA20: ; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_111)); add_180482_2381377266(&result0, (*s0).loc.r); } goto LA10; LA12: ; { TY534811 LOC23; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = result0; LOC23[1] = (*s0).loc.r; result0 = HEX25_180905_2381377266((*(*s0).constraint).kindU.S3.strval, LOC23, 2); } LA10: ; return result0; } N_NIMCALL(void, initloc_534273_839829468)(Tloc294816* result0, Tlockind294808 k0, Ttype294840* typ0, Tstorageloc294812 s0) { (*result0).k = k0; (*result0).s = s0; unsureAsgnRef((void**) (&(*result0).t), typ0); unsureAsgnRef((void**) (&(*result0).r), NIM_NIL); (*result0).flags = 0; } N_NIMCALL(void, initlocexprsingleuse_541289_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* result0) { initloc_534273_839829468(result0, ((Tlockind294808) 0), (*e0).typ, ((Tstorageloc294812) 0)); (*result0).flags |= ((NU16)1)<<((((Tlocflag294810) 8))%(sizeof(NU16)*8)); expr_541248_839829468(p0, e0, result0); } static N_INLINE(Ropeobj180006**, s_531179_3723162438)(Tcproc531021* p0, Tcprocsection531011 s0) { Ropeobj180006** result0; result0 = (Ropeobj180006**)0; result0 = &(*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].sections[(s0)- 0]; return result0; } N_NIMCALL(Ropeobj180006*, indentline_534656_839829468)(Tcproc531021* p0, Ropeobj180006* r0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = r0; { NI i_534680_839829468; NI HEX3Atmp_534683_839829468; NI res_534686_839829468; i_534680_839829468 = (NI)0; HEX3Atmp_534683_839829468 = (NI)0; HEX3Atmp_534683_839829468 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); res_534686_839829468 = ((NI) 0); { while (1) { if (!(res_534686_839829468 <= HEX3Atmp_534683_839829468)) goto LA3; i_534680_839829468 = res_534686_839829468; prepend_180893_2381377266(&result0, indent_534655_839829468); res_534686_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(void, linefmt_534714_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; Ropeobj180006* LOC3; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj180006*)0; LOC3 = indentline_534656_839829468(p0, LOC2); add_180482_2381377266(LOC1, LOC3); } N_NIMCALL(Ropeobj180006*, rdloc_540188_839829468)(Tloc294816* a0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = (*a0).r; { TY180507 LOC5; if (!(((*a0).flags &(1U<<((NU)(((Tlocflag294810) 0))&15U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = result0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_124), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(void, line_534690_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, Ropeobj180006* r0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = indentline_534656_839829468(p0, r0); add_180482_2381377266(LOC1, LOC2); } N_NIMCALL(void, linef_534700_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; Ropeobj180006* LOC3; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = HEX25_180905_2381377266(frmt0, args0, args0Len0); LOC3 = (Ropeobj180006*)0; LOC3 = indentline_534656_839829468(p0, LOC2); add_180482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentypeinfoauxbase_537960_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0, Ropeobj180006* base0) { NI nimtypekind0; Ropeobj180006* size0; TY537235 LOC17; NI flags0; Ropeobj180006* LOC33; TY534811 LOC34; NimStringDesc* LOC35; nimtypekind0 = (NI)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isobjlackingtypefield_535515_839829468(typ0); if (!LOC3) goto LA4; nimtypekind0 = ((NI) 18); } goto LA1; LA4: ; { nimtypekind0 = ((NI) ((*typ0).kind)); } LA1: ; size0 = (Ropeobj180006*)0; { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 0))&31U)))!=0)) goto LA9; size0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_133)); } goto LA7; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC12) goto LA13; LOC12 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; size0 = gettypedesc_537673_839829468(m0, origtype0); } goto LA7; LA14: ; { size0 = gettypedesc_537673_839829468(m0, typ0); } LA7: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = name0; LOC17[1] = size0; LOC17[2] = rope_180401_2381377266(((NI64) (nimtypekind0))); LOC17[3] = base0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_134), LOC17, 4); flags0 = ((NI) 0); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = containsgarbagecollectedref_322117_3876443242(typ0); if (!!(LOC20)) goto LA21; flags0 = (NI)(flags0 | ((NI) 1)); } LA21: ; { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = canformacycle_322123_3876443242(typ0); if (!!(LOC25)) goto LA26; flags0 = (NI)(flags0 | ((NI) 2)); } LA26: ; { TY534811 LOC32; if (!!((flags0 == ((NI) 0)))) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; LOC32[1] = rope_180401_2381377266(((NI64) (flags0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_135), LOC32, 2); } LA30: ; LOC33 = (Ropeobj180006*)0; LOC33 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_129)); memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = name0; LOC35 = (NimStringDesc*)0; LOC35 = typetostring_322017_3876443242(typ0, ((Tprefereddesc322011) 0)); LOC34[1] = rope_180277_2381377266(LOC35); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_136), LOC34, 2); } N_NIMCALL(Ropeobj180006*, getnimnode_537945_839829468)(Tcgen531027* m0) { Ropeobj180006* result0; TY534811 LOC1; result0 = (Ropeobj180006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = (*m0).typenodesname; LOC1[1] = rope_180401_2381377266(((NI64) ((*m0).typenodes))); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_138), LOC1, 2); (*m0).typenodes += ((NI) 1); return result0; } N_NIMCALL(void, gentupleinfo_538551_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0) { Ropeobj180006* LOC1; Ropeobj180006* expr0; NI length0; TY534811 LOC15; LOC1 = (Ropeobj180006*)0; LOC1 = rope_180277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_537960_839829468(m0, typ0, typ0, name0, LOC1); expr0 = getnimnode_537945_839829468(m0); length0 = sonslen_297327_850551059(typ0); { Ropeobj180006* tmp0; TY534811 LOC6; TY537238 LOC12; if (!(((NI) 0) < length0)) goto LA4; tmp0 = gettempname_535598_839829468(m0); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = tmp0; LOC6[1] = rope_180401_2381377266(((NI64) (length0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC6, 2); { NI i_538573_839829468; NI HEX3Atmp_538592_839829468; NI res_538595_839829468; i_538573_839829468 = (NI)0; HEX3Atmp_538592_839829468 = (NI)0; HEX3Atmp_538592_839829468 = (NI)(length0 - ((NI) 1)); res_538595_839829468 = ((NI) 0); { while (1) { Ttype294840* a0; Ropeobj180006* tmp20; TY537238 LOC10; TY537235 LOC11; if (!(res_538595_839829468 <= HEX3Atmp_538592_839829468)) goto LA9; i_538573_839829468 = res_538595_839829468; a0 = (*typ0).sons->data[i_538573_839829468]; tmp20 = getnimnode_537945_839829468(m0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0; LOC10[1] = rope_180401_2381377266(((NI64) (i_538573_839829468))); LOC10[2] = tmp20; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC10, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = tmp20; LOC11[1] = gettypedesc_537673_839829468(m0, typ0); LOC11[2] = rope_180401_2381377266(((NI64) (i_538573_839829468))); LOC11[3] = gentypeinfo_537941_839829468(m0, a0); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_141), LOC11, 4); res_538595_839829468 += ((NI) 1); } LA9: ; } } memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = expr0; LOC12[1] = rope_180401_2381377266(((NI64) (length0))); LOC12[2] = tmp0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC12, 3); } goto LA2; LA4: ; { TY534811 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_180401_2381377266(((NI64) (length0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC14, 2); } LA2: ; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = name0; LOC15[1] = expr0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC15, 2); } N_NIMCALL(Ttype294840*, fakeclosuretype_539010_839829468)(Tsym294834* owner0) { Ttype294840* result0; Ttype294840* LOC1; Ttype294840* r0; Ttype294840* LOC2; result0 = (Ttype294840*)0; result0 = newtype_297107_850551059(((Ttypekind294244) 18), owner0); LOC1 = (Ttype294840*)0; LOC1 = newtype_297107_850551059(((Ttypekind294244) 26), owner0); rawaddson_298394_850551059(result0, LOC1); r0 = newtype_297107_850551059(((Ttypekind294244) 22), owner0); LOC2 = (Ttype294840*)0; LOC2 = newtype_297107_850551059(((Ttypekind294244) 18), owner0); rawaddson_298394_850551059(r0, LOC2); rawaddson_298394_850551059(result0, r0); return result0; } N_NIMCALL(void, gentypeinfoaux_538027_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0) { Ropeobj180006* base0; base0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; NI LOC4; Ttype294840* x0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = sonslen_297327_850551059(typ0); LOC3 = (((NI) 0) < LOC4); if (!(LOC3)) goto LA5; LOC3 = !(((*typ0).sons->data[((NI) 0)] == NIM_NIL)); LA5: ; if (!LOC3) goto LA6; x0 = (*typ0).sons->data[((NI) 0)]; { if (!((*typ0).kind == ((Ttypekind294244) 17))) goto LA10; x0 = skiptypes_298099_850551059(x0, IL64(211106247215360)); } LA10: ; base0 = gentypeinfo_537941_839829468(m0, x0); } goto LA1; LA6: ; { base0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_18)); } LA1: ; gentypeinfoauxbase_537960_839829468(m0, typ0, origtype0, name0, base0); } static N_INLINE(NIM_BOOL, iscomplexvaluetype_540317_839829468)(Ttype294840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((983056 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); if (LOC1) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind294244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention294002) 8)); LA4: ; LOC1 = LOC3; LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, usestringh_534345_839829468)(Tcgen531027* m0) { { NIM_BOOL LOC5; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag531025) 4))&7U)))!=0))) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag531025) 4))%(sizeof(NU8)*8)); LOC5 = (NIM_BOOL)0; LOC5 = includestr_148249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_151)); } LA3: ; } N_NIMCALL(Ropeobj180006*, addrloc_540204_839829468)(Tloc294816* a0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = (*a0).r; { NIM_BOOL LOC3; Tctypekind531007 LOC5; Ropeobj180006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = !((((*a0).flags &(1U<<((NU)(((Tlocflag294810) 0))&15U)))!=0)); if (!(LOC3)) goto LA4; LOC5 = (Tctypekind531007)0; LOC5 = maptype_535394_839829468((*a0).t); LOC3 = !((LOC5 == ((Tctypekind531007) 17))); LA4: ; if (!LOC3) goto LA6; LOC8 = (Ropeobj180006*)0; LOC8 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_128), result0); result0 = HEX26_180447_2381377266(LOC8, ((NimStringDesc*) &T839829468_117)); } LA6: ; return result0; } N_NIMCALL(void, genobjectinit_540242_839829468)(Tcproc531021* p0, Tcprocsection531011 section0, Ttype294840* t0, Tloc294816* a0, NIM_BOOL takeaddr0) { Ttypefieldresult322145 LOC1; LOC1 = (Ttypefieldresult322145)0; LOC1 = analyseobjectwithtypefield_322149_3876443242(t0); switch (LOC1) { case ((Ttypefieldresult322145) 0): { } break; case ((Ttypefieldresult322145) 1): { Ropeobj180006* r0; Ttype294840* s0; TY534811 LOC19; r0 = rdloc_540188_839829468(a0); { TY180507 LOC8; if (!!(takeaddr0)) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = r0; r0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_124), LOC8, 1); } LA6: ; s0 = skiptypes_298099_850551059(t0, IL64(211106232576256)); { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA12: ; if (!!(LOC11)) goto LA13; { while (1) { NIM_BOOL LOC17; LOC17 = (NIM_BOOL)0; LOC17 = ((*s0).kind == ((Ttypekind294244) 17)); if (!(LOC17)) goto LA18; LOC17 = !(((*s0).sons->data[((NI) 0)] == NIM_NIL)); LA18: ; if (!LOC17) goto LA16; add_180487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); s0 = skiptypes_298099_850551059((*s0).sons->data[((NI) 0)], IL64(211106247215360)); } LA16: ; } } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = r0; LOC19[1] = gentypeinfo_537941_839829468((*p0).module, t0); linefmt_534714_839829468(p0, section0, ((NimStringDesc*) &T839829468_154), LOC19, 2); } break; case ((Ttypefieldresult322145) 2): { Ropeobj180006* r0; TY534811 LOC26; { if (!takeaddr0) goto LA23; r0 = addrloc_540204_839829468(a0); } goto LA21; LA23: ; { r0 = rdloc_540188_839829468(a0); } LA21: ; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = r0; LOC26[1] = gentypeinfo_537941_839829468((*p0).module, t0); linefmt_534714_839829468(p0, section0, ((NimStringDesc*) &T839829468_155), LOC26, 2); } break; } } N_NIMCALL(void, constructloc_540388_839829468)(Tcproc531021* p0, Tloc294816* loc0, NIM_BOOL istemp0) { Ttype294840* typ0; typ0 = skiptypes_298099_850551059((*loc0).t, IL64(211106233624832)); { NIM_BOOL LOC3; TY534811 LOC6; LOC3 = (NIM_BOOL)0; LOC3 = iscomplexvaluetype_540317_839829468(typ0); if (!!(LOC3)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_540188_839829468(loc0); LOC6[1] = gettypedesc_537673_839829468((*p0).module, typ0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_150), LOC6, 2); } goto LA1; LA4: ; { { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = !(istemp0); if (LOC10) goto LA11; LOC10 = containsgarbagecollectedref_322117_3876443242((*loc0).t); LA11: ; if (!LOC10) goto LA12; { NIM_BOOL LOC16; TY534811 LOC19; LOC16 = (NIM_BOOL)0; LOC16 = isimportedcpptype_535478_839829468(typ0); if (!!(LOC16)) goto LA17; usestringh_534345_839829468((*p0).module); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_540204_839829468(loc0); LOC19[1] = rdloc_540188_839829468(loc0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_152), LOC19, 2); } LA17: ; } LA12: ; genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 2), (*loc0).t, loc0, NIM_TRUE); } LA1: ; } N_NIMCALL(void, gettemp_539032_839829468)(Tcproc531021* p0, Ttype294840* t0, Tloc294816* result0, NIM_BOOL needsinit0) { Ropeobj180006* LOC1; TY534811 LOC2; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj180006*)0; LOC1 = rope_180401_2381377266(((NI64) ((*p0).labels))); unsureAsgnRef((void**) (&(*result0).r), HEX26_180452_2381377266(((NimStringDesc*) &T839829468_149), LOC1)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC2[1] = (*result0).r; linefmt_534714_839829468(p0, ((Tcprocsection531011) 0), ((NimStringDesc*) &T839829468_54), LOC2, 2); (*result0).k = ((Tlockind294808) 1); unsureAsgnRef((void**) (&(*result0).t), t0); (*result0).s = ((Tstorageloc294812) 2); (*result0).flags = 0; constructloc_540388_839829468(p0, (&(*result0)), !(needsinit0)); } static N_INLINE(Ropeobj180006*, parentobj_539257_839829468)(Ropeobj180006* accessor0, Tcgen531027* m0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; TY180507 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = accessor0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_161), LOC7, 1); } goto LA1; LA5: ; { result0 = accessor0; } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, intliteral_541270_839829468)(NI64 i0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (IL64(-2147483648) < i0); if (!(LOC3)) goto LA4; LOC3 = (i0 <= IL64(2147483647)); LA4: ; if (!LOC3) goto LA5; result0 = rope_180401_2381377266(i0); } goto LA1; LA5: ; { TY535289 LOC10; if (!(i0 == IL64(-2147483648))) goto LA8; memset((void*)LOC10, 0, sizeof(LOC10)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_166), LOC10, 0); } goto LA1; LA8: ; { TY180507 LOC14; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_180401_2381377266(i0); result0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC14, 1); } goto LA1; LA12: ; { TY535289 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_168), LOC16, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, int64literal_551430_839829468)(NI64 i0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { TY180507 LOC5; if (!((IL64(-9223372036854775807) - IL64(1)) < i0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_180401_2381377266(i0); result0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_167), LOC5, 1); } goto LA1; LA3: ; { TY535289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_168), LOC7, 0); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, uint64literal_551442_839829468)(NU64 i0) { Ropeobj180006* result0; NimStringDesc* LOC1; NimStringDesc* LOC2; result0 = (Ropeobj180006*)0; LOC1 = (NimStringDesc*)0; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_8401_1689653243(i0); LOC1 = rawNewString(LOC2->Sup.len + 3); appendString(LOC1, LOC2); appendString(LOC1, ((NimStringDesc*) &T839829468_171)); result0 = rope_180277_2381377266(LOC1); return result0; } N_NIMCALL(Ropeobj180006*, getstrlit_551468_839829468)(Tcgen531027* m0, NimStringDesc* s0) { Ropeobj180006* result0; Ropeobj180006* LOC1; TY537238 LOC2; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_79)); result0 = gettempname_535598_839829468(m0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = result0; LOC2[1] = makecstring_193638_155036129(s0); LOC2[2] = rope_180401_2381377266(((NI64) ((s0 ? s0->Sup.len : 0)))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_177), LOC2, 3); return result0; } N_NIMCALL(Ropeobj180006*, genliteral_551476_839829468)(Tcproc531021* p0, Tnode294802* n0, Ttype294840* ty0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!(ty0 == NIM_NIL)) goto LA3; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_165)); } LA3: ; switch ((*n0).kind) { case ((Tnodekind294020) 5) ... ((Tnodekind294020) 15): { Ttype294840* LOC6; LOC6 = (Ttype294840*)0; LOC6 = skiptypes_298099_850551059(ty0, IL64(211106242013440)); switch ((*LOC6).kind) { case ((Ttypekind294244) 2): case ((Ttypekind294244) 5): { result0 = intliteral_541270_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind294244) 1): { { TY535289 LOC13; if (!!(((*n0).kindU.S1.intval == IL64(0)))) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_169), LOC13, 0); } goto LA9; LA11: ; { TY535289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_170), LOC15, 0); } LA9: ; } break; case ((Ttypekind294244) 35): { result0 = int64literal_551430_839829468((*n0).kindU.S1.intval); } break; case ((Ttypekind294244) 44): { result0 = uint64literal_551442_839829468(((NU64) ((*n0).kindU.S1.intval))); } break; default: { TY534811 LOC19; Ttype294840* LOC20; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (Ttype294840*)0; LOC20 = skiptypes_298099_850551059(ty0, IL64(211106242013440)); LOC19[0] = gettypedesc_537673_839829468((*p0).module, LOC20); LOC19[1] = intliteral_541270_839829468((*n0).kindU.S1.intval); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_172), LOC19, 2); } break; } } break; case ((Tnodekind294020) 23): { Ttype294840* t0; t0 = skiptypes_298099_850551059(ty0, IL64(211106242013440)); { NIM_BOOL LOC24; NI id0; Ropeobj180006* LOC28; LOC24 = (NIM_BOOL)0; LOC24 = ((*t0).kind == ((Ttypekind294244) 25)); if (!(LOC24)) goto LA25; LOC24 = ((*t0).callconv == ((Tcallingconvention294002) 8)); LA25: ; if (!LOC24) goto LA26; id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC28 = (Ropeobj180006*)0; LOC28 = rope_180401_2381377266(((NI64) (id0))); result0 = HEX26_180418_2381377266((*(*p0).module).tmpbase, LOC28); { TY534811 LOC33; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA31; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC33[1] = result0; addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_173), LOC33, 2); } LA31: ; } goto LA22; LA26: ; { result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_174)); } LA22: ; } break; case ((Tnodekind294020) 20) ... ((Tnodekind294020) 22): { { TY535289 LOC40; if (!(*n0).kindU.S3.strval == 0) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_175), LOC40, 0); } goto LA36; LA38: ; { Ttype294840* LOC42; NI id0; LOC42 = (Ttype294840*)0; LOC42 = skiptypes_298099_850551059(ty0, IL64(211106242013440)); if (!((*LOC42).kind == ((Ttypekind294244) 28))) goto LA43; id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); { TY180507 LOC49; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA47; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = getstrlit_551468_839829468((*p0).module, (*n0).kindU.S3.strval); result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_176), LOC49, 1); } goto LA45; LA47: ; { TY534811 LOC51; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = (*(*p0).module).tmpbase; LOC51[1] = rope_180401_2381377266(((NI64) (id0))); result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_178), LOC51, 2); } LA45: ; } goto LA36; LA43: ; { result0 = makecstring_193638_155036129((*n0).kindU.S3.strval); } LA36: ; } break; case ((Tnodekind294020) 16) ... ((Tnodekind294020) 18): { NimStringDesc* LOC54; LOC54 = (NimStringDesc*)0; LOC54 = tostrmaxprecision_300007_3471544153((*n0).kindU.S2.floatval); result0 = rope_180277_2381377266(LOC54); } break; default: { NimStringDesc* LOC56; LOC56 = (NimStringDesc*)0; LOC56 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI294020))->Sup.len + 12); appendString(LOC56, ((NimStringDesc*) &T839829468_179)); appendString(LOC56, reprEnum((NI)(*n0).kind, (&NTI294020))); appendChar(LOC56, 41); internalerror_198100_155036129((*n0).info, LOC56); result0 = NIM_NIL; } break; } return result0; } N_NIMCALL(Ropeobj180006*, genliteral_541273_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = genliteral_551476_839829468(p0, n0, (*n0).typ); return result0; } N_NIMCALL(void, gencaserange_539028_839829468)(Tcproc531021* p0, Tnode294802* branch0) { NI length0; length0 = len_295081_850551059(branch0); { NI j_549677_839829468; NI HEX3Atmp_549718_839829468; NI res_549721_839829468; j_549677_839829468 = (NI)0; HEX3Atmp_549718_839829468 = (NI)0; HEX3Atmp_549718_839829468 = (NI)(length0 - ((NI) 2)); res_549721_839829468 = ((NI) 0); { while (1) { if (!(res_549721_839829468 <= HEX3Atmp_549718_839829468)) goto LA3; j_549677_839829468 = res_549721_839829468; { Tnode294802* LOC6; LOC6 = (Tnode294802*)0; LOC6 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); if (!((*LOC6).kind == ((Tnodekind294020) 44))) goto LA7; { TY534811 LOC13; Tnode294802* LOC14; Tnode294802* LOC15; Tnode294802* LOC16; Tnode294802* LOC17; if (!((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 0))&7U)))!=0)) goto LA11; memset((void*)LOC13, 0, sizeof(LOC13)); LOC14 = (Tnode294802*)0; LOC14 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); LOC15 = (Tnode294802*)0; LOC15 = HEX5BHEX5D_295238_850551059(LOC14, ((NI) 0)); LOC13[0] = genliteral_541273_839829468(p0, LOC15); LOC16 = (Tnode294802*)0; LOC16 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); LOC17 = (Tnode294802*)0; LOC17 = HEX5BHEX5D_295238_850551059(LOC16, ((NI) 1)); LOC13[1] = genliteral_541273_839829468(p0, LOC17); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_164), LOC13, 2); } goto LA9; LA11: ; { Tnode294802* v0; Tnode294802* LOC19; Tnode294802* LOC20; LOC19 = (Tnode294802*)0; LOC19 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); LOC20 = (Tnode294802*)0; LOC20 = HEX5BHEX5D_295238_850551059(LOC19, ((NI) 0)); v0 = copynode_298528_850551059(LOC20); { while (1) { Tnode294802* LOC23; Tnode294802* LOC24; TY180507 LOC25; LOC23 = (Tnode294802*)0; LOC23 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); LOC24 = (Tnode294802*)0; LOC24 = HEX5BHEX5D_295238_850551059(LOC23, ((NI) 1)); if (!((*v0).kindU.S1.intval <= (*LOC24).kindU.S1.intval)) goto LA22; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = genliteral_541273_839829468(p0, v0); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_180), LOC25, 1); (*v0).kindU.S1.intval += ((NI) 1); } LA22: ; } } LA9: ; } goto LA4; LA7: ; { TY180507 LOC27; Tnode294802* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Tnode294802*)0; LOC28 = HEX5BHEX5D_295238_850551059(branch0, j_549677_839829468); LOC27[0] = genliteral_541273_839829468(p0, LOC28); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_180), LOC27, 1); } LA4: ; res_549721_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, gentraverseproc_539039_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Tnode294802* n0) { { { if (!(n0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; switch ((*n0).kind) { case ((Tnodekind294020) 138): { { NI i_539068_839829468; NI HEX3Atmp_539239_839829468; NI LOC7; NI res_539242_839829468; i_539068_839829468 = (NI)0; HEX3Atmp_539239_839829468 = (NI)0; LOC7 = (NI)0; LOC7 = sonslen_297351_850551059(n0); HEX3Atmp_539239_839829468 = (NI)(LOC7 - ((NI) 1)); res_539242_839829468 = ((NI) 0); { while (1) { if (!(res_539242_839829468 <= HEX3Atmp_539239_839829468)) goto LA9; i_539068_839829468 = res_539242_839829468; gentraverseproc_539039_839829468(c0, accessor0, (*n0).kindU.S6.sons->data[i_539068_839829468]); res_539242_839829468 += ((NI) 1); } LA9: ; } } } break; case ((Tnodekind294020) 139): { Tcproc531021* p0; Tsym294834* disc0; TY534811 LOC15; TY535289 LOC28; { if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)))) goto LA13; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_162)); } LA13: ; p0 = (*c0).p; disc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = accessor0; LOC15[1] = (*disc0).loc.r; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_163), LOC15, 2); { NI i_539098_839829468; NI HEX3Atmp_539249_839829468; NI LOC17; NI res_539252_839829468; i_539098_839829468 = (NI)0; HEX3Atmp_539249_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = sonslen_297351_850551059(n0); HEX3Atmp_539249_839829468 = (NI)(LOC17 - ((NI) 1)); res_539252_839829468 = ((NI) 1); { while (1) { Tnode294802* branch0; Tnode294802* LOC26; TY535289 LOC27; if (!(res_539252_839829468 <= HEX3Atmp_539249_839829468)) goto LA19; i_539098_839829468 = res_539252_839829468; branch0 = (*n0).kindU.S6.sons->data[i_539098_839829468]; { if (!((*branch0).kind == ((Tnodekind294020) 85))) goto LA22; gencaserange_539028_839829468((*c0).p, branch0); } goto LA20; LA22: ; { TY535289 LOC25; memset((void*)LOC25, 0, sizeof(LOC25)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_181), LOC25, 0); } LA20: ; LOC26 = (Tnode294802*)0; LOC26 = lastson_297364_850551059(branch0); gentraverseproc_539039_839829468(c0, accessor0, LOC26); memset((void*)LOC27, 0, sizeof(LOC27)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_182), LOC27, 0); res_539252_839829468 += ((NI) 1); } LA19: ; } } memset((void*)LOC28, 0, sizeof(LOC28)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_183), LOC28, 0); } break; case ((Tnodekind294020) 3): { Tsym294834* field0; TY534811 LOC34; Ropeobj180006* LOC35; field0 = (*n0).kindU.S4.sym; { if (!((*field0).loc.t == NIM_NIL)) goto LA32; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } LA32: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = accessor0; LOC34[1] = (*field0).loc.r; LOC35 = (Ropeobj180006*)0; LOC35 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_90), LOC34, 2); gentraverseproc_539022_839829468(c0, LOC35, (*field0).loc.t); } break; default: { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_184)); } break; } }BeforeRet: ; } N_NIMCALL(void, linecg_534707_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; Ropeobj180006* LOC3; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, args0, args0Len0); LOC3 = (Ropeobj180006*)0; LOC3 = indentline_534656_839829468(p0, LOC2); add_180482_2381377266(LOC1, LOC3); } N_NIMCALL(void, gentraverseproc_539022_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Ttype294840* typ_539027_839829468) { Ttype294840* typ_539302_839829468; Tcproc531021* p0; { { if (!(typ_539027_839829468 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; typ_539302_839829468 = getuniquetype_530640_2036603609(typ_539027_839829468); p0 = (*c0).p; switch ((*typ_539302_839829468).kind) { case ((Ttypekind294244) 11): case ((Ttypekind294244) 10): case ((Ttypekind294244) 8): { Ttype294840* LOC6; LOC6 = (Ttype294840*)0; LOC6 = lastson_297377_850551059(typ_539302_839829468); gentraverseproc_539022_839829468(c0, accessor0, LOC6); } break; case ((Ttypekind294244) 4): case ((Ttypekind294244) 16): { NI64 arraysize0; Tloc294816 i0; Ttype294840* LOC8; TY534811 LOC9; TY534811 LOC10; Ropeobj180006* LOC11; TY535289 LOC12; arraysize0 = lengthord_322007_3876443242((*typ_539302_839829468).sons->data[((NI) 0)]); memset((void*)(&i0), 0, sizeof(i0)); LOC8 = (Ttype294840*)0; LOC8 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC8, (&i0), NIM_FALSE); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = i0.r; LOC9[1] = rope_180401_2381377266(arraysize0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_159), LOC9, 2); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = accessor0; LOC10[1] = i0.r; LOC11 = (Ropeobj180006*)0; LOC11 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC10, 2); gentraverseproc_539022_839829468(c0, LOC11, (*typ_539302_839829468).sons->data[((NI) 1)]); memset((void*)LOC12, 0, sizeof(LOC12)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC12, 0); } break; case ((Ttypekind294244) 17): { { NI i_539325_839829468; NI HEX3Atmp_539384_839829468; NI LOC15; NI res_539387_839829468; i_539325_839829468 = (NI)0; HEX3Atmp_539384_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = sonslen_297327_850551059(typ_539302_839829468); HEX3Atmp_539384_839829468 = (NI)(LOC15 - ((NI) 1)); res_539387_839829468 = ((NI) 0); { while (1) { Ttype294840* x0; Ropeobj180006* LOC22; if (!(res_539387_839829468 <= HEX3Atmp_539384_839829468)) goto LA17; i_539325_839829468 = res_539387_839829468; x0 = (*typ_539302_839829468).sons->data[i_539325_839829468]; { if (!!((x0 == NIM_NIL))) goto LA20; x0 = skiptypes_298099_850551059(x0, IL64(211106247215360)); } LA20: ; LOC22 = (Ropeobj180006*)0; LOC22 = parentobj_539257_839829468(accessor0, (*(*c0).p).module); gentraverseproc_539022_839829468(c0, LOC22, x0); res_539387_839829468 += ((NI) 1); } LA17: ; } } { if (!!(((*typ_539302_839829468).n == NIM_NIL))) goto LA25; gentraverseproc_539039_839829468(c0, accessor0, (*typ_539302_839829468).n); } LA25: ; } break; case ((Ttypekind294244) 18): { Ttype294840* typ0; typ0 = getuniquetype_530640_2036603609(typ_539302_839829468); { NI i_539363_839829468; NI HEX3Atmp_539392_839829468; NI LOC29; NI res_539395_839829468; i_539363_839829468 = (NI)0; HEX3Atmp_539392_839829468 = (NI)0; LOC29 = (NI)0; LOC29 = sonslen_297327_850551059(typ0); HEX3Atmp_539392_839829468 = (NI)(LOC29 - ((NI) 1)); res_539395_839829468 = ((NI) 0); { while (1) { TY534811 LOC32; Ropeobj180006* LOC33; if (!(res_539395_839829468 <= HEX3Atmp_539392_839829468)) goto LA31; i_539363_839829468 = res_539395_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = accessor0; LOC32[1] = rope_180401_2381377266(((NI64) (i_539363_839829468))); LOC33 = (Ropeobj180006*)0; LOC33 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_185), LOC32, 2); gentraverseproc_539022_839829468(c0, LOC33, (*typ0).sons->data[i_539363_839829468]); res_539395_839829468 += ((NI) 1); } LA31: ; } } } break; case ((Ttypekind294244) 22): case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { TY180507 LOC35; memset((void*)LOC35, 0, sizeof(LOC35)); LOC35[0] = accessor0; linecg_534707_839829468(p0, ((Tcprocsection531011) 2), (*c0).visitorfrmt, LOC35, 1); } break; case ((Ttypekind294244) 25): { { TY180507 LOC41; TY180507 LOC42; if (!((*typ_539302_839829468).callconv == ((Tcallingconvention294002) 8))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = accessor0; LOC41[0] = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_186), LOC42, 1); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), (*c0).visitorfrmt, LOC41, 1); } LA39: ; } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, gentraverseprocseq_539399_839829468)(Ttraversalclosure539019* c0, Ropeobj180006* accessor0, Ttype294840* typ0) { Tcproc531021* p0; Tloc294816 i0; Ttype294840* LOC1; TY537238 LOC2; NimStringDesc* LOC3; TY534811 LOC11; Ropeobj180006* LOC12; TY535289 LOC13; p0 = (*c0).p; memset((void*)(&i0), 0, sizeof(i0)); LOC1 = (Ttype294840*)0; LOC1 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC1, (&i0), NIM_FALSE); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = i0.r; LOC2[1] = accessor0; LOC3 = (NimStringDesc*)0; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*(*c0).p).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA7: ; if (!LOC6) goto LA8; LOC3 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA4; LA8: ; { LOC3 = copyString(((NimStringDesc*) &T839829468_158)); } LA4: ; LOC2[2] = rope_180277_2381377266(LOC3); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_156), LOC2, 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = accessor0; LOC11[1] = i0.r; LOC12 = (Ropeobj180006*)0; LOC12 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_187), LOC11, 2); gentraverseproc_539022_839829468(c0, LOC12, (*typ0).sons->data[((NI) 0)]); memset((void*)LOC13, 0, sizeof(LOC13)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC13, 0); } N_NIMCALL(Ropeobj180006*, gentraverseproc_539632_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttypeinforeason539016 reason0) { Ropeobj180006* result0; Ttraversalclosure539019 c0; Tcproc531021* p0; Ropeobj180006* header0; TY180507 LOC3; Ropeobj180006* t0; TY180507 LOC4; TY180507 LOC5; Ropeobj180006* generatedproc0; TY537235 LOC20; Ropeobj180006** LOC21; Ropeobj180006** LOC22; Ropeobj180006** LOC23; TY180507 LOC24; result0 = (Ropeobj180006*)0; memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_531206_3723162438(NIM_NIL, m0); result0 = gettempname_535598_839829468(m0); switch (reason0) { case ((Ttypeinforeason539016) 0): { c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_145)); } break; default: { } break; } memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = result0; header0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_146), LOC3, 1); t0 = gettypedesc_537673_839829468(m0, typ0); memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = t0; linef_534700_839829468(p0, ((Tcprocsection531011) 0), ((NimStringDesc*) &T839829468_147), LOC4, 1); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = t0; linef_534700_839829468(p0, ((Tcprocsection531011) 1), ((NimStringDesc*) &T839829468_148), LOC5, 1); c0.p = p0; { Ropeobj180006* LOC10; if (!((*typ0).kind == ((Ttypekind294244) 24))) goto LA8; LOC10 = (Ropeobj180006*)0; LOC10 = rope_180277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseprocseq_539399_839829468((&c0), LOC10, typ0); } goto LA6; LA8: ; { { Ttype294840* LOC14; Ropeobj180006* LOC17; LOC14 = (Ttype294840*)0; LOC14 = skiptypes_298099_850551059((*typ0).sons->data[((NI) 0)], IL64(211106232576256)); if (!((65552 &((NU64)1<<((NU)((*LOC14).kind)&63U)))!=0)) goto LA15; LOC17 = (Ropeobj180006*)0; LOC17 = rope_180277_2381377266(((NimStringDesc*) &T839829468_188)); gentraverseproc_539022_839829468((&c0), LOC17, (*typ0).sons->data[((NI) 0)]); } goto LA12; LA15: ; { Ropeobj180006* LOC19; LOC19 = (Ropeobj180006*)0; LOC19 = rope_180277_2381377266(((NimStringDesc*) &T839829468_189)); gentraverseproc_539022_839829468((&c0), LOC19, (*typ0).sons->data[((NI) 0)]); } LA12: ; } LA6: ; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = header0; LOC21 = (Ropeobj180006**)0; LOC21 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); LOC20[1] = (*LOC21); LOC22 = (Ropeobj180006**)0; LOC22 = s_531179_3723162438(p0, ((Tcprocsection531011) 1)); LOC20[2] = (*LOC22); LOC23 = (Ropeobj180006**)0; LOC23 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); LOC20[3] = (*LOC23); generatedproc0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_190), LOC20, 4); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = header0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC24, 1); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, genarrayinfo_539005_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0) { Ropeobj180006* LOC1; LOC1 = (Ropeobj180006*)0; LOC1 = gentypeinfo_537941_839829468(m0, (*typ0).sons->data[((NI) 1)]); gentypeinfoauxbase_537960_839829468(m0, typ0, typ0, name0, LOC1); } N_NIMCALL(void, gensetinfo_538867_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0) { Ropeobj180006* tmp0; TY537238 LOC1; NI64 LOC2; gentypeinfoaux_538027_839829468(m0, typ0, typ0, name0); tmp0 = getnimnode_537945_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC2 = (NI64)0; LOC2 = firstord_322001_3876443242(typ0); LOC1[1] = rope_180401_2381377266(LOC2); LOC1[2] = name0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_193), LOC1, 3); } N_NIMCALL(void, genenuminfo_538599_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0) { Ropeobj180006* nodeptrs0; NI length0; TY534811 LOC1; Ropeobj180006* enumnames0; Ropeobj180006* specialcases0; NI firstnimnode0; NIM_BOOL hasholes0; Ropeobj180006* enumarray0; Ropeobj180006* counter0; TY180507 LOC24; TY537238 LOC25; TY538847 LOC26; TY537235 LOC27; gentypeinfoaux_538027_839829468(m0, typ0, typ0, name0); nodeptrs0 = gettempname_535598_839829468(m0); length0 = sonslen_297351_850551059((*typ0).n); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = nodeptrs0; LOC1[1] = rope_180401_2381377266(((NI64) (length0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC1, 2); enumnames0 = (Ropeobj180006*)0; specialcases0 = (Ropeobj180006*)0; firstnimnode0 = (*m0).typenodes; hasholes0 = NIM_FALSE; { NI i_538624_839829468; NI HEX3Atmp_538860_839829468; NI res_538863_839829468; i_538624_839829468 = (NI)0; HEX3Atmp_538860_839829468 = (NI)0; HEX3Atmp_538860_839829468 = (NI)(length0 - ((NI) 1)); res_538863_839829468 = ((NI) 0); { while (1) { Tsym294834* field0; Ropeobj180006* elemnode0; if (!(res_538863_839829468 <= HEX3Atmp_538860_839829468)) goto LA4; i_538624_839829468 = res_538863_839829468; field0 = (*(*(*typ0).n).kindU.S6.sons->data[i_538624_839829468]).kindU.S4.sym; elemnode0 = getnimnode_537945_839829468(m0); { Ropeobj180006* LOC9; if (!((*field0).ast == NIM_NIL)) goto LA7; LOC9 = (Ropeobj180006*)0; LOC9 = makecstring_193638_155036129((*(*field0).name).s); add_180482_2381377266(&enumnames0, LOC9); } goto LA5; LA7: ; { Ropeobj180006* LOC11; LOC11 = (Ropeobj180006*)0; LOC11 = makecstring_193638_155036129((*(*field0).ast).kindU.S3.strval); add_180482_2381377266(&enumnames0, LOC11); } LA5: ; { NimStringDesc* LOC16; if (!(i_538624_839829468 < (NI)(length0 - ((NI) 1)))) goto LA14; LOC16 = (NimStringDesc*)0; LOC16 = rawNewString(tnl_178644_4151366050->Sup.len + 2); appendString(LOC16, ((NimStringDesc*) &T839829468_110)); appendString(LOC16, tnl_178644_4151366050); add_180487_2381377266(&enumnames0, LOC16); } LA14: ; { NIM_BOOL LOC19; TY534811 LOC23; LOC19 = (NIM_BOOL)0; LOC19 = !(((*field0).position == i_538624_839829468)); if (LOC19) goto LA20; LOC19 = (((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 5))&31U)))!=0); LA20: ; if (!LOC19) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = elemnode0; LOC23[1] = rope_180401_2381377266(((NI64) ((*field0).position))); addf_181205_2381377266(&specialcases0, ((NimStringDesc*) &T839829468_194), LOC23, 2); hasholes0 = NIM_TRUE; } LA21: ; res_538863_839829468 += ((NI) 1); } LA4: ; } } enumarray0 = gettempname_535598_839829468(m0); counter0 = gettempname_535598_839829468(m0); memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = counter0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_195), LOC24, 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = enumarray0; LOC25[1] = rope_180401_2381377266(((NI64) (length0))); LOC25[2] = enumnames0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_196), LOC25, 3); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = counter0; LOC26[1] = rope_180401_2381377266(((NI64) (length0))); LOC26[2] = (*m0).typenodesname; LOC26[3] = rope_180401_2381377266(((NI64) (firstnimnode0))); LOC26[4] = enumarray0; LOC26[5] = nodeptrs0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_197), LOC26, 6); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], specialcases0); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = getnimnode_537945_839829468(m0); LOC27[1] = rope_180401_2381377266(((NI64) (length0))); LOC27[2] = nodeptrs0; LOC27[3] = name0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_198), LOC27, 4); { TY180507 LOC32; if (!hasholes0) goto LA30; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = name0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_199), LOC32, 1); } LA30: ; } N_NIMCALL(Ropeobj180006*, discriminatortablename_538057_839829468)(Tcgen531027* m0, Ttype294840* objtype_538060_839829468, Tsym294834* d0) { Ropeobj180006* result0; Ttype294840* objtype0; TY534811 LOC8; NimStringDesc* LOC9; result0 = (Ropeobj180006*)0; objtype0 = objtype_538060_839829468; { while (1) { Tsym294834* LOC3; LOC3 = (Tsym294834*)0; LOC3 = lookupinrecord_301119_2984716966((*objtype0).n, (*d0).name); if (!(LOC3 == NIM_NIL)) goto LA2; objtype0 = (*objtype0).sons->data[((NI) 0)]; } LA2: ; } { if (!((*objtype0).sym == NIM_NIL)) goto LA6; internalerror_198100_155036129((*d0).info, ((NimStringDesc*) &T839829468_200)); } LA6: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_180401_2381377266(((NI64) ((*objtype0).Sup.id))); LOC9 = (NimStringDesc*)0; LOC9 = mangle_530847_2036603609((*(*d0).name).s); LOC8[1] = rope_180277_2381377266(LOC9); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_201), LOC8, 2); return result0; } N_NIMCALL(void, genobjectfields_538104_839829468)(Tcgen531027* m0, Ttype294840* typ0, Tnode294802* n0, Ropeobj180006* expr0) { switch ((*n0).kind) { case ((Tnodekind294020) 138): { NI L0; L0 = sonslen_297351_850551059(n0); { if (!(L0 == ((NI) 1))) goto LA4; genobjectfields_538104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[((NI) 0)], expr0); } goto LA2; LA4: ; { Ropeobj180006* tmp0; TY534811 LOC9; TY537238 LOC14; if (!(((NI) 0) < L0)) goto LA7; tmp0 = gettempname_535598_839829468(m0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = tmp0; LOC9[1] = rope_180401_2381377266(((NI64) (L0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_139), LOC9, 2); { NI i_538127_839829468; NI HEX3Atmp_538482_839829468; NI res_538485_839829468; i_538127_839829468 = (NI)0; HEX3Atmp_538482_839829468 = (NI)0; HEX3Atmp_538482_839829468 = (NI)(L0 - ((NI) 1)); res_538485_839829468 = ((NI) 0); { while (1) { Ropeobj180006* tmp20; TY537238 LOC13; if (!(res_538485_839829468 <= HEX3Atmp_538482_839829468)) goto LA12; i_538127_839829468 = res_538485_839829468; tmp20 = getnimnode_537945_839829468(m0); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = tmp0; LOC13[1] = rope_180401_2381377266(((NI64) (i_538127_839829468))); LOC13[2] = tmp20; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC13, 3); genobjectfields_538104_839829468(m0, typ0, (*n0).kindU.S6.sons->data[i_538127_839829468], tmp20); res_538485_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = expr0; LOC14[1] = rope_180401_2381377266(((NI64) (L0))); LOC14[2] = tmp0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_142), LOC14, 3); } goto LA2; LA7: ; { TY534811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = expr0; LOC16[1] = rope_180401_2381377266(((NI64) (L0))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_143), LOC16, 2); } LA2: ; } break; case ((Tnodekind294020) 139): { Tsym294834* field0; Ropeobj180006* tmp0; NI64 L0; TY538401 LOC18; TY534811 LOC19; field0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; tmp0 = discriminatortablename_538057_839829468(m0, typ0, field0); L0 = lengthord_322007_3876443242((*field0).typ); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = expr0; LOC18[1] = gettypedesc_537673_839829468(m0, typ0); LOC18[2] = (*field0).loc.r; LOC18[3] = gentypeinfo_537941_839829468(m0, (*field0).typ); LOC18[4] = makecstring_193638_155036129((*(*field0).name).s); LOC18[5] = tmp0; LOC18[6] = rope_180401_2381377266(L0); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_202), LOC18, 7); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0; LOC19[1] = rope_180401_2381377266((NI64)(L0 + IL64(1))); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_203), LOC19, 2); { NI i_538421_839829468; NI HEX3Atmp_538501_839829468; NI LOC21; NI res_538504_839829468; i_538421_839829468 = (NI)0; HEX3Atmp_538501_839829468 = (NI)0; LOC21 = (NI)0; LOC21 = sonslen_297351_850551059(n0); HEX3Atmp_538501_839829468 = (NI)(LOC21 - ((NI) 1)); res_538504_839829468 = ((NI) 1); { while (1) { Tnode294802* b0; Ropeobj180006* tmp20; Tnode294802* LOC24; if (!(res_538504_839829468 <= HEX3Atmp_538501_839829468)) goto LA23; i_538421_839829468 = res_538504_839829468; b0 = (*n0).kindU.S6.sons->data[i_538421_839829468]; tmp20 = getnimnode_537945_839829468(m0); LOC24 = (Tnode294802*)0; LOC24 = lastson_297364_850551059(b0); genobjectfields_538104_839829468(m0, typ0, LOC24, tmp20); switch ((*b0).kind) { case ((Tnodekind294020) 85): { { NI LOC28; LOC28 = (NI)0; LOC28 = sonslen_297351_850551059(b0); if (!(LOC28 < ((NI) 2))) goto LA29; internalerror_198100_155036129((*b0).info, ((NimStringDesc*) &T839829468_204)); } LA29: ; { NI j_538436_839829468; NI HEX3Atmp_538494_839829468; NI LOC32; NI res_538497_839829468; j_538436_839829468 = (NI)0; HEX3Atmp_538494_839829468 = (NI)0; LOC32 = (NI)0; LOC32 = sonslen_297351_850551059(b0); HEX3Atmp_538494_839829468 = (NI)(LOC32 - ((NI) 2)); res_538497_839829468 = ((NI) 0); { while (1) { if (!(res_538497_839829468 <= HEX3Atmp_538494_839829468)) goto LA34; j_538436_839829468 = res_538497_839829468; { NI x0; NI64 LOC39; NI y0; NI64 LOC40; if (!((*(*b0).kindU.S6.sons->data[j_538436_839829468]).kind == ((Tnodekind294020) 44))) goto LA37; LOC39 = (NI64)0; LOC39 = getordvalue_322129_3876443242((*(*b0).kindU.S6.sons->data[j_538436_839829468]).kindU.S6.sons->data[((NI) 0)]); x0 = ((NI) (LOC39)); LOC40 = (NI64)0; LOC40 = getordvalue_322129_3876443242((*(*b0).kindU.S6.sons->data[j_538436_839829468]).kindU.S6.sons->data[((NI) 1)]); y0 = ((NI) (LOC40)); { while (1) { TY537238 LOC43; if (!(x0 <= y0)) goto LA42; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = tmp0; LOC43[1] = rope_180401_2381377266(((NI64) (x0))); LOC43[2] = tmp20; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC43, 3); x0 += ((NI) 1); } LA42: ; } } goto LA35; LA37: ; { TY537238 LOC45; NI64 LOC46; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = tmp0; LOC46 = (NI64)0; LOC46 = getordvalue_322129_3876443242((*b0).kindU.S6.sons->data[j_538436_839829468]); LOC45[1] = rope_180401_2381377266(LOC46); LOC45[2] = tmp20; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC45, 3); } LA35: ; res_538497_839829468 += ((NI) 1); } LA34: ; } } } break; case ((Tnodekind294020) 88): { TY537238 LOC48; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = tmp0; LOC48[1] = rope_180401_2381377266(L0); LOC48[2] = tmp20; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_140), LOC48, 3); } break; default: { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_205)); } break; } res_538504_839829468 += ((NI) 1); } LA23: ; } } } break; case ((Tnodekind294020) 3): { Tsym294834* field0; field0 = (*n0).kindU.S4.sym; { TY538475 LOC55; if (!((*field0).kindU.S4.bitsize == ((NI) 0))) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = expr0; LOC55[1] = gettypedesc_537673_839829468(m0, typ0); LOC55[2] = (*field0).loc.r; LOC55[3] = gentypeinfo_537941_839829468(m0, (*field0).typ); LOC55[4] = makecstring_193638_155036129((*(*field0).name).s); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_206), LOC55, 5); } LA53: ; } break; default: { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_207)); } break; } } N_NIMCALL(void, genobjectinfo_538508_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ttype294840* origtype0, Ropeobj180006* name0) { Ropeobj180006* tmp0; TY534811 LOC12; Ttype294840* t0; { if (!((*typ0).kind == ((Ttypekind294244) 17))) goto LA3; gentypeinfoaux_538027_839829468(m0, typ0, origtype0, name0); } goto LA1; LA3: ; { Ropeobj180006* LOC6; LOC6 = (Ropeobj180006*)0; LOC6 = rope_180277_2381377266(((NimStringDesc*) &T839829468_18)); gentypeinfoauxbase_537960_839829468(m0, typ0, origtype0, name0, LOC6); } LA1: ; tmp0 = getnimnode_537945_839829468(m0); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = isimportedcpptype_535478_839829468(typ0); if (!!(LOC9)) goto LA10; genobjectfields_538104_839829468(m0, typ0, (*typ0).n, tmp0); } LA10: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = name0; LOC12[1] = tmp0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_144), LOC12, 2); t0 = (*typ0).sons->data[((NI) 0)]; { while (1) { if (!!((t0 == NIM_NIL))) goto LA14; t0 = skiptypes_298099_850551059(t0, IL64(211106247215360)); (*t0).flags |= ((NU32)1)<<((((Ttypeflag294431) 5))%(sizeof(NU32)*8)); t0 = (*t0).sons->data[((NI) 0)]; } LA14: ; } } N_NIMCALL(void, gendeepcopyproc_540066_839829468)(Tcgen531027* m0, Tsym294834* s0, Ropeobj180006* result0) { TY534811 LOC1; genproc_534951_839829468(m0, s0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = result0; LOC1[1] = (*s0).loc.r; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_208), LOC1, 2); } N_NIMCALL(Ropeobj180006*, gentypeinfo_537941_839829468)(Tcgen531027* m0, Ttype294840* t_537944_839829468) { Ropeobj180006* result0; Ttype294840* origtype0; Ttype294840* t0; TY180507 LOC1; Tsym294834* owner0; Ttype294840* LOC12; Ropeobj180006* LOC66; Ropeobj180006* LOC67; Ropeobj180006* LOC68; { result0 = (Ropeobj180006*)0; origtype0 = t_537944_839829468; t0 = getuniquetype_530640_2036603609(t_537944_839829468); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rope_180401_2381377266(((NI64) ((*t0).Sup.id))); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_127), LOC1, 1); { NIM_BOOL LOC4; Ropeobj180006* LOC7; Ropeobj180006* LOC8; Ropeobj180006* LOC9; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_270862_2627731572((&(*m0).typeinfomarker), (*t0).Sup.id); if (!LOC4) goto LA5; LOC7 = (Ropeobj180006*)0; LOC7 = rope_180277_2381377266(((NimStringDesc*) &T839829468_128)); LOC8 = (Ropeobj180006*)0; LOC8 = HEX26_180418_2381377266(LOC7, result0); LOC9 = (Ropeobj180006*)0; LOC9 = rope_180277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_180418_2381377266(LOC8, LOC9); goto BeforeRet; } LA5: ; { while (1) { if (!((*t0).kind == ((Ttypekind294244) 13))) goto LA11; t0 = lastson_297377_850551059(t0); } LA11: ; } LOC12 = (Ttype294840*)0; LOC12 = skiptypes_298099_850551059(t0, IL64(211106247256320)); owner0 = getmodule_301123_2984716966((*LOC12).owner); { Tcgen531027* LOC17; Ropeobj180006* LOC18; Ropeobj180006* LOC19; Ropeobj180006* LOC20; TY534811 LOC21; NimStringDesc* LOC22; Ropeobj180006* LOC23; Ropeobj180006* LOC24; Ropeobj180006* LOC25; if (!!((owner0 == (*m0).module))) goto LA15; LOC17 = (Tcgen531027*)0; LOC17 = bmod_531201_3723162438(owner0); LOC18 = (Ropeobj180006*)0; LOC18 = gentypeinfo_537941_839829468(LOC17, t0); LOC19 = (Ropeobj180006*)0; LOC19 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_129)); LOC20 = (Ropeobj180006*)0; LOC20 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_130)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = result0; LOC22 = (NimStringDesc*)0; LOC22 = typetostring_322017_3876443242(t0, ((Tprefereddesc322011) 0)); LOC21[1] = rope_180277_2381377266(LOC22); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_131), LOC21, 2); LOC23 = (Ropeobj180006*)0; LOC23 = rope_180277_2381377266(((NimStringDesc*) &T839829468_128)); LOC24 = (Ropeobj180006*)0; LOC24 = HEX26_180418_2381377266(LOC23, result0); LOC25 = (Ropeobj180006*)0; LOC25 = rope_180277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_180418_2381377266(LOC24, LOC25); goto BeforeRet; } LA15: ; switch ((*t0).kind) { case ((Ttypekind294244) 3): case ((Ttypekind294244) 62): { result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_132)); } break; case ((Ttypekind294244) 26): case ((Ttypekind294244) 1): case ((Ttypekind294244) 2): case ((Ttypekind294244) 29): case ((Ttypekind294244) 28): case ((Ttypekind294244) 31) ... ((Ttypekind294244) 44): case ((Ttypekind294244) 23): { Ropeobj180006* LOC28; LOC28 = (Ropeobj180006*)0; LOC28 = rope_180277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_537960_839829468(m0, t0, t0, result0, LOC28); } break; case ((Ttypekind294244) 59): { { Ttype294840* LOC34; if (!!(((*t0).n == NIM_NIL))) goto LA32; LOC34 = (Ttype294840*)0; LOC34 = lastson_297377_850551059(t0); result0 = gentypeinfo_537941_839829468(m0, LOC34); } goto LA30; LA32: ; { NimStringDesc* LOC36; LOC36 = (NimStringDesc*)0; LOC36 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI294244))->Sup.len + 13); appendString(LOC36, ((NimStringDesc*) &T839829468_137)); appendString(LOC36, reprEnum((NI)(*t0).kind, (&NTI294244))); appendChar(LOC36, 41); internalerror_198113_155036129(LOC36); } LA30: ; } break; case ((Ttypekind294244) 25): { { Ropeobj180006* LOC42; if (!!(((*t0).callconv == ((Tcallingconvention294002) 8)))) goto LA40; LOC42 = (Ropeobj180006*)0; LOC42 = rope_180277_2381377266(((NimStringDesc*) &T839829468_132)); gentypeinfoauxbase_537960_839829468(m0, t0, t0, result0, LOC42); } goto LA38; LA40: ; { Ttype294840* LOC44; LOC44 = (Ttype294840*)0; LOC44 = fakeclosuretype_539010_839829468((*t0).owner); gentupleinfo_538551_839829468(m0, LOC44, result0); } LA38: ; } break; case ((Ttypekind294244) 24): case ((Ttypekind294244) 22): { gentypeinfoaux_538027_839829468(m0, t0, t0, result0); { Ropeobj180006* markerproc0; TY534811 LOC50; if (!(((Tgcmode171080) 4) <= gselectedgc_171133_2607990831)) goto LA48; markerproc0 = gentraverseproc_539632_839829468(m0, t0, ((Ttypeinforeason539016) 0)); memset((void*)LOC50, 0, sizeof(LOC50)); LOC50[0] = result0; LOC50[1] = markerproc0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_192), LOC50, 2); } LA48: ; } break; case ((Ttypekind294244) 21): case ((Ttypekind294244) 20): { gentypeinfoaux_538027_839829468(m0, t0, t0, result0); } break; case ((Ttypekind294244) 4): case ((Ttypekind294244) 16): { genarrayinfo_539005_839829468(m0, t0, result0); } break; case ((Ttypekind294244) 19): { gensetinfo_538867_839829468(m0, t0, result0); } break; case ((Ttypekind294244) 14): { genenuminfo_538599_839829468(m0, t0, result0); } break; case ((Ttypekind294244) 17): { genobjectinfo_538508_839829468(m0, t0, origtype0, result0); } break; case ((Ttypekind294244) 18): { gentupleinfo_538551_839829468(m0, t0, result0); } break; default: { NimStringDesc* LOC58; LOC58 = (NimStringDesc*)0; LOC58 = rawNewString(reprEnum((NI)(*t0).kind, (&NTI294244))->Sup.len + 13); appendString(LOC58, ((NimStringDesc*) &T839829468_137)); appendString(LOC58, reprEnum((NI)(*t0).kind, (&NTI294244))); appendChar(LOC58, 41); internalerror_198113_155036129(LOC58); } break; } { if (!!(((*t0).deepcopy == NIM_NIL))) goto LA61; gendeepcopyproc_540066_839829468(m0, (*t0).deepcopy, result0); } goto LA59; LA61: ; { if (!!(((*origtype0).deepcopy == NIM_NIL))) goto LA64; gendeepcopyproc_540066_839829468(m0, (*origtype0).deepcopy, result0); } goto LA59; LA64: ; LA59: ; LOC66 = (Ropeobj180006*)0; LOC66 = rope_180277_2381377266(((NimStringDesc*) &T839829468_128)); LOC67 = (Ropeobj180006*)0; LOC67 = HEX26_180418_2381377266(LOC66, result0); LOC68 = (Ropeobj180006*)0; LOC68 = rope_180277_2381377266(((NimStringDesc*) &T839829468_117)); result0 = HEX26_180418_2381377266(LOC67, LOC68); }BeforeRet: ; return result0; } N_NIMCALL(void, localdebuginfo_540449_839829468)(Tcproc531021* p0, Tsym294834* s0) { Ropeobj180006* a0; TY537235 LOC16; NimStringDesc* LOC17; { { if (!!(((163840 & (*p0).options) == 163840))) goto LA3; goto BeforeRet; } LA3: ; { Ttype294840* LOC7; LOC7 = (Ttype294840*)0; LOC7 = skiptypes_298099_850551059((*s0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC7).kind)&63U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; a0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_52), (*s0).loc.r); { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*s0).kind == ((Tsymkind294435) 3)); if (!(LOC12)) goto LA13; LOC12 = ccgintroducedptr_535611_839829468(s0); LA13: ; if (!LOC12) goto LA14; a0 = (*s0).loc.r; } LA14: ; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_180401_2381377266(((NI64) ((*p0).maxframelen))); LOC17 = (NimStringDesc*)0; LOC17 = nsuNormalize((*(*s0).name).s); LOC16[1] = makecstring_193638_155036129(LOC17); LOC16[2] = a0; LOC16[3] = gentypeinfo_537941_839829468((*p0).module, (*s0).loc.t); linef_534700_839829468(p0, ((Tcprocsection531011) 1), ((NimStringDesc*) &T839829468_126), LOC16, 4); (*p0).maxframelen += ((NI) 1); (*p0).blocks->data[(NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1))].framelen += ((NI) 1); }BeforeRet: ; } N_NIMCALL(void, assignlocalvar_540614_839829468)(Tcproc531021* p0, Tsym294834* s0) { Ropeobj180006* decl0; Ropeobj180006* LOC1; Ropeobj180006* LOC2; LOC1 = (Ropeobj180006*)0; LOC1 = localvardecl_540532_839829468(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = HEX26_180447_2381377266(LOC1, ((NimStringDesc*) &T839829468_125)); decl0 = HEX26_180447_2381377266(LOC2, tnl_178644_4151366050); line_534690_839829468(p0, ((Tcprocsection531011) 0), decl0); localdebuginfo_540449_839829468(p0, s0); } N_NIMCALL(void, initlocalvar_540398_839829468)(Tcproc531021* p0, Tsym294834* v0, NIM_BOOL immediateasgn0) { { if (!!((((*v0).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0))) goto LA3; { if (!!(immediateasgn0)) goto LA7; constructloc_540388_839829468(p0, (&(*v0).loc), NIM_FALSE); } LA7: ; } LA3: ; } N_NIMCALL(void, fillresult_535865_839829468)(Tsym294834* param0) { TY535289 LOC1; Ropeobj180006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj180006*)0; LOC2 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_210), LOC1, 0); fillloc_534282_839829468((&(*param0).loc), ((Tlockind294808) 4), (*param0).typ, LOC2, ((Tstorageloc294812) 2)); { NIM_BOOL LOC5; Tctypekind531007 LOC6; LOC5 = (NIM_BOOL)0; LOC6 = (Tctypekind531007)0; LOC6 = mapreturntype_535447_839829468((*param0).typ); LOC5 = !((LOC6 == ((Tctypekind531007) 17))); if (!(LOC5)) goto LA7; LOC5 = isinvalidreturntype_535550_839829468((*param0).typ); LA7: ; if (!LOC5) goto LA8; (*param0).loc.flags |= ((NU16)1)<<((((Tlocflag294810) 0))%(sizeof(NU16)*8)); (*param0).loc.s = ((Tstorageloc294812) 0); } LA8: ; } N_NIMCALL(void, assignparam_540994_839829468)(Tcproc531021* p0, Tsym294834* s0) { localdebuginfo_540449_839829468(p0, s0); } N_NIMCALL(void, closuresetup_562158_839829468)(Tcproc531021* p0, Tsym294834* prc0) { Tnode294802* ls0; Tnode294802* LOC5; Tsym294834* env0; TY534811 LOC10; { { if (!!((((*(*prc0).typ).flags &(1U<<((NU)(((Ttypeflag294431) 11))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; LOC5 = (Tnode294802*)0; LOC5 = HEX5BHEX5D_295238_850551059((*prc0).ast, ((NI) 3)); ls0 = lastson_297364_850551059(LOC5); { if (!!(((*ls0).kind == ((Tnodekind294020) 3)))) goto LA8; internalerror_198100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_211)); } LA8: ; env0 = (*ls0).kindU.S4.sym; assignlocalvar_540614_839829468(p0, env0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_540188_839829468((&(*env0).loc)); LOC10[1] = gettypedesc_537673_839829468((*p0).module, (*env0).typ); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_212), LOC10, 2); }BeforeRet: ; } N_NIMCALL(Ropeobj180006*, initgcframe_540435_839829468)(Tcproc531021* p0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { TY180507 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).gcframetype; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_217), LOC5, 1); } LA3: ; return result0; } N_NIMCALL(Ropeobj180006*, initframe_562140_839829468)(Tcproc531021* p0, Ropeobj180006* procname0, Ropeobj180006* filename0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_218)); { Ropeobj180006* LOC6; TY537235 LOC7; if (!(((NI) 0) < (*p0).maxframelen)) goto LA4; LOC6 = (Ropeobj180006*)0; LOC6 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_219)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = procname0; LOC7[1] = filename0; LOC7[2] = rope_180401_2381377266(((NI64) ((*p0).maxframelen))); LOC7[3] = rope_180401_2381377266(((NI64) ((*p0).blocks->data[((NI) 0)].framelen))); result0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_220), LOC7, 4); } goto LA2; LA4: ; { TY534811 LOC9; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = procname0; LOC9[1] = filename0; result0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_221), LOC9, 2); } LA2: ; return result0; } N_NIMCALL(void, appcg_534648_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, args0, args0Len0); add_180482_2381377266(LOC1, LOC2); } N_NIMCALL(Ropeobj180006*, deinitgcframe_540441_839829468)(Tcproc531021* p0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { TY535289 LOC5; if (!(((NI) 0) < ((NI) ((*p0).gcframeid)))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_225), LOC5, 0); } LA3: ; return result0; } N_NIMCALL(Ropeobj180006*, deinitframe_562150_839829468)(Tcproc531021* p0) { Ropeobj180006* result0; TY535289 LOC1; result0 = (Ropeobj180006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_226), LOC1, 0); return result0; } N_NIMCALL(void, genprocaux_562284_839829468)(Tcgen531027* m0, Tsym294834* prc0) { Tcproc531021* p0; Ropeobj180006* header0; Ropeobj180006* returnstmt0; Tnode294802* LOC51; Ropeobj180006* generatedproc0; p0 = newproc_531206_3723162438(prc0, m0); header0 = genprocheader_537867_839829468(m0, prc0); returnstmt0 = NIM_NIL; { NIM_BOOL LOC3; Tsym294834* res0; LOC3 = (NIM_BOOL)0; LOC3 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0)); if (!(LOC3)) goto LA4; LOC3 = !(((*(*prc0).typ).sons->data[((NI) 0)] == NIM_NIL)); LA4: ; if (!LOC3) goto LA5; { NI LOC9; LOC9 = (NI)0; LOC9 = len_295081_850551059((*prc0).ast); if (!(LOC9 <= ((NI) 7))) goto LA10; internalerror_198100_155036129((*prc0).info, ((NimStringDesc*) &T839829468_120)); } LA10: ; res0 = (*(*(*prc0).ast).kindU.S6.sons->data[((NI) 7)]).kindU.S4.sym; { NIM_BOOL LOC14; TY180507 LOC34; LOC14 = (NIM_BOOL)0; LOC14 = isinvalidreturntype_535550_839829468((*(*prc0).typ).sons->data[((NI) 0)]); if (!!(LOC14)) goto LA15; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)) goto LA19; (*res0).flags |= ((NU32)1)<<((((Tsymflag294184) 12))%(sizeof(NU32)*8)); } LA19: ; { NIM_BOOL LOC23; NIM_BOOL LOC24; NIM_BOOL LOC26; Tnode294802* val0; Tnode294802* LOC29; Ropeobj180006* decl0; Tloc294816 a0; TY534811 LOC32; LOC23 = (NIM_BOOL)0; LOC24 = (NIM_BOOL)0; LOC24 = (((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0); if (!(LOC24)) goto LA25; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA27: ; LOC24 = LOC26; LA25: ; LOC23 = LOC24; if (!(LOC23)) goto LA28; LOC29 = (Tnode294802*)0; LOC29 = getbody_337226_1724185294(prc0); val0 = easyresultasgn_562191_839829468(LOC29); LOC23 = !((val0 == NIM_NIL)); LA28: ; if (!LOC23) goto LA30; decl0 = localvardecl_540532_839829468(p0, res0); memset((void*)(&a0), 0, sizeof(a0)); initlocexprsingleuse_541289_839829468(p0, val0, (&a0)); memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = decl0; LOC32[1] = rdloc_540188_839829468((&a0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC32, 2); } goto LA21; LA30: ; { assignlocalvar_540614_839829468(p0, res0); initlocalvar_540398_839829468(p0, res0, NIM_FALSE); } LA21: ; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_540188_839829468((&(*res0).loc)); returnstmt0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_209), LOC34, 1); } goto LA12; LA15: ; { fillresult_535865_839829468(res0); assignparam_540994_839829468(p0, res0); { Ttype294840* LOC38; LOC38 = (Ttype294840*)0; LOC38 = skiptypes_298099_850551059((*res0).typ, IL64(211106232576256)); if (!((*LOC38).kind == ((Ttypekind294244) 16))) goto LA39; (*res0).loc.s = ((Tstorageloc294812) 0); } LA39: ; } LA12: ; } LA5: ; { NI i_562627_839829468; NI HEX3Atmp_562743_839829468; NI LOC42; NI res_562746_839829468; i_562627_839829468 = (NI)0; HEX3Atmp_562743_839829468 = (NI)0; LOC42 = (NI)0; LOC42 = sonslen_297351_850551059((*(*prc0).typ).n); HEX3Atmp_562743_839829468 = (NI)(LOC42 - ((NI) 1)); res_562746_839829468 = ((NI) 1); { while (1) { if (!(res_562746_839829468 <= HEX3Atmp_562743_839829468)) goto LA44; i_562627_839829468 = res_562746_839829468; { Tsym294834* param0; param0 = (*(*(*(*prc0).typ).n).kindU.S6.sons->data[i_562627_839829468]).kindU.S4.sym; { NIM_BOOL LOC48; LOC48 = (NIM_BOOL)0; LOC48 = iscompiletimeonly_330706_3876443242((*param0).typ); if (!LOC48) goto LA49; goto LA45; } LA49: ; assignparam_540994_839829468(p0, param0); } LA45: ; res_562746_839829468 += ((NI) 1); } LA44: ; } } closuresetup_562158_839829468(p0, prc0); LOC51 = (Tnode294802*)0; LOC51 = getbody_337226_1724185294(prc0); genstmts_541244_839829468(p0, LOC51); generatedproc0 = (Ropeobj180006*)0; { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 14))&31U)))!=0)) goto LA54; { if (!((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 6))&7U)))!=0)) goto LA58; header0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA58: ; } LA54: ; { TY537235 LOC68; Ropeobj180006** LOC69; Ropeobj180006** LOC70; Ropeobj180006** LOC71; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0)) goto LA62; { if (!((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 6))&7U)))!=0)) goto LA66; header0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_214), header0); } LA66: ; memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = header0; LOC69 = (Ropeobj180006**)0; LOC69 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); LOC68[1] = (*LOC69); LOC70 = (Ropeobj180006**)0; LOC70 = s_531179_3723162438(p0, ((Tcprocsection531011) 1)); LOC68[2] = (*LOC70); LOC71 = (Ropeobj180006**)0; LOC71 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); LOC68[3] = (*LOC71); generatedproc0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_215), LOC68, 4); } goto LA60; LA62: ; { TY180507 LOC73; Ropeobj180006* LOC74; Ropeobj180006** LOC93; Ropeobj180006** LOC94; Ropeobj180006* LOC101; TY535289 LOC107; Ropeobj180006* LOC108; memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = header0; generatedproc0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_216), LOC73, 1); LOC74 = (Ropeobj180006*)0; LOC74 = initgcframe_540435_839829468(p0); add_180482_2381377266(&generatedproc0, LOC74); { Ropeobj180006** LOC79; Ropeobj180006* procname0; Ropeobj180006* LOC80; Ropeobj180006* LOC81; if (!(((*prc0).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0)) goto LA77; LOC79 = (Ropeobj180006**)0; LOC79 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); add_180482_2381377266(&generatedproc0, (*LOC79)); procname0 = makecstring_193638_155036129((*(*prc0).name).s); LOC80 = (Ropeobj180006*)0; LOC80 = quotedfilename_198818_155036129((*prc0).info); LOC81 = (Ropeobj180006*)0; LOC81 = initframe_562140_839829468(p0, procname0, LOC80); add_180482_2381377266(&generatedproc0, LOC81); } goto LA75; LA77: ; { Ropeobj180006** LOC83; LOC83 = (Ropeobj180006**)0; LOC83 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); add_180482_2381377266(&generatedproc0, (*LOC83)); } LA75: ; { TY535289 LOC88; if (!(((*prc0).options &(1U<<((NU)(((Toption171009) 19))&31U)))!=0)) goto LA86; memset((void*)LOC88, 0, sizeof(LOC88)); appcg_534648_839829468(p0, ((Tcprocsection531011) 1), ((NimStringDesc*) &T839829468_222), LOC88, 0); } LA86: ; { if (!(*p0).beforeretneeded) goto LA91; add_180487_2381377266(&generatedproc0, ((NimStringDesc*) &T839829468_223)); } LA91: ; LOC93 = (Ropeobj180006**)0; LOC93 = s_531179_3723162438(p0, ((Tcprocsection531011) 1)); add_180482_2381377266(&generatedproc0, (*LOC93)); LOC94 = (Ropeobj180006**)0; LOC94 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(&generatedproc0, (*LOC94)); { TY535289 LOC99; Ropeobj180006* LOC100; if (!(*p0).beforeretneeded) goto LA97; memset((void*)LOC99, 0, sizeof(LOC99)); LOC100 = (Ropeobj180006*)0; LOC100 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_224), LOC99, 0); add_180482_2381377266(&generatedproc0, LOC100); } LA97: ; LOC101 = (Ropeobj180006*)0; LOC101 = deinitgcframe_540441_839829468(p0); add_180482_2381377266(&generatedproc0, LOC101); { Ropeobj180006* LOC106; if (!(((*prc0).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0)) goto LA104; LOC106 = (Ropeobj180006*)0; LOC106 = deinitframe_562150_839829468(p0); add_180482_2381377266(&generatedproc0, LOC106); } LA104: ; add_180482_2381377266(&generatedproc0, returnstmt0); memset((void*)LOC107, 0, sizeof(LOC107)); LOC108 = (Ropeobj180006*)0; LOC108 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_227), LOC107, 0); add_180482_2381377266(&generatedproc0, LOC108); } LA60: ; add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 10))- 0], generatedproc0); } N_NIMCALL(Tcgen531027*, findpendingmodule_534241_839829468)(Tcgen531027* m0, Tsym294834* s0) { Tcgen531027* result0; Tsym294834* ms0; result0 = (Tcgen531027*)0; ms0 = getmodule_301123_2984716966(s0); result0 = gmodules_531170_3723162438->data[(*ms0).position]; return result0; } N_NIMCALL(NIM_BOOL, isgetprocaddr_561443_839829468)(Tlib294820* lib0) { NIM_BOOL result0; Tnode294802* n0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; n0 = (*lib0).path; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*n0).kind == ((Tnodekind294020) 27) || (*n0).kind == ((Tnodekind294020) 29) || (*n0).kind == ((Tnodekind294020) 30) || (*n0).kind == ((Tnodekind294020) 31) || (*n0).kind == ((Tnodekind294020) 26) || (*n0).kind == ((Tnodekind294020) 28) || (*n0).kind == ((Tnodekind294020) 32)); if (!(LOC2)) goto LA3; LOC2 = !(((*n0).typ == NIM_NIL)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((100663296 &((NU64)1<<((NU)((*(*n0).typ).kind)&63U)))!=0); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, initlocexpr_541283_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* result0) { initloc_534273_839829468(result0, ((Tlockind294808) 0), (*e0).typ, ((Tstorageloc294812) 0)); expr_541248_839829468(p0, e0, result0); } N_NIMCALL(void, loaddynamiclib_561481_839829468)(Tcgen531027* m0, Tlib294820* lib0) { { Ropeobj180006* tmp0; TY180507 LOC5; if (!!((*lib0).generated)) goto LA3; (*lib0).generated = NIM_TRUE; tmp0 = gettempname_535598_839829468(m0); asgnRefNoCycle((void**) (&(*lib0).name), tmp0); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = tmp0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_228), LOC5, 1); { TY136002* s0; Ropeobj180006* loadlib0; TY534811 LOC18; if (!((*(*lib0).path).kind >= ((Tnodekind294020) 20) && (*(*lib0).path).kind <= ((Tnodekind294020) 22))) goto LA8; s0 = (TY136002*) newSeq((&NTI136002), 0); libcandidates_172605_2607990831((*(*lib0).path).kindU.S3.strval, (&s0)); rawmessage_196612_155036129(((Tmsgkind193002) 286), (*(*lib0).path).kindU.S3.strval); loadlib0 = NIM_NIL; { NI i_561847_839829468; NI HEX3Atmp_561902_839829468; NI res_561905_839829468; i_561847_839829468 = (NI)0; HEX3Atmp_561902_839829468 = (NI)0; HEX3Atmp_561902_839829468 = (s0 ? (s0->Sup.len-1) : -1); res_561905_839829468 = ((NI) 0); { while (1) { TY534811 LOC17; if (!(res_561905_839829468 <= HEX3Atmp_561902_839829468)) goto LA12; i_561847_839829468 = res_561905_839829468; (*m0).labels += ((NI) 1); { if (!(((NI) 0) < i_561847_839829468)) goto LA15; add_180487_2381377266(&loadlib0, ((NimStringDesc*) &T839829468_229)); } LA15: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = getstrlit_551468_839829468(m0, s0->data[i_561847_839829468]); appcg_534632_839829468(m0, &loadlib0, ((NimStringDesc*) &T839829468_230), LOC17, 2); res_561905_839829468 += ((NI) 1); } LA12: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = loadlib0; LOC18[1] = getstrlit_551468_839829468(m0, (*(*lib0).path).kindU.S3.strval); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 16))- 0], ((NimStringDesc*) &T839829468_231), LOC18, 2); } goto LA6; LA8: ; { Tcproc531021* p0; Tloc294816 dest0; Ropeobj180006** LOC20; Ropeobj180006** LOC21; Ropeobj180006** LOC22; TY534811 LOC23; p0 = newproc_531206_3723162438(NIM_NIL, m0); (*p0).options = ((*p0).options & ~ 163840); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_541283_839829468(p0, (*lib0).path, (&dest0)); LOC20 = (Ropeobj180006**)0; LOC20 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], (*LOC20)); LOC21 = (Ropeobj180006**)0; LOC21 = s_531179_3723162438(p0, ((Tcprocsection531011) 1)); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 16))- 0], (*LOC21)); LOC22 = (Ropeobj180006**)0; LOC22 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 16))- 0], (*LOC22)); memset((void*)LOC23, 0, sizeof(LOC23)); LOC23[0] = tmp0; LOC23[1] = rdloc_540188_839829468((&dest0)); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 16))- 0], ((NimStringDesc*) &T839829468_232), LOC23, 2); } LA6: ; } LA3: ; { if (!((*lib0).name == NIM_NIL)) goto LA26; internalerror_198113_155036129(((NimStringDesc*) &T839829468_233)); } LA26: ; } N_NIMCALL(Ropeobj180006*, mangledynlibproc_540816_839829468)(Tsym294834* sym0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 16))&31U)))!=0)) goto LA3; result0 = rope_180277_2381377266((*(*sym0).name).s); } goto LA1; LA3: ; { TY180507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_180401_2381377266(((NI64) ((*sym0).Sup.id))); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_234), LOC6, 1); } LA1: ; return result0; } N_NIMCALL(void, symindynamiclib_561929_839829468)(Tcgen531027* m0, Tsym294834* sym0) { Tlib294820* lib0; NIM_BOOL iscall0; Ropeobj180006* extname0; Ropeobj180006* tmp0; TY534811 LOC43; lib0 = (*sym0).annex; iscall0 = isgetprocaddr_561443_839829468(lib0); extname0 = (*sym0).loc.r; { if (!!(iscall0)) goto LA3; loaddynamiclib_561481_839829468(m0, lib0); } LA3: ; tmp0 = mangledynlibproc_540816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); (*m0).labels += ((NI) 2); { Tnode294802* n0; Tloc294816 a0; Tnode294802* LOC9; Ropeobj180006* params0; Ropeobj180006* LOC10; Ropeobj180006* load0; TY537235 LOC17; NimStringDesc* LOC18; Tnode294802* last0; NimStringDesc* idx0; if (!iscall0) goto LA7; n0 = (*lib0).path; memset((void*)(&a0), 0, sizeof(a0)); LOC9 = (Tnode294802*)0; LOC9 = HEX5BHEX5D_295238_850551059(n0, ((NI) 0)); initlocexpr_541283_839829468((*m0).initproc, LOC9, (&a0)); LOC10 = (Ropeobj180006*)0; LOC10 = rdloc_540188_839829468((&a0)); params0 = HEX26_180447_2381377266(LOC10, ((NimStringDesc*) &T839829468_118)); { NI i_561964_839829468; NI HEX3Atmp_562025_839829468; NI LOC12; NI res_562028_839829468; i_561964_839829468 = (NI)0; HEX3Atmp_562025_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = len_295081_850551059(n0); HEX3Atmp_562025_839829468 = (NI)(LOC12 - ((NI) 2)); res_562028_839829468 = ((NI) 1); { while (1) { Tnode294802* LOC15; Ropeobj180006* LOC16; if (!(res_562028_839829468 <= HEX3Atmp_562025_839829468)) goto LA14; i_561964_839829468 = res_562028_839829468; LOC15 = (Tnode294802*)0; LOC15 = HEX5BHEX5D_295238_850551059(n0, i_561964_839829468); initlocexpr_541283_839829468((*m0).initproc, LOC15, (&a0)); LOC16 = (Ropeobj180006*)0; LOC16 = rdloc_540188_839829468((&a0)); add_180482_2381377266(&params0, LOC16); add_180487_2381377266(&params0, ((NimStringDesc*) &T839829468_110)); res_562028_839829468 += ((NI) 1); } LA14: ; } } memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = tmp0; LOC17[1] = gettypedesc_537673_839829468(m0, (*sym0).typ); LOC17[2] = params0; LOC18 = (NimStringDesc*)0; LOC18 = HEX24_180856_2381377266(extname0); LOC17[3] = makecstring_193638_155036129(LOC18); load0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_235), LOC17, 4); last0 = lastson_297364_850551059(n0); { if (!((*last0).kind == ((Tnodekind294020) 58))) goto LA21; last0 = (*last0).kindU.S6.sons->data[((NI) 1)]; } LA21: ; { NimStringDesc* LOC27; if (!!(((*last0).kind == ((Tnodekind294020) 20)))) goto LA25; LOC27 = (NimStringDesc*)0; LOC27 = HEX24_198185_1689653243(T839829468_236); internalerror_198113_155036129(LOC27); } LA25: ; idx0 = (*last0).kindU.S3.strval; { Ropeobj180006** LOC32; if (!((idx0 ? idx0->Sup.len : 0) == ((NI) 0))) goto LA30; LOC32 = (Ropeobj180006**)0; LOC32 = s_531179_3723162438((*m0).initproc, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC32, load0); } goto LA28; LA30: ; { NIM_BOOL LOC34; LOC34 = (NIM_BOOL)0; LOC34 = ((idx0 ? idx0->Sup.len : 0) == ((NI) 1)); if (!(LOC34)) goto LA35; LOC34 = (((NU8)(idx0->data[((NI) 0)])) >= ((NU8)(48)) && ((NU8)(idx0->data[((NI) 0)])) <= ((NU8)(57))); LA35: ; if (!LOC34) goto LA36; add_180482_2381377266(&(*m0).extensionloaders[(((NU8)(idx0->data[((NI) 0)])))- 48], load0); } goto LA28; LA36: ; { NimStringDesc* LOC39; LOC39 = (NimStringDesc*)0; LOC39 = rawNewString(idx0->Sup.len + 13); appendString(LOC39, ((NimStringDesc*) &T839829468_237)); appendString(LOC39, idx0); internalerror_198100_155036129((*sym0).info, LOC39); } LA28: ; } goto LA5; LA7: ; { TY537235 LOC41; NimStringDesc* LOC42; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = gettypedesc_537673_839829468(m0, (*sym0).typ); LOC41[2] = (*lib0).name; LOC42 = (NimStringDesc*)0; LOC42 = HEX24_180856_2381377266(extname0); LOC41[3] = makecstring_193638_155036129(LOC42); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 16))- 0], ((NimStringDesc*) &T839829468_238), LOC41, 4); } LA5: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*sym0).loc.r; LOC43[1] = gettypedesc_537673_839829468(m0, (*sym0).loc.t); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_239), LOC43, 2); } N_NIMCALL(void, symindynamiclibpartial_562071_839829468)(Tcgen531027* m0, Tsym294834* sym0) { asgnRefNoCycle((void**) (&(*sym0).loc.r), mangledynlibproc_540816_839829468(sym0)); asgnRefNoCycle((void**) (&(*(*sym0).typ).sym), NIM_NIL); } N_NIMCALL(void, genprocnoforward_562906_839829468)(Tcgen531027* m0, Tsym294834* prc0) { { fillprocloc_541201_839829468(prc0); useheader_534369_839829468(m0, prc0); { Ropeobj180006* LOC5; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 7))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = cgsym_534403_839829468(m0, (*(*prc0).name).s); goto BeforeRet; } LA3: ; genprocprototype_541254_839829468(m0, prc0); { if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)) goto LA8; } goto LA6; LA8: ; { if (!((*(*prc0).typ).callconv == ((Tcallingconvention294002) 5))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = containsorincl_270862_2627731572((&(*m0).declaredthings), (*prc0).Sup.id); if (!!(LOC15)) goto LA16; genprocaux_562284_839829468(m0, prc0); } LA16: ; } goto LA6; LA11: ; { Tcgen531027* q0; if (!(((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 4))&15U)))!=0)) goto LA19; q0 = findpendingmodule_534241_839829468(m0, prc0); { NIM_BOOL LOC23; NIM_BOOL LOC25; LOC23 = (NIM_BOOL)0; LOC23 = !((q0 == NIM_NIL)); if (!(LOC23)) goto LA24; LOC25 = (NIM_BOOL)0; LOC25 = containsorincl_270862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC23 = !(LOC25); LA24: ; if (!LOC23) goto LA26; symindynamiclib_561929_839829468(q0, prc0); } goto LA21; LA26: ; { symindynamiclibpartial_562071_839829468(m0, prc0); } LA21: ; } goto LA6; LA19: ; { Tcgen531027* q0; if (!!((((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0))) goto LA30; q0 = findpendingmodule_534241_839829468(m0, prc0); { NIM_BOOL LOC34; NIM_BOOL LOC36; LOC34 = (NIM_BOOL)0; LOC34 = !((q0 == NIM_NIL)); if (!(LOC34)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = containsorincl_270862_2627731572((&(*q0).declaredthings), (*prc0).Sup.id); LOC34 = !(LOC36); LA35: ; if (!LOC34) goto LA37; genprocaux_562284_839829468(q0, prc0); } LA37: ; } goto LA6; LA30: ; LA6: ; }BeforeRet: ; } N_NIMCALL(void, genproc_534951_839829468)(Tcgen531027* m0, Tsym294834* prc0) { { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = (((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 26))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isactivated_563431_839829468(prc0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; goto BeforeRet; } LA6: ; fillprocloc_541201_839829468(prc0); { if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 4))&31U)))!=0)) goto LA10; addforwardedproc_534203_839829468(m0, prc0); } goto LA8; LA10: ; { genprocnoforward_562906_839829468(m0, prc0); { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = ((65600 & (*prc0).flags) == 64); if (!(LOC16)) goto LA17; LOC16 = !((generatedheader_534201_839829468 == NIM_NIL)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)); LA18: ; if (!LOC15) goto LA19; genprocprototype_541254_839829468(generatedheader_534201_839829468, prc0); { if (!((*(*prc0).typ).callconv == ((Tcallingconvention294002) 5))) goto LA23; { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = containsorincl_270862_2627731572((&(*generatedheader_534201_839829468).declaredthings), (*prc0).Sup.id); if (!!(LOC27)) goto LA28; genprocaux_562284_839829468(generatedheader_534201_839829468, prc0); } LA28: ; } LA23: ; } LA19: ; } LA8: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, emulatedthreadvars_534949_839829468)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((71303168 & ~ gglobaloptions_171130_2607990831)==0); return result0; } N_NIMCALL(void, declarethreadvar_540676_839829468)(Tcgen531027* m0, Tsym294834* s0, NIM_BOOL isextern0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_534949_839829468(); if (!LOC3) goto LA4; { NIM_BOOL LOC8; TY534811 LOC11; LOC8 = (NIM_BOOL)0; LOC8 = containsorincl_270862_2627731572((&nimtvdeclared_540675_839829468), (*s0).Sup.id); if (!!(LOC8)) goto LA9; nimtvdeps_540674_839829468 = (Ttypeseq294836*) incrSeqV2(&(nimtvdeps_540674_839829468)->Sup, sizeof(Ttype294840*)); asgnRefNoCycle((void**) (&nimtvdeps_540674_839829468->data[nimtvdeps_540674_839829468->Sup.len]), (*s0).loc.t); ++nimtvdeps_540674_839829468->Sup.len; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_537673_839829468(m0, (*s0).loc.t); LOC11[1] = (*s0).loc.r; addf_181205_2381377266(&nimtv_540656_839829468, ((NimStringDesc*) &T839829468_54), LOC11, 2); } LA9: ; } goto LA1; LA4: ; { Ropeobj180006* LOC21; TY180507 LOC22; { if (!isextern0) goto LA15; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_240)); } LA15: ; { if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 22))&63U)))!=0)) goto LA19; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_241)); } LA19: ; LOC21 = (Ropeobj180006*)0; LOC21 = gettypedesc_537673_839829468(m0, (*s0).loc.t); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], LOC21); memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = (*s0).loc.r; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC22, 1); } LA1: ; } N_NIMCALL(void, genvarprototypeaux_546254_839829468)(Tcgen531027* m0, Tsym294834* sym0) { Ropeobj180006* LOC1; { useheader_534369_839829468(m0, sym0); LOC1 = (Ropeobj180006*)0; LOC1 = manglename_535205_839829468(sym0); fillloc_534282_839829468((&(*sym0).loc), ((Tlockind294808) 3), (*sym0).typ, LOC1, ((Tstorageloc294812) 3)); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0); if (LOC4) goto LA5; LOC4 = containsorincl_270862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LA5: ; if (!LOC4) goto LA6; goto BeforeRet; } LA6: ; { if (!!(((*(*sym0).owner).Sup.id == (*(*m0).module).Sup.id))) goto LA10; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 22))&31U)))!=0)) goto LA14; declarethreadvar_540676_839829468(m0, sym0, NIM_TRUE); } goto LA12; LA14: ; { Ropeobj180006* LOC17; TY180507 LOC30; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_240)); LOC17 = (Ropeobj180006*)0; LOC17 = gettypedesc_537673_839829468(m0, (*sym0).loc.t); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], LOC17); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 4))&15U)))!=0)) goto LA20; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_53)); } LA20: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 8))&31U)))!=0)) goto LA24; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_121)); } LA24: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 7))&31U)))!=0)) goto LA28; add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_122)); } LA28: ; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = (*sym0).loc.r; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_242), LOC30, 1); } LA12: ; } LA10: ; }BeforeRet: ; } N_NIMCALL(void, genvarprototype_541236_839829468)(Tcgen531027* m0, Tsym294834* sym0) { genvarprototypeaux_546254_839829468(m0, sym0); } N_NIMCALL(Ropeobj180006*, cgsym_534403_839829468)(Tcgen531027* m0, NimStringDesc* name0) { Ropeobj180006* result0; Tsym294834* sym0; result0 = (Ropeobj180006*)0; sym0 = getcompilerproc_340748_3937434831(name0); { if (!!((sym0 == NIM_NIL))) goto LA3; switch ((*sym0).kind) { case ((Tsymkind294435) 12): case ((Tsymkind294435) 13): case ((Tsymkind294435) 15): case ((Tsymkind294435) 14): { genproc_534951_839829468(m0, sym0); } break; case ((Tsymkind294435) 8): case ((Tsymkind294435) 11): case ((Tsymkind294435) 9): { genvarprototype_541236_839829468(m0, sym0); } break; case ((Tsymkind294435) 7): { Ropeobj180006* LOC8; LOC8 = (Ropeobj180006*)0; LOC8 = gettypedesc_537673_839829468(m0, (*sym0).typ); } break; default: { NimStringDesc* LOC10; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(name0->Sup.len + reprEnum((NI)(*sym0).kind, (&NTI294435))->Sup.len + 9); appendString(LOC10, ((NimStringDesc*) &T839829468_243)); appendString(LOC10, name0); appendString(LOC10, ((NimStringDesc*) &T839829468_244)); appendString(LOC10, reprEnum((NI)(*sym0).kind, (&NTI294435))); internalerror_198113_155036129(LOC10); } break; } } goto LA1; LA3: ; { rawmessage_196612_155036129(((Tmsgkind193002) 68), name0); } LA1: ; result0 = (*sym0).loc.r; return result0; } N_NIMCALL(Ropeobj180006*, ropecg_534407_839829468)(Tcgen531027* m0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006* result0; NI i0; NI length0; NI num0; result0 = (Ropeobj180006*)0; i0 = ((NI) 0); length0 = (frmt0 ? frmt0->Sup.len : 0); result0 = NIM_NIL; num0 = ((NI) 0); { while (1) { NI start0; if (!(i0 < length0)) goto LA2; { if (!((NU8)(frmt0->data[i0]) == (NU8)(36))) goto LA5; i0 += ((NI) 1); switch (((NU8)(frmt0->data[i0]))) { case 36: { add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_19)); i0 += ((NI) 1); } break; case 35: { i0 += ((NI) 1); add_180482_2381377266(&result0, args0[num0]); num0 += ((NI) 1); } break; case 48 ... 57: { NI j0; j0 = ((NI) 0); { while (1) { j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = (length0 <= i0); if (LOC14) goto LA15; LOC14 = !((((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))); LA15: ; if (!LOC14) goto LA16; goto LA10; } LA16: ; } } LA10: ; num0 = j0; { NimStringDesc* LOC22; NimStringDesc* LOC23; if (!((NI)((args0Len0-1) + ((NI) 1)) < j0)) goto LA20; LOC22 = (NimStringDesc*)0; LOC23 = (NimStringDesc*)0; LOC23 = nimIntToStr(j0); LOC22 = rawNewString(LOC23->Sup.len + 30); appendString(LOC22, ((NimStringDesc*) &T839829468_20)); appendString(LOC22, LOC23); internalerror_198113_155036129(LOC22); } LA20: ; add_180482_2381377266(&result0, args0[(NI)(j0 - ((NI) 1))]); } break; case 110: { { if (!!(((goptions_171128_2607990831 &(1U<<((NU)(((Toption171009) 10))&31U)))!=0))) goto LA27; add_180482_2381377266(&result0, rnl_180903_2381377266); } LA27: ; i0 += ((NI) 1); } break; case 78: { add_180482_2381377266(&result0, rnl_180903_2381377266); i0 += ((NI) 1); } break; default: { NimStringDesc* LOC31; LOC31 = (NimStringDesc*)0; LOC31 = rawNewString(31); appendString(LOC31, ((NimStringDesc*) &T839829468_20)); appendChar(LOC31, frmt0->data[i0]); internalerror_198113_155036129(LOC31); } break; } } goto LA3; LA5: ; { NIM_BOOL LOC33; NI j0; NimStringDesc* ident0; Ropeobj180006* LOC39; LOC33 = (NIM_BOOL)0; LOC33 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC33)) goto LA34; LOC33 = (((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(97)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(122)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) >= ((NU8)(65)) && ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) <= ((NU8)(90)) || ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(95))); LA34: ; if (!LOC33) goto LA35; i0 += ((NI) 1); j0 = i0; { while (1) { if (!(((NU8)(frmt0->data[j0])) >= ((NU8)(97)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(122)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(65)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(90)) || ((NU8)(frmt0->data[j0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[j0])) <= ((NU8)(57)) || ((NU8)(frmt0->data[j0])) == ((NU8)(95)))) goto LA38; j0 += ((NI) 1); } LA38: ; } ident0 = copyStrLast(frmt0, i0, (NI)(j0 - ((NI) 1))); i0 = j0; LOC39 = (Ropeobj180006*)0; LOC39 = cgsym_534403_839829468(m0, ident0); add_180482_2381377266(&result0, LOC39); } goto LA3; LA35: ; { NIM_BOOL LOC41; NI j0; NimStringDesc* LOC47; Ropeobj180006* LOC48; LOC41 = (NIM_BOOL)0; LOC41 = ((NU8)(frmt0->data[i0]) == (NU8)(35)); if (!(LOC41)) goto LA42; LOC41 = ((NU8)(frmt0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(36)); LA42: ; if (!LOC41) goto LA43; i0 += ((NI) 2); j0 = ((NI) 0); { while (1) { if (!(((NU8)(frmt0->data[i0])) >= ((NU8)(48)) && ((NU8)(frmt0->data[i0])) <= ((NU8)(57)))) goto LA46; j0 = (NI)((NI)((NI)(j0 * ((NI) 10)) + ((NI) (((NU8)(frmt0->data[i0]))))) - ((NI) 48)); i0 += ((NI) 1); } LA46: ; } LOC47 = (NimStringDesc*)0; LOC47 = HEX24_180856_2381377266(args0[(NI)(j0 - ((NI) 1))]); LOC48 = (Ropeobj180006*)0; LOC48 = cgsym_534403_839829468(m0, LOC47); add_180482_2381377266(&result0, LOC48); } goto LA3; LA43: ; LA3: ; start0 = i0; { while (1) { if (!(i0 < length0)) goto LA50; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(36))); if (!(LOC53)) goto LA54; LOC53 = !(((NU8)(frmt0->data[i0]) == (NU8)(35))); LA54: ; if (!LOC53) goto LA55; i0 += ((NI) 1); } goto LA51; LA55: ; { goto LA49; } LA51: ; } LA50: ; } LA49: ; { NimStringDesc* LOC62; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA60; LOC62 = (NimStringDesc*)0; LOC62 = copyStrLast(frmt0, start0, (NI)(i0 - ((NI) 1))); add_180487_2381377266(&result0, LOC62); } LA60: ; } LA2: ; } return result0; } static N_INLINE(NIM_BOOL, crossescppboundary_562754_839829468)(Tcgen531027* m0, Tsym294834* sym0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; Tsym294834* LOC4; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); if (!(LOC2)) goto LA3; LOC4 = (Tsym294834*)0; LOC4 = getmodule_301123_2984716966(sym0); LOC2 = !((((*LOC4).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0)); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA5; LOC1 = !((gcmd_171132_2607990831 == ((Tcommands171076) 2))); LA5: ; result0 = LOC1; return result0; } N_NIMCALL(void, genprocprototype_541254_839829468)(Tcgen531027* m0, Tsym294834* sym0) { { useheader_534369_839829468(m0, sym0); { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 4))&15U)))!=0)) goto LA7; { NIM_BOOL LOC11; Tsym294834* LOC12; NIM_BOOL LOC14; TY534811 LOC17; Ropeobj180006* LOC18; LOC11 = (NIM_BOOL)0; LOC12 = (Tsym294834*)0; LOC12 = getmodule_301123_2984716966(sym0); LOC11 = !(((*LOC12).Sup.id == (*(*m0).module).Sup.id)); if (!(LOC11)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_270862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC11 = !(LOC14); LA13: ; if (!LOC11) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_537673_839829468(m0, (*sym0).loc.t); LOC17[1] = mangledynlibproc_540816_839829468(sym0); LOC18 = (Ropeobj180006*)0; LOC18 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_245), LOC17, 2); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], LOC18); } LA15: ; } goto LA5; LA7: ; { NIM_BOOL LOC20; Ropeobj180006* header0; TY180507 LOC47; Ropeobj180006* LOC48; LOC20 = (NIM_BOOL)0; LOC20 = containsorincl_270862_2627731572((&(*m0).declaredprotos), (*sym0).Sup.id); if (!!(LOC20)) goto LA21; header0 = genprocheader_537867_839829468(m0, sym0); { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 14))&31U)))!=0); if (!(LOC25)) goto LA26; LOC25 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 6))&7U)))!=0); LA26: ; if (!LOC25) goto LA27; header0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_213), header0); } LA27: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = !(((*(*sym0).typ).callconv == ((Tcallingconvention294002) 5))); if (!(LOC31)) goto LA32; LOC31 = crossescppboundary_562754_839829468(m0, sym0); LA32: ; if (!LOC31) goto LA33; header0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_246), header0); } LA33: ; { NIM_BOOL LOC37; LOC37 = (NIM_BOOL)0; LOC37 = (((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0); if (!(LOC37)) goto LA38; LOC37 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 7))&7U)))!=0); LA38: ; if (!LOC37) goto LA39; add_180487_2381377266(&header0, ((NimStringDesc*) &T839829468_247)); } LA39: ; { NIM_BOOL LOC43; LOC43 = (NIM_BOOL)0; LOC43 = (((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 14))&31U)))!=0); if (!(LOC43)) goto LA44; LOC43 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 7))&7U)))!=0); LA44: ; if (!LOC43) goto LA45; add_180487_2381377266(&header0, ((NimStringDesc*) &T839829468_248)); } LA45: ; memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = header0; LOC48 = (Ropeobj180006*)0; LOC48 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_191), LOC47, 1); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 7))- 0], LOC48); } goto LA5; LA21: ; LA5: ; }BeforeRet: ; } static N_INLINE(NIM_BOOL, usesnativegc_171177_2607990831)(void) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = (((Tgcmode171080) 5) <= gselectedgc_171133_2607990831); return result0; } N_NIMCALL(void, genrefassign_540311_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY534811 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc294812) 2)); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = usesnativegc_171177_2607990831(); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468(dest0); LOC8[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC8, 2); } goto LA1; LA6: ; { if (!((*dest0).s == ((Tstorageloc294812) 3))) goto LA10; { NIM_BOOL LOC14; TY534811 LOC17; LOC14 = (NIM_BOOL)0; LOC14 = canformacycle_322123_3876443242((*dest0).t); if (!LOC14) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_540204_839829468(dest0); LOC17[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_249), LOC17, 2); } goto LA12; LA15: ; { TY534811 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_540204_839829468(dest0); LOC19[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_250), LOC19, 2); } LA12: ; } goto LA1; LA10: ; { TY534811 LOC21; memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = addrloc_540204_839829468(dest0); LOC21[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_251), LOC21, 2); } LA1: ; } N_NIMCALL(void, optasgnloc_551789_839829468)(Tloc294816* a0, Ttype294840* t0, Ropeobj180006* field0, Tloc294816* Result) { Ropeobj180006* LOC1; Ropeobj180006* LOC2; (*Result).k = ((Tlockind294808) 5); (*Result).s = (*a0).s; unsureAsgnRef((void**) (&(*Result).t), t0); LOC1 = (Ropeobj180006*)0; LOC1 = rdloc_540188_839829468(a0); LOC2 = (Ropeobj180006*)0; LOC2 = HEX26_180447_2381377266(LOC1, ((NimStringDesc*) &T839829468_257)); unsureAsgnRef((void**) (&(*Result).r), HEX26_180418_2381377266(LOC2, field0)); } N_NIMCALL(void, genoptasgntuple_552001_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0) { Tassignmentflag540302Set newflags0; Ttype294840* t_552053_839829468; Ttype294840* LOC9; { if (!((*src0).s == ((Tstorageloc294812) 1))) goto LA3; newflags0 = (flags0 | 1); } goto LA1; LA3: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag294431) 6))&31U)))!=0)) goto LA6; newflags0 = (flags0 & ~ 1); } goto LA1; LA6: ; { newflags0 = flags0; } LA1: ; LOC9 = (Ttype294840*)0; LOC9 = skiptypes_298099_850551059((*dest0).t, IL64(211106232576256)); t_552053_839829468 = getuniquetype_530640_2036603609(LOC9); { NI i_552071_839829468; NI HEX3Atmp_552077_839829468; NI LOC11; NI res_552080_839829468; i_552071_839829468 = (NI)0; HEX3Atmp_552077_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = len_297339_850551059(t_552053_839829468); HEX3Atmp_552077_839829468 = (LOC11 - 1); res_552080_839829468 = ((NI) 0); { while (1) { Ttype294840* t0; Ropeobj180006* field0; TY180507 LOC14; Tloc294816 LOC15; Tloc294816 LOC16; if (!(res_552080_839829468 <= HEX3Atmp_552077_839829468)) goto LA13; i_552071_839829468 = res_552080_839829468; t0 = (*t_552053_839829468).sons->data[i_552071_839829468]; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_180401_2381377266(((NI64) (i_552071_839829468))); field0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_260), LOC14, 1); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_551789_839829468(dest0, t0, field0, (&LOC15)); memset((void*)(&LOC16), 0, sizeof(LOC16)); optasgnloc_551789_839829468(src0, t0, field0, (&LOC16)); genassignment_541264_839829468(p0, (&LOC15), (&LOC16), newflags0); res_552080_839829468 += ((NI) 1); } LA13: ; } } } N_NIMCALL(void, gengenericasgn_552167_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0) { { NIM_BOOL LOC3; Ttype294840* LOC5; LOC3 = (NIM_BOOL)0; LOC3 = !(((flags0 &(1U<<((NU)(((Tassignmentflag540302) 0))&7U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype294840*)0; LOC5 = skiptypes_298099_850551059((*dest0).t, IL64(211106242013440)); LOC3 = (((*LOC5).flags &(1U<<((NU)(((Ttypeflag294431) 6))&31U)))!=0); LA4: ; if (!LOC3) goto LA6; { NIM_BOOL LOC10; NIM_BOOL LOC12; TY537238 LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*dest0).s == ((Tstorageloc294812) 2)); if (LOC10) goto LA11; LOC12 = (NIM_BOOL)0; LOC12 = usesnativegc_171177_2607990831(); LOC10 = !(LOC12); LA11: ; if (!LOC10) goto LA13; usestringh_534345_839829468((*p0).module); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = addrloc_540204_839829468(dest0); LOC15[1] = addrloc_540204_839829468(src0); LOC15[2] = rdloc_540188_839829468(dest0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_261), LOC15, 3); } goto LA8; LA13: ; { TY537238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_540204_839829468(dest0); LOC17[1] = addrloc_540204_839829468(src0); LOC17[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_262), LOC17, 3); } LA8: ; } goto LA1; LA6: ; { TY537238 LOC19; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = addrloc_540204_839829468(dest0); LOC19[1] = addrloc_540204_839829468(src0); LOC19[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_263), LOC19, 3); } LA1: ; } N_NIMCALL(NI, asgncomplexity_551751_839829468)(Tnode294802* n0) { NI result0; result0 = (NI)0; { if (!!((n0 == NIM_NIL))) goto LA3; switch ((*n0).kind) { case ((Tnodekind294020) 3): { result0 = ((NI) 1); } break; case ((Tnodekind294020) 139): { result0 = ((NI) 100); } break; case ((Tnodekind294020) 138): { { Tnode294802* t_551768_839829468; t_551768_839829468 = (Tnode294802*)0; { NI i_551782_839829468; NI HEX3Atmp_551784_839829468; NI LOC10; NI res_551786_839829468; i_551782_839829468 = (NI)0; HEX3Atmp_551784_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = len_295081_850551059(n0); HEX3Atmp_551784_839829468 = (LOC10 - 1); res_551786_839829468 = ((NI) 0); { while (1) { NI LOC13; if (!(res_551786_839829468 <= HEX3Atmp_551784_839829468)) goto LA12; i_551782_839829468 = res_551786_839829468; t_551768_839829468 = (*n0).kindU.S6.sons->data[i_551782_839829468]; LOC13 = (NI)0; LOC13 = asgncomplexity_551751_839829468(t_551768_839829468); result0 += LOC13; res_551786_839829468 += ((NI) 1); } LA12: ; } } } } break; default: { } break; } } LA3: ; return result0; } N_NIMCALL(void, genoptasgnobject_552084_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0, Tnode294802* t0) { Tassignmentflag540302Set newflags0; { { if (!(t0 == NIM_NIL)) goto LA3; goto BeforeRet; } LA3: ; { if (!((*src0).s == ((Tstorageloc294812) 1))) goto LA7; newflags0 = (flags0 | 1); } goto LA5; LA7: ; { if (!(((*(*dest0).t).flags &(1U<<((NU)(((Ttypeflag294431) 6))&31U)))!=0)) goto LA10; newflags0 = (flags0 & ~ 1); } goto LA5; LA10: ; { newflags0 = flags0; } LA5: ; switch ((*t0).kind) { case ((Tnodekind294020) 3): { Tsym294834* field0; Tloc294816 LOC14; Tloc294816 LOC15; field0 = (*t0).kindU.S4.sym; memset((void*)(&LOC14), 0, sizeof(LOC14)); optasgnloc_551789_839829468(dest0, (*field0).typ, (*field0).loc.r, (&LOC14)); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_551789_839829468(src0, (*field0).typ, (*field0).loc.r, (&LOC15)); genassignment_541264_839829468(p0, (&LOC14), (&LOC15), newflags0); } break; case ((Tnodekind294020) 138): { { Tnode294802* child_552155_839829468; child_552155_839829468 = (Tnode294802*)0; { NI i_552160_839829468; NI HEX3Atmp_552162_839829468; NI LOC19; NI res_552164_839829468; i_552160_839829468 = (NI)0; HEX3Atmp_552162_839829468 = (NI)0; LOC19 = (NI)0; LOC19 = len_295081_850551059(t0); HEX3Atmp_552162_839829468 = (LOC19 - 1); res_552164_839829468 = ((NI) 0); { while (1) { if (!(res_552164_839829468 <= HEX3Atmp_552162_839829468)) goto LA21; i_552160_839829468 = res_552164_839829468; child_552155_839829468 = (*t0).kindU.S6.sons->data[i_552160_839829468]; genoptasgnobject_552084_839829468(p0, dest0, src0, newflags0, child_552155_839829468); res_552164_839829468 += ((NI) 1); } LA21: ; } } } } break; default: { } break; } }BeforeRet: ; } N_NIMCALL(void, genassignment_541264_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0, Tassignmentflag540302Set flags0) { Ttype294840* ty0; { { NIM_BOOL LOC3; TY534811 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = !(((*src0).t == NIM_NIL)); if (!(LOC3)) goto LA4; LOC3 = ((*(*src0).t).kind == ((Ttypekind294244) 21)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_540188_839829468(dest0); LOC7[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC7, 2); goto BeforeRet; } LA5: ; ty0 = skiptypes_298099_850551059((*dest0).t, IL64(211106233624832)); switch ((*ty0).kind) { case ((Ttypekind294244) 22): { genrefassign_540311_839829468(p0, dest0, src0, flags0); } break; case ((Ttypekind294244) 24): { { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = !(((flags0 &(1U<<((NU)(((Tassignmentflag540302) 0))&7U)))!=0)); if (!(LOC12)) goto LA13; LOC12 = !(((*src0).s == ((Tstorageloc294812) 1))); LA13: ; if (!LOC12) goto LA14; genrefassign_540311_839829468(p0, dest0, src0, flags0); } goto LA10; LA14: ; { TY537238 LOC17; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = addrloc_540204_839829468(dest0); LOC17[1] = rdloc_540188_839829468(src0); LOC17[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_252), LOC17, 3); } LA10: ; } break; case ((Ttypekind294244) 28): { { NIM_BOOL LOC21; LOC21 = (NIM_BOOL)0; LOC21 = !(((flags0 &(1U<<((NU)(((Tassignmentflag540302) 0))&7U)))!=0)); if (!(LOC21)) goto LA22; LOC21 = !(((*src0).s == ((Tstorageloc294812) 1))); LA22: ; if (!LOC21) goto LA23; genrefassign_540311_839829468(p0, dest0, src0, flags0); } goto LA19; LA23: ; { { NIM_BOOL LOC28; NIM_BOOL LOC30; TY534811 LOC33; LOC28 = (NIM_BOOL)0; LOC28 = ((*dest0).s == ((Tstorageloc294812) 2)); if (LOC28) goto LA29; LOC30 = (NIM_BOOL)0; LOC30 = usesnativegc_171177_2607990831(); LOC28 = !(LOC30); LA29: ; if (!LOC28) goto LA31; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_540188_839829468(dest0); LOC33[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_253), LOC33, 2); } goto LA26; LA31: ; { Tloc294816 tmp0; TY537238 LOC37; TY180507 LOC38; if (!((*dest0).s == ((Tstorageloc294812) 3))) goto LA35; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, ty0, (&tmp0), NIM_FALSE); memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_540188_839829468(dest0); LOC37[1] = rdloc_540188_839829468(src0); LOC37[2] = rdloc_540188_839829468((&tmp0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_254), LOC37, 3); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_540188_839829468((&tmp0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_255), LOC38, 1); } goto LA26; LA35: ; { TY534811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = addrloc_540204_839829468(dest0); LOC40[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_256), LOC40, 2); } LA26: ; } LA19: ; } break; case ((Ttypekind294244) 25): { { NIM_BOOL LOC44; Tloc294816 a0; Ropeobj180006* LOC47; Tloc294816 LOC48; Tloc294816 b0; Ropeobj180006* LOC49; Tloc294816 LOC50; TY534811 LOC51; LOC44 = (NIM_BOOL)0; LOC44 = needscomplexassignment_535511_839829468((*dest0).t); if (!LOC44) goto LA45; memset((void*)(&a0), 0, sizeof(a0)); LOC47 = (Ropeobj180006*)0; LOC47 = rope_180277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC48), 0, sizeof(LOC48)); optasgnloc_551789_839829468(dest0, (*dest0).t, LOC47, (&LOC48)); memcpy((void*)(&a0), (NIM_CONST void*)(&LOC48), sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); LOC49 = (Ropeobj180006*)0; LOC49 = rope_180277_2381377266(((NimStringDesc*) &T839829468_258)); memset((void*)(&LOC50), 0, sizeof(LOC50)); optasgnloc_551789_839829468(src0, (*dest0).t, LOC49, (&LOC50)); memcpy((void*)(&b0), (NIM_CONST void*)(&LOC50), sizeof(b0)); genrefassign_540311_839829468(p0, (&a0), (&b0), flags0); memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_540188_839829468(dest0); LOC51[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_259), LOC51, 2); } goto LA42; LA45: ; { TY534811 LOC53; memset((void*)LOC53, 0, sizeof(LOC53)); LOC53[0] = rdloc_540188_839829468(dest0); LOC53[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC53, 2); } LA42: ; } break; case ((Ttypekind294244) 18): { { NIM_BOOL LOC57; LOC57 = (NIM_BOOL)0; LOC57 = needscomplexassignment_535511_839829468((*dest0).t); if (!LOC57) goto LA58; { NI LOC62; LOC62 = (NI)0; LOC62 = len_297339_850551059((*dest0).t); if (!(LOC62 <= ((NI) 4))) goto LA63; genoptasgntuple_552001_839829468(p0, dest0, src0, flags0); } goto LA60; LA63: ; { gengenericasgn_552167_839829468(p0, dest0, src0, flags0); } LA60: ; } goto LA55; LA58: ; { TY534811 LOC67; memset((void*)LOC67, 0, sizeof(LOC67)); LOC67[0] = rdloc_540188_839829468(dest0); LOC67[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC67, 2); } LA55: ; } break; case ((Ttypekind294244) 17): { { NIM_BOOL LOC71; TY534811 LOC74; LOC71 = (NIM_BOOL)0; LOC71 = isimportedcpptype_535478_839829468(ty0); if (!LOC71) goto LA72; memset((void*)LOC74, 0, sizeof(LOC74)); LOC74[0] = rdloc_540188_839829468(dest0); LOC74[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC74, 2); } goto LA69; LA72: ; { NIM_BOOL LOC76; LOC76 = (NIM_BOOL)0; LOC76 = isobjlackingtypefield_535515_839829468(ty0); if (!!(LOC76)) goto LA77; gengenericasgn_552167_839829468(p0, dest0, src0, flags0); } goto LA69; LA77: ; { NIM_BOOL LOC80; LOC80 = (NIM_BOOL)0; LOC80 = needscomplexassignment_535511_839829468(ty0); if (!LOC80) goto LA81; { NIM_BOOL LOC85; NI LOC87; Ropeobj180006* LOC90; LOC85 = (NIM_BOOL)0; LOC85 = (*ty0).sons->data[((NI) 0)] == 0; if (!(LOC85)) goto LA86; LOC87 = (NI)0; LOC87 = asgncomplexity_551751_839829468((*ty0).n); LOC85 = (LOC87 <= ((NI) 4)); LA86: ; if (!LOC85) goto LA88; LOC90 = (Ropeobj180006*)0; LOC90 = gettypedesc_537673_839829468((*p0).module, ty0); ty0 = getuniquetype_530640_2036603609(ty0); { NimStringDesc* LOC95; if (!!(!(((*ty0).n == NIM_NIL)))) goto LA93; LOC95 = (NimStringDesc*)0; LOC95 = HEX24_198185_1689653243(T839829468_264); internalerror_198113_155036129(LOC95); } LA93: ; genoptasgnobject_552084_839829468(p0, dest0, src0, flags0, (*ty0).n); } goto LA83; LA88: ; { gengenericasgn_552167_839829468(p0, dest0, src0, flags0); } LA83: ; } goto LA69; LA81: ; { TY534811 LOC98; memset((void*)LOC98, 0, sizeof(LOC98)); LOC98[0] = rdloc_540188_839829468(dest0); LOC98[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC98, 2); } LA69: ; } break; case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = needscomplexassignment_535511_839829468((*dest0).t); if (!LOC102) goto LA103; gengenericasgn_552167_839829468(p0, dest0, src0, flags0); } goto LA100; LA103: ; { TY537238 LOC106; usestringh_534345_839829468((*p0).module); memset((void*)LOC106, 0, sizeof(LOC106)); LOC106[0] = rdloc_540188_839829468(dest0); LOC106[1] = rdloc_540188_839829468(src0); LOC106[2] = gettypedesc_537673_839829468((*p0).module, ty0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_261), LOC106, 3); } LA100: ; } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { { NIM_BOOL LOC110; TY537238 LOC113; LOC110 = (NIM_BOOL)0; LOC110 = needscomplexassignment_535511_839829468((*dest0).t); if (!LOC110) goto LA111; memset((void*)LOC113, 0, sizeof(LOC113)); LOC113[0] = addrloc_540204_839829468(dest0); LOC113[1] = addrloc_540204_839829468(src0); LOC113[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_266), LOC113, 3); } goto LA108; LA111: ; { TY534811 LOC115; usestringh_534345_839829468((*p0).module); memset((void*)LOC115, 0, sizeof(LOC115)); LOC115[0] = rdloc_540188_839829468(dest0); LOC115[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_267), LOC115, 2); } LA108: ; } break; case ((Ttypekind294244) 19): { { Tctypekind531007 LOC119; TY537238 LOC122; NI64 LOC123; LOC119 = (Tctypekind531007)0; LOC119 = maptype_535394_839829468(ty0); if (!(LOC119 == ((Tctypekind531007) 17))) goto LA120; usestringh_534345_839829468((*p0).module); memset((void*)LOC122, 0, sizeof(LOC122)); LOC122[0] = rdloc_540188_839829468(dest0); LOC122[1] = rdloc_540188_839829468(src0); LOC123 = (NI64)0; LOC123 = getsize_322135_3876443242((*dest0).t); LOC122[2] = rope_180401_2381377266(LOC123); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_268), LOC122, 3); } goto LA117; LA120: ; { TY534811 LOC125; memset((void*)LOC125, 0, sizeof(LOC125)); LOC125[0] = rdloc_540188_839829468(dest0); LOC125[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC125, 2); } LA117: ; } break; case ((Ttypekind294244) 21): case ((Ttypekind294244) 26): case ((Ttypekind294244) 2): case ((Ttypekind294244) 1): case ((Ttypekind294244) 14): case ((Ttypekind294244) 29): case ((Ttypekind294244) 31) ... ((Ttypekind294244) 44): case ((Ttypekind294244) 20): case ((Ttypekind294244) 23): { TY534811 LOC127; memset((void*)LOC127, 0, sizeof(LOC127)); LOC127[0] = rdloc_540188_839829468(dest0); LOC127[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC127, 2); } break; default: { NimStringDesc* LOC129; LOC129 = (NimStringDesc*)0; LOC129 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI294244))->Sup.len + 15); appendString(LOC129, ((NimStringDesc*) &T839829468_269)); appendString(LOC129, reprEnum((NI)(*ty0).kind, (&NTI294244))); internalerror_198113_155036129(LOC129); } break; } }BeforeRet: ; } N_NIMCALL(void, putlocintodest_541258_839829468)(Tcproc531021* p0, Tloc294816* d0, Tloc294816* s0) { { if (!!(((*d0).k == ((Tlockind294808) 0)))) goto LA3; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag294810) 2))&15U)))!=0)) goto LA7; genassignment_541264_839829468(p0, (&(*d0)), s0, 0); } goto LA5; LA7: ; { genassignment_541264_839829468(p0, (&(*d0)), s0, 1); } LA5: ; } goto LA1; LA3: ; { genericAssign((void*)(&(*d0)), (void*)s0, (&NTI294816)); } LA1: ; } N_NIMCALL(NIM_BOOL, issimpleconst_534311_839829468)(Ttype294840* typ0) { NIM_BOOL result0; Ttype294840* t0; NIM_BOOL LOC1; NIM_BOOL LOC3; result0 = (NIM_BOOL)0; t0 = skiptypes_298099_850551059(typ0, IL64(211106240964864)); LOC1 = (NIM_BOOL)0; LOC1 = !(((17760272 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)); if (!(LOC1)) goto LA2; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind294244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention294002) 8)); LA4: ; LOC1 = !(LOC3); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putintodest_552468_839829468)(Tcproc531021* p0, Tloc294816* d0, Ttype294840* t0, Ropeobj180006* r0, Tstorageloc294812 s0) { Tloc294816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind294808) 0)))) goto LA3; initloc_534273_839829468((&a0), ((Tlockind294808) 6), t0, s0); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag294810) 2))&15U)))!=0)) goto LA7; genassignment_541264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_541264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind294808) 6); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NI64, bitsettoword_551578_839829468)(Tbitset341004* s0, NI size0) { NI64 result0; result0 = (NI64)0; result0 = IL64(0); { NI j_551612_839829468; NI HEX3Atmp_551622_839829468; NI res_551625_839829468; j_551612_839829468 = (NI)0; HEX3Atmp_551622_839829468 = (NI)0; HEX3Atmp_551622_839829468 = (NI)(size0 - ((NI) 1)); res_551625_839829468 = ((NI) 0); { while (1) { if (!(res_551625_839829468 <= HEX3Atmp_551622_839829468)) goto LA3; j_551612_839829468 = res_551625_839829468; { if (!(j_551612_839829468 < (s0 ? s0->Sup.len : 0))) goto LA6; result0 = (NI64)(result0 | (NI64)((NU64)(((NI64)(NU64)(NU8)(s0->data[j_551612_839829468]))) << (NU64)(((NI64) ((NI)(j_551612_839829468 * ((NI) 8))))))); } LA6: ; res_551625_839829468 += ((NI) 1); } LA3: ; } } return result0; } N_NIMCALL(Ropeobj180006*, genrawsetdata_551629_839829468)(Tbitset341004* cs0, NI size0) { Ropeobj180006* result0; NimStringDesc* frmt0; result0 = (Ropeobj180006*)0; frmt0 = (NimStringDesc*)0; { TY535289 LOC5; if (!(((NI) 8) < size0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_273), LOC5, 0); { NI i_551649_839829468; NI HEX3Atmp_551657_839829468; NI res_551660_839829468; i_551649_839829468 = (NI)0; HEX3Atmp_551657_839829468 = (NI)0; HEX3Atmp_551657_839829468 = (NI)(size0 - ((NI) 1)); res_551660_839829468 = ((NI) 0); { while (1) { TY180507 LOC19; NimStringDesc* LOC20; if (!(res_551660_839829468 <= HEX3Atmp_551657_839829468)) goto LA8; i_551649_839829468 = res_551660_839829468; { if (!(i_551649_839829468 < (NI)(size0 - ((NI) 1)))) goto LA11; { if (!(((NI) ((NI)((NI)(i_551649_839829468 + ((NI) 1)) % ((NI) 8)))) == ((NI) 0))) goto LA15; frmt0 = copyString(((NimStringDesc*) &T839829468_274)); } goto LA13; LA15: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_275)); } LA13: ; } goto LA9; LA11: ; { frmt0 = copyString(((NimStringDesc*) &T839829468_276)); } LA9: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC20 = (NimStringDesc*)0; LOC20 = nsuToHex(((NI64)(NU64)(NU8)(cs0->data[i_551649_839829468])), ((NI) 2)); LOC19[0] = rope_180277_2381377266(LOC20); addf_181205_2381377266(&result0, frmt0, LOC19, 1); res_551660_839829468 += ((NI) 1); } LA8: ; } } } goto LA1; LA3: ; { NI64 LOC22; LOC22 = (NI64)0; LOC22 = bitsettoword_551578_839829468(cs0, size0); result0 = intliteral_541270_839829468(LOC22); } LA1: ; return result0; } N_NIMCALL(void, appcg_534640_839829468)(Tcgen531027* m0, Tcfilesection531005 s0, NimStringDesc* frmt0, Ropeobj180006** args0, NI args0Len0) { Ropeobj180006* LOC1; LOC1 = (Ropeobj180006*)0; LOC1 = ropecg_534407_839829468(m0, frmt0, args0, args0Len0); add_180482_2381377266(&(*m0).s[(s0)- 0], LOC1); } N_NIMCALL(Ropeobj180006*, genconstseq_561371_839829468)(Tcproc531021* p0, Tnode294802* n0, Ttype294840* t0) { Ropeobj180006* result0; Ropeobj180006* data0; TY180507 LOC1; NI LOC2; TY537235 LOC18; NI LOC19; TY534811 LOC20; result0 = (Ropeobj180006*)0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = len_295081_850551059(n0); LOC1[0] = rope_180401_2381377266(((NI64) (LOC2))); data0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_277), LOC1, 1); { NI LOC5; LOC5 = (NI)0; LOC5 = len_295081_850551059(n0); if (!(((NI) 0) < LOC5)) goto LA6; add_180487_2381377266(&data0, ((NimStringDesc*) &T839829468_278)); { NI i_561395_839829468; NI HEX3Atmp_561411_839829468; NI LOC9; NI res_561414_839829468; i_561395_839829468 = (NI)0; HEX3Atmp_561411_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = len_295081_850551059(n0); HEX3Atmp_561411_839829468 = (NI)(LOC9 - ((NI) 1)); res_561414_839829468 = ((NI) 0); { while (1) { Ropeobj180006* LOC17; if (!(res_561414_839829468 <= HEX3Atmp_561411_839829468)) goto LA11; i_561395_839829468 = res_561414_839829468; { TY535289 LOC16; if (!(((NI) 0) < i_561395_839829468)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); addf_181205_2381377266(&data0, ((NimStringDesc*) &T839829468_279), LOC16, 0); } LA14: ; LOC17 = (Ropeobj180006*)0; LOC17 = genconstexpr_556849_839829468(p0, (*n0).kindU.S6.sons->data[i_561395_839829468]); add_180482_2381377266(&data0, LOC17); res_561414_839829468 += ((NI) 1); } LA11: ; } } add_180487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); } LA6: ; add_180487_2381377266(&data0, ((NimStringDesc*) &T839829468_280)); result0 = gettempname_535598_839829468((*p0).module); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = gettypedesc_537673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); LOC19 = (NI)0; LOC19 = len_295081_850551059(n0); LOC18[1] = rope_180401_2381377266(((NI64) (LOC19))); LOC18[2] = result0; LOC18[3] = data0; appcg_534640_839829468((*p0).module, ((Tcfilesection531005) 8), ((NimStringDesc*) &T839829468_281), LOC18, 4); memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC20[1] = result0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_282), LOC20, 2); return result0; } N_NIMCALL(Ropeobj180006*, gennamedconstexpr_561284_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!((*n0).kind == ((Tnodekind294020) 34))) goto LA3; result0 = genconstexpr_556849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA3: ; { result0 = genconstexpr_556849_839829468(p0, n0); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, genconstsimplelist_561299_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; NI length0; TY535289 LOC10; result0 = (Ropeobj180006*)0; length0 = sonslen_297351_850551059(n0); result0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_223)); { NI i_561333_839829468; NI HEX3Atmp_561362_839829468; NI HEX3Atmp_561363_839829468; NI res_561366_839829468; i_561333_839829468 = (NI)0; HEX3Atmp_561362_839829468 = (NI)0; HEX3Atmp_561363_839829468 = (NI)0; HEX3Atmp_561362_839829468 = ((*n0).kind == ((Tnodekind294020) 38)); HEX3Atmp_561363_839829468 = (NI)(length0 - ((NI) 2)); res_561366_839829468 = ((NI) (HEX3Atmp_561362_839829468)); { while (1) { TY180507 LOC4; if (!(res_561366_839829468 <= HEX3Atmp_561363_839829468)) goto LA3; i_561333_839829468 = res_561366_839829468; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = gennamedconstexpr_561284_839829468(p0, (*n0).kindU.S6.sons->data[i_561333_839829468]); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_283), LOC4, 1); res_561366_839829468 += ((NI) 1); } LA3: ; } } { Ropeobj180006* LOC9; if (!(((NI) (((*n0).kind == ((Tnodekind294020) 38)))) < length0)) goto LA7; LOC9 = (Ropeobj180006*)0; LOC9 = gennamedconstexpr_561284_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))]); add_180482_2381377266(&result0, LOC9); } LA7: ; memset((void*)LOC10, 0, sizeof(LOC10)); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_160), LOC10, 0); return result0; } N_NIMCALL(Ropeobj180006*, genconstexpr_556849_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; switch ((*n0).kind) { case ((Tnodekind294020) 58): case ((Tnodekind294020) 59): { result0 = genconstexpr_556849_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)]); } break; case ((Tnodekind294020) 39): { Tbitset341004* cs0; NI64 LOC3; cs0 = (Tbitset341004*)0; tobitset_342001_452470228(n0, (&cs0)); LOC3 = (NI64)0; LOC3 = getsize_322135_3876443242((*n0).typ); result0 = genrawsetdata_551629_839829468(cs0, ((NI) (LOC3))); } break; case ((Tnodekind294020) 41): case ((Tnodekind294020) 37): case ((Tnodekind294020) 155): case ((Tnodekind294020) 38): { Ttype294840* t0; t0 = skiptypes_298099_850551059((*n0).typ, IL64(211106232576256)); { if (!((*t0).kind == ((Ttypekind294244) 24))) goto LA7; result0 = genconstseq_561371_839829468(p0, n0, t0); } goto LA5; LA7: ; { result0 = genconstsimplelist_561299_839829468(p0, n0); } LA5: ; } break; default: { Tloc294816 d0; memset((void*)(&d0), 0, sizeof(d0)); initlocexpr_541283_839829468(p0, n0, (&d0)); result0 = rdloc_540188_839829468((&d0)); } break; } return result0; } N_NIMCALL(void, requestconstimpl_541240_839829468)(Tcproc531021* p0, Tsym294834* sym0) { Tcgen531027* m0; Tcgen531027* q0; { m0 = (*p0).module; useheader_534369_839829468(m0, sym0); { Ropeobj180006* LOC5; if (!((*sym0).loc.k == ((Tlockind294808) 0))) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = manglename_535205_839829468(sym0); fillloc_534282_839829468((&(*sym0).loc), ((Tlockind294808) 8), (*sym0).typ, LOC5, ((Tstorageloc294812) 1)); } LA3: ; { if (!(((*sym0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)) goto LA8; goto BeforeRet; } LA8: ; q0 = findpendingmodule_534241_839829468(m0, sym0); { NIM_BOOL LOC12; NIM_BOOL LOC14; TY537238 LOC17; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_270862_2627731572((&(*q0).declaredthings), (*sym0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_537673_839829468(q0, (*sym0).typ); LOC17[1] = (*sym0).loc.r; LOC17[2] = genconstexpr_556849_839829468((*q0).initproc, (*sym0).ast); addf_181205_2381377266(&(*q0).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; { NIM_BOOL LOC20; NIM_BOOL LOC22; Ropeobj180006* headerdecl0; TY534811 LOC25; LOC20 = (NIM_BOOL)0; LOC20 = !((q0 == m0)); if (!(LOC20)) goto LA21; LOC22 = (NIM_BOOL)0; LOC22 = containsorincl_270862_2627731572((&(*m0).declaredthings), (*sym0).Sup.id); LOC20 = !(LOC22); LA21: ; if (!LOC20) goto LA23; memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = gettypedesc_537673_839829468(m0, (*sym0).loc.t); LOC25[1] = (*sym0).loc.r; headerdecl0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_284), LOC25, 2); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 8))- 0], headerdecl0); { NIM_BOOL LOC28; LOC28 = (NIM_BOOL)0; LOC28 = (((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 6))&31U)))!=0); if (!(LOC28)) goto LA29; LOC28 = !((generatedheader_534201_839829468 == NIM_NIL)); LA29: ; if (!LOC28) goto LA30; add_180482_2381377266(&(*generatedheader_534201_839829468).s[(((Tcfilesection531005) 8))- 0], headerdecl0); } LA30: ; } LA23: ; }BeforeRet: ; } N_NIMCALL(void, gencomplexconst_560249_839829468)(Tcproc531021* p0, Tsym294834* sym0, Tloc294816* d0) { requestconstimpl_541240_839829468(p0, sym0); putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } static N_INLINE(Ropeobj180006**, procsec_531194_3723162438)(Tcproc531021* p0, Tcprocsection531011 s0) { Ropeobj180006** result0; result0 = (Ropeobj180006**)0; result0 = &(*p0).blocks->data[((NI) 0)].sections[(s0)- 0]; return result0; } N_NIMCALL(void, accessthreadlocalvar_534945_839829468)(Tcproc531021* p0, Tsym294834* s0) { { NIM_BOOL LOC3; Ropeobj180006** LOC7; TY535289 LOC8; Ropeobj180006** LOC9; TY535289 LOC10; Ropeobj180006* LOC11; LOC3 = (NIM_BOOL)0; LOC3 = emulatedthreadvars_534949_839829468(); if (!(LOC3)) goto LA4; LOC3 = !((*p0).threadvaraccessed); LA4: ; if (!LOC3) goto LA5; (*p0).threadvaraccessed = NIM_TRUE; (*(*p0).module).flags |= ((NU8)1)<<((((Codegenflag531025) 1))%(sizeof(NU8)*8)); LOC7 = (Ropeobj180006**)0; LOC7 = procsec_531194_3723162438(p0, ((Tcprocsection531011) 0)); memset((void*)LOC8, 0, sizeof(LOC8)); addf_181205_2381377266(LOC7, ((NimStringDesc*) &T839829468_286), LOC8, 0); LOC9 = (Ropeobj180006**)0; LOC9 = procsec_531194_3723162438(p0, ((Tcprocsection531011) 1)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC11 = (Ropeobj180006*)0; LOC11 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_287), LOC10, 0); add_180482_2381377266(LOC9, LOC11); } LA5: ; } static N_INLINE(NIM_BOOL, isemptytype_299441_850551059)(Ttype294840* t0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = (t0 == NIM_NIL); if (LOC1) goto LA2; LOC1 = ((IL64(4611686018427388032) &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, putdataintodest_552436_839829468)(Tcproc531021* p0, Tloc294816* d0, Ttype294840* t0, Ropeobj180006* r0) { Tloc294816 a0; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind294808) 0)))) goto LA3; initloc_534273_839829468((&a0), ((Tlockind294808) 8), t0, ((Tstorageloc294812) 1)); a0.r = r0; { if (!(((*d0).flags &(1U<<((NU)(((Tlocflag294810) 2))&15U)))!=0)) goto LA7; genassignment_541264_839829468(p0, (&(*d0)), (&a0), 0); } goto LA5; LA7: ; { genassignment_541264_839829468(p0, (&(*d0)), (&a0), 1); } LA5: ; } goto LA1; LA3: ; { (*d0).k = ((Tlockind294808) 8); unsureAsgnRef((void**) (&(*d0).t), t0); unsureAsgnRef((void**) (&(*d0).r), r0); } LA1: ; } N_NIMCALL(NIM_BOOL, freshlineinfo_534818_839829468)(Tcproc531021* p0, Tlineinfo193336 info0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = !(((*p0).lastlineinfo.line == info0.line)); if (LOC3) goto LA4; LOC3 = !(((*p0).lastlineinfo.fileindex == info0.fileindex)); LA4: ; if (!LOC3) goto LA5; (*p0).lastlineinfo.line = info0.line; (*p0).lastlineinfo.fileindex = info0.fileindex; result0 = NIM_TRUE; } LA5: ; return result0; } N_NIMCALL(void, genlinedir_534823_839829468)(Tcproc531021* p0, Tnode294802* t0) { NI line0; Ropeobj180006** LOC11; NimStringDesc* LOC12; line0 = safelinenm_534721_839829468((*t0).info); { Ropeobj180006** LOC5; TY535289 LOC6; Ropeobj180006* LOC7; Ropeobj180006* LOC8; Ropeobj180006* LOC9; Ropeobj180006* LOC10; if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 28))&63U)))!=0)) goto LA3; LOC5 = (Ropeobj180006**)0; LOC5 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj180006*)0; LOC7 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_293), LOC6, 0); LOC8 = (Ropeobj180006*)0; LOC8 = sourceline_194065_155036129((*t0).info); LOC9 = (Ropeobj180006*)0; LOC9 = HEX26_180418_2381377266(LOC7, LOC8); LOC10 = (Ropeobj180006*)0; LOC10 = HEX26_180418_2381377266(LOC9, rnl_180903_2381377266); add_180482_2381377266(LOC5, LOC10); } LA3: ; LOC11 = (Ropeobj180006**)0; LOC11 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); LOC12 = (NimStringDesc*)0; LOC12 = tofullpath_194261_155036129((*t0).info.fileindex); genclinedir_534725_839829468(LOC11, LOC12, line0); { NIM_BOOL LOC15; NIM_BOOL LOC17; LOC15 = (NIM_BOOL)0; LOC15 = ((163840 & (*p0).options) == 163840); if (!(LOC15)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = ((*p0).prc == NIM_NIL); if (LOC17) goto LA18; LOC17 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0)); LA18: ; LOC15 = LOC17; LA16: ; if (!LOC15) goto LA19; { NIM_BOOL LOC23; TY534811 LOC26; NimStringDesc* LOC27; LOC23 = (NIM_BOOL)0; LOC23 = freshlineinfo_534818_839829468(p0, (*t0).info); if (!LOC23) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rope_180401_2381377266(((NI64) (line0))); LOC27 = (NimStringDesc*)0; LOC27 = tofilename_194257_155036129((*t0).info.fileindex); LOC26[1] = makecstring_193638_155036129(LOC27); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_294), LOC26, 2); } LA24: ; } goto LA13; LA19: ; { NIM_BOOL LOC29; NIM_BOOL LOC30; NIM_BOOL LOC32; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((98304 & (*p0).options) == 98304); if (!(LOC30)) goto LA31; LOC32 = (NIM_BOOL)0; LOC32 = ((*p0).prc == NIM_NIL); if (LOC32) goto LA33; LOC32 = !((((*(*p0).prc).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0)); LA33: ; LOC30 = LOC32; LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA34; LOC29 = (((NI32) 0) <= (*t0).info.fileindex); LA34: ; if (!LOC29) goto LA35; { NIM_BOOL LOC39; TY534811 LOC42; LOC39 = (NIM_BOOL)0; LOC39 = freshlineinfo_534818_839829468(p0, (*t0).info); if (!LOC39) goto LA40; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rope_180401_2381377266(((NI64) (line0))); LOC42[1] = quotedfilename_198818_155036129((*t0).info); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_295), LOC42, 2); } LA40: ; } goto LA13; LA35: ; LA13: ; } N_NIMCALL(Ropeobj180006*, getlabel_541217_839829468)(Tcproc531021* p0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; (*p0).labels += ((NI) 1); LOC1 = (Ropeobj180006*)0; LOC1 = rope_180401_2381377266(((NI64) ((*p0).labels))); result0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_296), LOC1); return result0; } N_NIMCALL(void, fixlabel_541230_839829468)(Tcproc531021* p0, Ropeobj180006* labl0) { TY180507 LOC1; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = labl0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_299), LOC1, 1); } N_NIMCALL(void, genandor_556311_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0) { Ropeobj180006* L0; Tloc294816 tmp0; L0 = (Ropeobj180006*)0; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); (*p0).splitdecls += ((NI) 1); expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); L0 = getlabel_541217_839829468(p0); { TY534811 LOC5; if (!(m0 == ((Tmagic294524) 127))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&tmp0)); LOC5[1] = L0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_297), LOC5, 2); } goto LA1; LA3: ; { TY534811 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_540188_839829468((&tmp0)); LOC7[1] = L0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_298), LOC7, 2); } LA1: ; expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&tmp0)); fixlabel_541230_839829468(p0, L0); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA10; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI294816)); } goto LA8; LA10: ; { genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA8: ; (*p0).splitdecls -= ((NI) 1); } N_NIMCALL(void, unaryarith_554646_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0) { Tloc294816 a0; Ttype294840* t0; TY537238 LOC1; NI64 LOC2; Ropeobj180006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype294840*)0; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_298099_850551059((*e0).typ, IL64(211106233624832)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); LOC2 = (NI64)0; LOC2 = getsize_322135_3876443242(t0); LOC1[1] = rope_180401_2381377266((NI64)(LOC2 * IL64(8))); LOC1[2] = getsimpletypedesc_535936_839829468((*p0).module, (*e0).typ); LOC3 = (Ropeobj180006*)0; LOC3 = HEX25_180905_2381377266(unarithtab_554653_839829468[(op0)- 99], LOC1, 3); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC3, ((Tstorageloc294812) 0)); } N_NIMCALL(void, unaryarithoverflow_553633_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0) { Tloc294816 a0; Ttype294840* t0; TY534811 LOC7; NI64 LOC8; Ropeobj180006* LOC9; memset((void*)(&a0), 0, sizeof(a0)); t0 = (Ttype294840*)0; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_298099_850551059((*e0).typ, IL64(211106233624832)); { TY534811 LOC5; NI64 LOC6; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 5))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&a0)); LOC6 = (NI64)0; LOC6 = firstord_322001_3876443242(t0); LOC5[1] = intliteral_541270_839829468(LOC6); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_317), LOC5, 2); } LA3: ; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_540188_839829468((&a0)); LOC8 = (NI64)0; LOC8 = getsize_322135_3876443242(t0); LOC7[1] = rope_180401_2381377266((NI64)(LOC8 * IL64(8))); LOC9 = (Ropeobj180006*)0; LOC9 = HEX25_180905_2381377266(opr_553640_839829468[(m0)- 96], LOC7, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC9, ((Tstorageloc294812) 0)); } N_NIMCALL(void, binaryarith_553819_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0) { Tloc294816 a0; Tloc294816 b0; NI64 s0; NI64 LOC1; NI64 LOC2; TY537235 LOC3; Ropeobj180006* LOC4; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); s0 = (NI64)0; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (NI64)0; LOC1 = getsize_322135_3876443242(a0.t); LOC2 = (NI64)0; LOC2 = getsize_322135_3876443242(b0.t); s0 = (NI64)(((LOC1 >= LOC2) ? LOC1 : LOC2) * IL64(8)); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = rdloc_540188_839829468((&a0)); LOC3[1] = rdloc_540188_839829468((&b0)); LOC3[2] = rope_180401_2381377266(s0); LOC3[3] = getsimpletypedesc_535936_839829468((*p0).module, (*e0).typ); LOC4 = (Ropeobj180006*)0; LOC4 = HEX25_180905_2381377266(binarithtab_553826_839829468[(op0)- 52], LOC3, 4); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC4, ((Tstorageloc294812) 0)); } N_NIMCALL(void, binaryfloatarith_558729_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0) { { Tloc294816 a0; Tloc294816 b0; TY537235 LOC5; Tnode294802* LOC6; Ropeobj180006* LOC7; if (!!(((384 & (*p0).options) == 0))) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_180277_2381377266(opr_558763_839829468[(m0)- 52]); LOC5[1] = rdloc_540188_839829468((&a0)); LOC5[2] = rdloc_540188_839829468((&b0)); LOC6 = (Tnode294802*)0; LOC6 = HEX5BHEX5D_295238_850551059(e0, ((NI) 1)); LOC5[3] = getsimpletypedesc_535936_839829468((*p0).module, (*LOC6).typ); LOC7 = (Ropeobj180006*)0; LOC7 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_319), LOC5, 4); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc294812) 0)); { TY180507 LOC12; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 7))&31U)))!=0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_540188_839829468((&(*d0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_323), LOC12, 1); } LA10: ; { TY180507 LOC17; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 8))&31U)))!=0)) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_540188_839829468((&(*d0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_324), LOC17, 1); } LA15: ; } goto LA1; LA3: ; { binaryarith_553819_839829468(p0, e0, d0, m0); } LA1: ; } N_NIMCALL(void, geneqproc_554214_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype294840* LOC3; TY534811 LOC6; Ropeobj180006* LOC7; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059(a0.t, IL64(211106232576256)); if (!((*LOC3).callconv == ((Tcallingconvention294002) 8))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rdloc_540188_839829468((&a0)); LOC6[1] = rdloc_540188_839829468((&b0)); LOC7 = (Ropeobj180006*)0; LOC7 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_352), LOC6, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC7, ((Tstorageloc294812) 0)); } goto LA1; LA4: ; { TY534811 LOC9; Ropeobj180006* LOC10; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rdloc_540188_839829468((&a0)); LOC9[1] = rdloc_540188_839829468((&b0)); LOC10 = (Ropeobj180006*)0; LOC10 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_341), LOC9, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC10, ((Tstorageloc294812) 0)); } LA1: ; } N_NIMCALL(Ropeobj180006*, rdcharloc_540227_839829468)(Tloc294816* a0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = rdloc_540188_839829468(a0); { Ttype294840* LOC3; TY180507 LOC6; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059((*a0).t, IL64(211106233624832)); if (!((*LOC3).kind == ((Ttypekind294244) 2))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_358), LOC6, 1); } LA4: ; return result0; } N_NIMCALL(Ropeobj180006*, binaryarithoverflowraw_553235_839829468)(Tcproc531021* p0, Ttype294840* t0, Tloc294816* a0, Tloc294816* b0, NimStringDesc* frmt0) { Ropeobj180006* result0; NI64 size0; Ropeobj180006* storage0; TY534811 LOC6; TY537238 LOC7; result0 = (Ropeobj180006*)0; size0 = getsize_322135_3876443242(t0); { if (!(size0 < ((NI64) (intsize_178641_4151366050)))) goto LA3; storage0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_36)); } goto LA1; LA3: ; { storage0 = gettypedesc_537673_839829468((*p0).module, t0); } LA1: ; result0 = gettempname_535598_839829468((*p0).module); memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = storage0; LOC6[1] = result0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 0), ((NimStringDesc*) &T839829468_54), LOC6, 2); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = result0; LOC7[1] = rdcharloc_540227_839829468(a0); LOC7[2] = rdcharloc_540227_839829468(b0); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), frmt0, LOC7, 3); { NIM_BOOL LOC10; TY537238 LOC14; NI64 LOC15; NI64 LOC16; LOC10 = (NIM_BOOL)0; LOC10 = (size0 < ((NI64) (intsize_178641_4151366050))); if (LOC10) goto LA11; LOC10 = ((1064960 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC15 = (NI64)0; LOC15 = firstord_322001_3876443242(t0); LOC14[1] = intliteral_541270_839829468(LOC15); LOC16 = (NI64)0; LOC16 = lastord_322004_3876443242(t0); LOC14[2] = intliteral_541270_839829468(LOC16); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_359), LOC14, 3); } LA12: ; return result0; } N_NIMCALL(void, binaryarithoverflow_553262_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 m0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* t0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_298099_850551059((*e0).typ, IL64(211106233624832)); { Ropeobj180006* res0; TY537238 LOC5; if (!!((((*p0).options &(1U<<((NU)(((Toption171009) 5))&31U)))!=0))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC5[1] = rdloc_540188_839829468((&a0)); LOC5[2] = rdloc_540188_839829468((&b0)); res0 = HEX25_180905_2381377266(opr_553279_839829468[(m0)- 45], LOC5, 3); putintodest_552468_839829468(p0, d0, (*e0).typ, res0, ((Tstorageloc294812) 0)); } goto LA1; LA3: ; { Ropeobj180006* res0; NimStringDesc* LOC7; TY534811 LOC13; Ropeobj180006* LOC14; LOC7 = (NimStringDesc*)0; { if (!((*t0).kind == ((Ttypekind294244) 35))) goto LA10; LOC7 = copyString(prc64_553274_839829468[(m0)- 45]); } goto LA8; LA10: ; { LOC7 = copyString(prc_553269_839829468[(m0)- 45]); } LA8: ; res0 = binaryarithoverflowraw_553235_839829468(p0, t0, (&a0), (&b0), LOC7); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC13[1] = res0; LOC14 = (Ropeobj180006*)0; LOC14 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_370), LOC13, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC14, ((Tstorageloc294812) 0)); } LA1: ; } N_NIMCALL(Ropeobj180006*, lenfield_541305_839829468)(Tcproc531021* p0) { Ropeobj180006* result0; NimStringDesc* LOC1; result0 = (Ropeobj180006*)0; LOC1 = (NimStringDesc*)0; { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC4) goto LA5; LOC4 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA5: ; if (!LOC4) goto LA6; LOC1 = copyString(((NimStringDesc*) &T839829468_157)); } goto LA2; LA6: ; { LOC1 = copyString(((NimStringDesc*) &T839829468_158)); } LA2: ; result0 = rope_180277_2381377266(LOC1); return result0; } N_NIMCALL(void, gcusage_556439_839829468)(Tnode294802* n0) { { NimStringDesc* LOC5; if (!(gselectedgc_171133_2607990831 == ((Tgcmode171080) 0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = rendertree_313044_382274130(n0, 0); message_198095_155036129((*n0).info, ((Tmsgkind193002) 263), LOC5); } LA3: ; } N_NIMCALL(void, genrepr_557339_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* t0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); t0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); switch ((*t0).kind) { case ((Ttypekind294244) 31) ... ((Ttypekind294244) 35): case ((Ttypekind294244) 40) ... ((Ttypekind294244) 44): { TY180507 LOC2; Ropeobj180006* LOC3; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_540188_839829468((&a0)); LOC3 = (Ropeobj180006*)0; LOC3 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_371), LOC2, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC3, a0.s); } break; case ((Ttypekind294244) 36) ... ((Ttypekind294244) 39): { TY180507 LOC5; Ropeobj180006* LOC6; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&a0)); LOC6 = (Ropeobj180006*)0; LOC6 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_372), LOC5, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } break; case ((Ttypekind294244) 1): { TY180507 LOC8; Ropeobj180006* LOC9; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468((&a0)); LOC9 = (Ropeobj180006*)0; LOC9 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_373), LOC8, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC9, a0.s); } break; case ((Ttypekind294244) 2): { TY180507 LOC11; Ropeobj180006* LOC12; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_540188_839829468((&a0)); LOC12 = (Ropeobj180006*)0; LOC12 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_374), LOC11, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC12, a0.s); } break; case ((Ttypekind294244) 14): case ((Ttypekind294244) 15): { TY534811 LOC14; Ropeobj180006* LOC15; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_540188_839829468((&a0)); LOC14[1] = gentypeinfo_537941_839829468((*p0).module, t0); LOC15 = (Ropeobj180006*)0; LOC15 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_375), LOC14, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } break; case ((Ttypekind294244) 28): { TY180507 LOC17; Ropeobj180006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_540188_839829468((&a0)); LOC18 = (Ropeobj180006*)0; LOC18 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_376), LOC17, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } break; case ((Ttypekind294244) 19): { TY534811 LOC20; Ropeobj180006* LOC21; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = addrloc_540204_839829468((&a0)); LOC20[1] = gentypeinfo_537941_839829468((*p0).module, t0); LOC21 = (Ropeobj180006*)0; LOC21 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_377), LOC20, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC21, a0.s); } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { Tloc294816 b0; TY534811 LOC34; Ttype294840* LOC35; Ropeobj180006* LOC36; memset((void*)(&b0), 0, sizeof(b0)); switch ((*a0.t).kind) { case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { TY180507 LOC24; Ropeobj180006* LOC25; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = rdloc_540188_839829468((&a0)); LOC25 = (Ropeobj180006*)0; LOC25 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_378), LOC24, 1); putintodest_552468_839829468(p0, (&b0), (*e0).typ, LOC25, a0.s); } break; case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { TY534811 LOC27; Ropeobj180006* LOC28; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rdloc_540188_839829468((&a0)); LOC27[1] = lenfield_541305_839829468(p0); LOC28 = (Ropeobj180006*)0; LOC28 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_379), LOC27, 2); putintodest_552468_839829468(p0, (&b0), (*e0).typ, LOC28, a0.s); } break; case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { TY534811 LOC30; NI64 LOC31; Ropeobj180006* LOC32; memset((void*)LOC30, 0, sizeof(LOC30)); LOC30[0] = rdloc_540188_839829468((&a0)); LOC31 = (NI64)0; LOC31 = lengthord_322007_3876443242(a0.t); LOC30[1] = rope_180401_2381377266(LOC31); LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_380), LOC30, 2); putintodest_552468_839829468(p0, (&b0), (*e0).typ, LOC32, a0.s); } break; default: { internalerror_198100_155036129((*(*e0).kindU.S6.sons->data[((NI) 0)]).info, ((NimStringDesc*) &T839829468_381)); } break; } memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = rdloc_540188_839829468((&b0)); LOC35 = (Ttype294840*)0; LOC35 = elemtype_322394_3876443242(t0); LOC34[1] = gentypeinfo_537941_839829468((*p0).module, LOC35); LOC36 = (Ropeobj180006*)0; LOC36 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_382), LOC34, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC36, a0.s); } break; case ((Ttypekind294244) 29): case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): case ((Ttypekind294244) 22): case ((Ttypekind294244) 21): case ((Ttypekind294244) 26): case ((Ttypekind294244) 5): case ((Ttypekind294244) 24): { TY534811 LOC38; Ropeobj180006* LOC39; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = rdloc_540188_839829468((&a0)); LOC38[1] = gentypeinfo_537941_839829468((*p0).module, t0); LOC39 = (Ropeobj180006*)0; LOC39 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC38, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC39, a0.s); } break; case ((Ttypekind294244) 3): case ((Ttypekind294244) 62): { localerror_198085_155036129((*e0).info, ((NimStringDesc*) &T839829468_384)); } break; default: { TY534811 LOC42; Ropeobj180006* LOC43; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = addrloc_540204_839829468((&a0)); LOC42[1] = gentypeinfo_537941_839829468((*p0).module, t0); LOC43 = (Ropeobj180006*)0; LOC43 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_383), LOC42, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC43, a0.s); } break; } gcusage_556439_839829468(e0); } N_NIMCALL(void, gengettypeinfo_557383_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Ttype294840* t0; Ropeobj180006* LOC1; t0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); LOC1 = (Ropeobj180006*)0; LOC1 = gentypeinfo_537941_839829468((*p0).module, t0); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC1, ((Tstorageloc294812) 0)); } N_NIMCALL(void, genswap_557638_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Tloc294816 tmp0; Ttype294840* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); LOC1 = (Ttype294840*)0; LOC1 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); gettemp_539032_839829468(p0, LOC1, (&tmp0), NIM_FALSE); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); genassignment_541264_839829468(p0, (&tmp0), (&a0), 0); genassignment_541264_839829468(p0, (&a0), (&b0), 0); genassignment_541264_839829468(p0, (&b0), (&tmp0), 0); } N_NIMCALL(void, unaryexpr_553209_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; TY180507 LOC1; Ropeobj180006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); } N_NIMCALL(void, binarystmt_552501_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; Tloc294816 b0; TY534811 LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { if (!!(((*d0).k == ((Tlockind294808) 0)))) goto LA3; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_387)); } LA3: ; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&a0)); LOC5[1] = rdloc_540188_839829468((&b0)); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), frmt0, LOC5, 2); } N_NIMCALL(void, genstrconcat_556452_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 tmp0; NI L0; Ropeobj180006* appends0; Ropeobj180006* lens0; TY537238 LOC21; Ropeobj180006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, (*e0).typ, (&tmp0), NIM_FALSE); L0 = ((NI) 0); appends0 = NIM_NIL; lens0 = NIM_NIL; { NI i_556475_839829468; NI HEX3Atmp_556547_839829468; NI LOC2; NI res_556550_839829468; i_556475_839829468 = (NI)0; HEX3Atmp_556547_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(e0); HEX3Atmp_556547_839829468 = (NI)(LOC2 - ((NI) 2)); res_556550_839829468 = ((NI) 0); { while (1) { if (!(res_556550_839829468 <= HEX3Atmp_556547_839829468)) goto LA4; i_556475_839829468 = res_556550_839829468; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))], (&a0)); { Ttype294840* LOC7; TY534811 LOC10; Ropeobj180006* LOC11; LOC7 = (Ttype294840*)0; LOC7 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind294244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0.r; LOC10[1] = rdloc_540188_839829468((&a0)); LOC11 = (Ropeobj180006*)0; LOC11 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_180482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY534811 LOC19; Ropeobj180006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))]).kind >= ((Tnodekind294020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))]).kind <= ((Tnodekind294020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_556475_839829468 + ((NI) 1))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY534811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_540188_839829468((&a0)); LOC18[1] = lenfield_541305_839829468(p0); addf_181205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = tmp0.r; LOC19[1] = rdloc_540188_839829468((&a0)); LOC20 = (Ropeobj180006*)0; LOC20 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_180482_2381377266(&appends0, LOC20); } LA5: ; res_556550_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = tmp0.r; LOC21[1] = lens0; LOC21[2] = rope_180401_2381377266(((NI64) (L0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_393), LOC21, 3); LOC22 = (Ropeobj180006**)0; LOC22 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC22, appends0); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA25; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI294816)); } goto LA23; LA25: ; { genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA23: ; gcusage_556439_839829468(e0); } N_NIMCALL(void, genstrappend_556554_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 dest0; Ropeobj180006* appends0; Ropeobj180006* lens0; NI L0; TY537238 LOC21; Ropeobj180006** LOC22; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&dest0), 0, sizeof(dest0)); appends0 = (Ropeobj180006*)0; lens0 = (Ropeobj180006*)0; L0 = ((NI) 0); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&dest0)); { NI i_556615_839829468; NI HEX3Atmp_556676_839829468; NI LOC2; NI res_556679_839829468; i_556615_839829468 = (NI)0; HEX3Atmp_556676_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(e0); HEX3Atmp_556676_839829468 = (NI)(LOC2 - ((NI) 3)); res_556679_839829468 = ((NI) 0); { while (1) { if (!(res_556679_839829468 <= HEX3Atmp_556676_839829468)) goto LA4; i_556615_839829468 = res_556679_839829468; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))], (&a0)); { Ttype294840* LOC7; TY534811 LOC10; Ropeobj180006* LOC11; LOC7 = (Ttype294840*)0; LOC7 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))]).typ, IL64(211106242013440)); if (!((*LOC7).kind == ((Ttypekind294244) 2))) goto LA8; L0 += ((NI) 1); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_540188_839829468((&dest0)); LOC10[1] = rdloc_540188_839829468((&a0)); LOC11 = (Ropeobj180006*)0; LOC11 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_390), LOC10, 2); add_180482_2381377266(&appends0, LOC11); } goto LA5; LA8: ; { TY534811 LOC19; Ropeobj180006* LOC20; { if (!((*(*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))]).kind >= ((Tnodekind294020) 20) && (*(*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))]).kind <= ((Tnodekind294020) 22))) goto LA15; L0 += ((*(*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))]).kindU.S3.strval ? (*(*e0).kindU.S6.sons->data[(NI)(i_556615_839829468 + ((NI) 2))]).kindU.S3.strval->Sup.len : 0); } goto LA13; LA15: ; { TY534811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_540188_839829468((&a0)); LOC18[1] = lenfield_541305_839829468(p0); addf_181205_2381377266(&lens0, ((NimStringDesc*) &T839829468_391), LOC18, 2); } LA13: ; memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_540188_839829468((&dest0)); LOC19[1] = rdloc_540188_839829468((&a0)); LOC20 = (Ropeobj180006*)0; LOC20 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_392), LOC19, 2); add_180482_2381377266(&appends0, LOC20); } LA5: ; res_556679_839829468 += ((NI) 1); } LA4: ; } } memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_540188_839829468((&dest0)); LOC21[1] = lens0; LOC21[2] = rope_180401_2381377266(((NI64) (L0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_395), LOC21, 3); LOC22 = (Ropeobj180006**)0; LOC22 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC22, appends0); gcusage_556439_839829468(e0); } N_NIMCALL(void, genseqelemappend_556683_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { NimStringDesc* seqappendpattern0; Tloc294816 a0; Tloc294816 b0; Tloc294816 dest0; Ttype294840* bt0; TY537238 LOC8; Ttype294840* LOC9; TY534811 LOC10; TY534811 LOC11; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_396)); } goto LA1; LA5: ; { seqappendpattern0 = copyString(((NimStringDesc*) &T839829468_397)); } LA1: ; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&dest0), 0, sizeof(dest0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); bt0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 2)]).typ, IL64(211106240964864)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468((&a0)); LOC9 = (Ttype294840*)0; LOC9 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC8[1] = gettypedesc_537673_839829468((*p0).module, LOC9); LOC8[2] = gettypedesc_537673_839829468((*p0).module, bt0); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), seqappendpattern0, LOC8, 3); initloc_534273_839829468((&dest0), ((Tlockind294808) 6), bt0, ((Tstorageloc294812) 3)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdloc_540188_839829468((&a0)); LOC10[1] = lenfield_541305_839829468(p0); dest0.r = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_398), LOC10, 2); genassignment_541264_839829468(p0, (&dest0), (&b0), 3); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdloc_540188_839829468((&a0)); LOC11[1] = lenfield_541305_839829468(p0); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_399), LOC11, 2); gcusage_556439_839829468(e0); } N_NIMCALL(void, binaryexpr_552549_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; Tloc294816 b0; TY534811 LOC1; Ropeobj180006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); LOC1[1] = rdloc_540188_839829468((&b0)); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); } N_NIMCALL(void, genstrequals_558667_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 x0; Tnode294802* a0; Tnode294802* b0; memset((void*)(&x0), 0, sizeof(x0)); a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; b0 = (*e0).kindU.S6.sons->data[((NI) 2)]; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*a0).kind == ((Tnodekind294020) 23)); if (LOC3) goto LA4; LOC3 = ((*b0).kind == ((Tnodekind294020) 23)); LA4: ; if (!LOC3) goto LA5; binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } goto LA1; LA5: ; { NIM_BOOL LOC8; TY534811 LOC12; Ropeobj180006* LOC13; LOC8 = (NIM_BOOL)0; LOC8 = ((*a0).kind >= ((Tnodekind294020) 20) && (*a0).kind <= ((Tnodekind294020) 22)); if (!(LOC8)) goto LA9; LOC8 = (((*a0).kindU.S3.strval) && ((*a0).kindU.S3.strval)->Sup.len == 0); LA9: ; if (!LOC8) goto LA10; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&x0)); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_540188_839829468((&x0)); LOC12[1] = lenfield_541305_839829468(p0); LOC13 = (Ropeobj180006*)0; LOC13 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC12, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC13, ((Tstorageloc294812) 0)); } goto LA1; LA10: ; { NIM_BOOL LOC15; TY534811 LOC19; Ropeobj180006* LOC20; LOC15 = (NIM_BOOL)0; LOC15 = ((*b0).kind >= ((Tnodekind294020) 20) && (*b0).kind <= ((Tnodekind294020) 22)); if (!(LOC15)) goto LA16; LOC15 = (((*b0).kindU.S3.strval) && ((*b0).kindU.S3.strval)->Sup.len == 0); LA16: ; if (!LOC15) goto LA17; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&x0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_540188_839829468((&x0)); LOC19[1] = lenfield_541305_839829468(p0); LOC20 = (Ropeobj180006*)0; LOC20 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_400), LOC19, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC20, ((Tstorageloc294812) 0)); } goto LA1; LA17: ; { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_401)); } LA1: ; } N_NIMCALL(void, genisnil_554620_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Ttype294840* t0; t0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*t0).kind == ((Ttypekind294244) 25)); if (!(LOC3)) goto LA4; LOC3 = ((*t0).callconv == ((Tcallingconvention294002) 8)); LA4: ; if (!LOC3) goto LA5; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_404)); } goto LA1; LA5: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_405)); } LA1: ; } N_NIMCALL(void, gendollar_557391_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; TY180507 LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); a0.r = ropecg_534407_839829468((*p0).module, frmt0, LOC1, 1); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA4; gettemp_539032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA4: ; genassignment_541264_839829468(p0, (&(*d0)), (&a0), 0); gcusage_556439_839829468(n0); } N_NIMCALL(Ropeobj180006*, genofhelper_557140_839829468)(Tcproc531021* p0, Ttype294840* dest0, Ropeobj180006* a0) { Ropeobj180006* result0; Ropeobj180006* ti0; result0 = (Ropeobj180006*)0; ti0 = gentypeinfo_537941_839829468((*p0).module, dest0); { NIM_BOOL LOC3; NIM_BOOL LOC5; TY534811 LOC9; LOC3 = (NIM_BOOL)0; LOC3 = (((*dest0).flags &(1U<<((NU)(((Ttypeflag294431) 2))&31U)))!=0); if (LOC3) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*(*p0).module).flags &(1U<<((NU)(((Codegenflag531025) 5))&7U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*dest0).flags &(1U<<((NU)(((Ttypeflag294431) 5))&31U)))!=0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = a0; LOC9[1] = ti0; result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_414), LOC9, 2); } goto LA1; LA7: ; { Ropeobj180006* LOC11; Ropeobj180006* cache0; Ropeobj180006* LOC12; TY180507 LOC13; TY537238 LOC14; LOC11 = (Ropeobj180006*)0; LOC11 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_129)); (*(*p0).module).labels += ((NI) 1); LOC12 = (Ropeobj180006*)0; LOC12 = rope_180401_2381377266(((NI64) ((*(*p0).module).labels))); cache0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_415), LOC12); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = cache0; addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_416), LOC13, 1); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = a0; LOC14[1] = ti0; LOC14[2] = cache0; result0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_417), LOC14, 3); } LA1: ; return result0; } N_NIMCALL(void, genof_557201_839829468)(Tcproc531021* p0, Tnode294802* x0, Ttype294840* typ0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* dest0; Ropeobj180006* r0; Ropeobj180006* nilcheck0; Ttype294840* t0; Ttype294840* LOC41; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, x0, (&a0)); dest0 = skiptypes_298099_850551059(typ0, IL64(211106247256320)); r0 = rdloc_540188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_298099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype294840* LOC16; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA2; { if (!!(((*t0).kind == ((Ttypekind294244) 23)))) goto LA5; nilcheck0 = r0; } LA5: ; { NIM_BOOL LOC9; NIM_BOOL LOC11; TY180507 LOC15; LOC9 = (NIM_BOOL)0; LOC9 = !(((*t0).kind == ((Ttypekind294244) 23))); if (LOC9) goto LA10; LOC11 = (NIM_BOOL)0; LOC11 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC11) goto LA12; LOC11 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA12: ; LOC9 = !(LOC11); LA10: ; if (!LOC9) goto LA13; memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = r0; r0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC15, 1); } LA13: ; LOC16 = (Ttype294840*)0; LOC16 = lastson_297377_850551059(t0); t0 = skiptypes_298099_850551059(LOC16, IL64(211106232576256)); } LA2: ; } { NIM_BOOL LOC19; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA20: ; if (!!(LOC19)) goto LA21; { while (1) { NIM_BOOL LOC25; TY535289 LOC27; Ropeobj180006* LOC28; LOC25 = (NIM_BOOL)0; LOC25 = ((*t0).kind == ((Ttypekind294244) 17)); if (!(LOC25)) goto LA26; LOC25 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA26: ; if (!LOC25) goto LA24; memset((void*)LOC27, 0, sizeof(LOC27)); LOC28 = (Ropeobj180006*)0; LOC28 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_153), LOC27, 0); add_180482_2381377266(&r0, LOC28); t0 = skiptypes_298099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA24: ; } } LA21: ; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = isobjlackingtypefield_535515_839829468(t0); if (!LOC31) goto LA32; globalerror_198071_155036129((*x0).info, ((Tmsgkind193002) 4), ((NimStringDesc*) &T839829468_412)); } LA32: ; { TY534811 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = genofhelper_557140_839829468(p0, dest0, r0); r0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_413), LOC38, 2); } goto LA34; LA36: ; { TY180507 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = genofhelper_557140_839829468(p0, dest0, r0); r0 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_418), LOC40, 1); } LA34: ; LOC41 = (Ttype294840*)0; LOC41 = getsystype_340150_3937434831(((Ttypekind294244) 1)); putintodest_552468_839829468(p0, d0, LOC41, r0, a0.s); } N_NIMCALL(void, genof_557331_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { genof_557201_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (*(*n0).kindU.S6.sons->data[((NI) 2)]).typ, d0); } N_NIMCALL(void, rawgennew_556741_839829468)(Tcproc531021* p0, Tloc294816* a0, Ropeobj180006* sizeexpr_556745_839829468) { Ropeobj180006* sizeexpr0; Ttype294840* reftype0; Tloc294816 b0; TY537238 args0; Ttype294840* bt0; sizeexpr0 = sizeexpr_556745_839829468; reftype0 = skiptypes_298099_850551059((*a0).t, IL64(211106242013440)); memset((void*)(&b0), 0, sizeof(b0)); initloc_534273_839829468((&b0), ((Tlockind294808) 6), (*a0).t, ((Tstorageloc294812) 3)); { TY180507 LOC5; Ttype294840* LOC6; if (!sizeexpr0 == 0) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (Ttype294840*)0; LOC6 = skiptypes_298099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); LOC5[0] = gettypedesc_537673_839829468((*p0).module, LOC6); sizeexpr0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_419), LOC5, 1); } LA3: ; memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_537673_839829468((*p0).module, reftype0); args0[1] = gentypeinfo_537941_839829468((*p0).module, reftype0); args0[2] = sizeexpr0; { NIM_BOOL LOC9; TY534811 LOC21; LOC9 = (NIM_BOOL)0; LOC9 = ((*a0).s == ((Tstorageloc294812) 3)); if (!(LOC9)) goto LA10; LOC9 = usesnativegc_171177_2607990831(); LA10: ; if (!LOC9) goto LA11; { NIM_BOOL LOC15; TY180507 LOC18; LOC15 = (NIM_BOOL)0; LOC15 = canformacycle_322123_3876443242((*a0).t); if (!LOC15) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_540188_839829468(a0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_420), LOC18, 1); } goto LA13; LA16: ; { TY180507 LOC20; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_540188_839829468(a0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_255), LOC20, 1); } LA13: ; b0.r = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_421), args0, 3); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdloc_540188_839829468(a0); LOC21[1] = rdloc_540188_839829468((&b0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC21, 2); } goto LA7; LA11: ; { b0.r = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_422), args0, 3); genassignment_541264_839829468(p0, a0, (&b0), 0); } LA7: ; bt0 = skiptypes_298099_850551059((*reftype0).sons->data[((NI) 0)], IL64(211106233624832)); genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 2), bt0, a0, NIM_FALSE); } N_NIMCALL(void, gennew_556782_839829468)(Tcproc531021* p0, Tnode294802* e0) { Tloc294816 a0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI LOC3; Tloc294816 se0; Ropeobj180006* LOC6; LOC3 = (NI)0; LOC3 = len_295081_850551059(e0); if (!(LOC3 == ((NI) 3))) goto LA4; memset((void*)(&se0), 0, sizeof(se0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&se0)); LOC6 = (Ropeobj180006*)0; LOC6 = rdloc_540188_839829468((&se0)); rawgennew_556741_839829468(p0, (&a0), LOC6); } goto LA1; LA4: ; { rawgennew_556741_839829468(p0, (&a0), NIM_NIL); } LA1: ; gcusage_556439_839829468(e0); } N_NIMCALL(void, gennewfinalize_557111_839829468)(Tcproc531021* p0, Tnode294802* e0) { Tloc294816 a0; Tloc294816 b0; Tloc294816 f0; Ttype294840* reftype0; Ttype294840* bt0; Ropeobj180006* ti0; TY534811 LOC1; TY537238 LOC2; Ttype294840* LOC3; Ttype294840* LOC4; Ttype294840* LOC5; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&f0), 0, sizeof(f0)); reftype0 = (Ttype294840*)0; bt0 = (Ttype294840*)0; ti0 = (Ropeobj180006*)0; reftype0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&f0)); initloc_534273_839829468((&b0), ((Tlockind294808) 6), a0.t, ((Tstorageloc294812) 3)); ti0 = gentypeinfo_537941_839829468((*p0).module, reftype0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = ti0; LOC1[1] = rdloc_540188_839829468((&f0)); addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_423), LOC1, 2); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = gettypedesc_537673_839829468((*p0).module, reftype0); LOC2[1] = ti0; LOC3 = (Ttype294840*)0; LOC3 = lastson_297377_850551059(reftype0); LOC4 = (Ttype294840*)0; LOC4 = skiptypes_298099_850551059(LOC3, IL64(211106233624832)); LOC2[2] = gettypedesc_537673_839829468((*p0).module, LOC4); b0.r = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_424), LOC2, 3); genassignment_541264_839829468(p0, (&a0), (&b0), 0); LOC5 = (Ttype294840*)0; LOC5 = lastson_297377_850551059(reftype0); bt0 = skiptypes_298099_850551059(LOC5, IL64(211106233624832)); genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 2), bt0, (&a0), NIM_FALSE); gcusage_556439_839829468(e0); } N_NIMCALL(void, gennewseqaux_556795_839829468)(Tcproc531021* p0, Tloc294816* dest0, Ropeobj180006* length0) { Ttype294840* seqtype0; TY537238 args0; Tloc294816 call0; seqtype0 = skiptypes_298099_850551059((*dest0).t, IL64(211106242013440)); memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_537673_839829468((*p0).module, seqtype0); args0[1] = gentypeinfo_537941_839829468((*p0).module, seqtype0); args0[2] = length0; memset((void*)(&call0), 0, sizeof(call0)); initloc_534273_839829468((&call0), ((Tlockind294808) 6), (*dest0).t, ((Tstorageloc294812) 3)); { NIM_BOOL LOC3; TY534811 LOC15; LOC3 = (NIM_BOOL)0; LOC3 = ((*dest0).s == ((Tstorageloc294812) 3)); if (!(LOC3)) goto LA4; LOC3 = usesnativegc_171177_2607990831(); LA4: ; if (!LOC3) goto LA5; { NIM_BOOL LOC9; TY180507 LOC12; LOC9 = (NIM_BOOL)0; LOC9 = canformacycle_322123_3876443242((*dest0).t); if (!LOC9) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_540188_839829468(dest0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_420), LOC12, 1); } goto LA7; LA10: ; { TY180507 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_540188_839829468(dest0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_255), LOC14, 1); } LA7: ; call0.r = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_425), args0, 3); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rdloc_540188_839829468(dest0); LOC15[1] = rdloc_540188_839829468((&call0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC15, 2); } goto LA1; LA5: ; { call0.r = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_426), args0, 3); genassignment_541264_839829468(p0, dest0, (&call0), 0); } LA1: ; } N_NIMCALL(void, gennewseq_556824_839829468)(Tcproc531021* p0, Tnode294802* e0) { Tloc294816 a0; Tloc294816 b0; Ropeobj180006* LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); LOC1 = (Ropeobj180006*)0; LOC1 = rdloc_540188_839829468((&b0)); gennewseqaux_556795_839829468(p0, (&a0), LOC1); gcusage_556439_839829468(e0); } N_NIMCALL(void, gennewseqofcap_556836_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Ttype294840* seqtype0; Tloc294816 a0; TY537238 LOC1; Ropeobj180006* LOC2; seqtype0 = skiptypes_298099_850551059((*e0).typ, IL64(211106242013440)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = gettypedesc_537673_839829468((*p0).module, seqtype0); LOC1[1] = gentypeinfo_537941_839829468((*p0).module, seqtype0); LOC1[2] = rdloc_540188_839829468((&a0)); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_427), LOC1, 3); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); gcusage_556439_839829468(e0); } N_NIMCALL(Ropeobj180006*, getclosuretype_537685_839829468)(Tcgen531027* m0, Ttype294840* t0, Tclosuretypekind537681 kind0) { Ropeobj180006* result0; Intset270030 check0; Ropeobj180006* rettype0; Ropeobj180006* desc0; result0 = (Ropeobj180006*)0; memset((void*)(&check0), 0, sizeof(check0)); chckNil((void*)(&check0)); memset((void*)(&check0), 0, sizeof(check0)); initintset_270885_2627731572((&check0)); result0 = gettempname_535598_839829468(m0); rettype0 = (Ropeobj180006*)0; desc0 = (Ropeobj180006*)0; genprocparams_536115_839829468(m0, t0, &rettype0, &desc0, (&check0), !((kind0 == ((Tclosuretypekind537681) 0))), NIM_FALSE); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedtype_535451_839829468(t0); if (!!(LOC3)) goto LA4; { NIM_BOOL LOC8; TY537235 LOC12; LOC8 = (NIM_BOOL)0; LOC8 = !(((*t0).callconv == ((Tcallingconvention294002) 8))); if (LOC8) goto LA9; LOC8 = !((kind0 == ((Tclosuretypekind537681) 2))); LA9: ; if (!LOC8) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_180277_2381377266(Callingconvtostr_535587_839829468[((*t0).callconv)- 0]); LOC12[1] = rettype0; LOC12[2] = result0; LOC12[3] = desc0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_64), LOC12, 4); } goto LA6; LA10: ; { TY537238 LOC14; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = result0; LOC14[1] = rettype0; LOC14[2] = desc0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 3))- 0], ((NimStringDesc*) &T839829468_75), LOC14, 3); } LA6: ; } LA4: ; return result0; } N_NIMCALL(void, gensomecast_558481_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* etyp0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); etyp0 = skiptypes_298099_850551059((*e0).typ, IL64(211106233624832)); { NIM_BOOL LOC3; TY534811 LOC7; Ropeobj180006* LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(281475111387152) &((NU64)1<<((NU)((*etyp0).kind)&63U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(((a0.flags &(1U<<((NU)(((Tlocflag294810) 0))&15U)))!=0)); LA4: ; if (!LOC3) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_537673_839829468((*p0).module, (*e0).typ); LOC7[1] = addrloc_540204_839829468((&a0)); LOC8 = (Ropeobj180006*)0; LOC8 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_429), LOC7, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC8, a0.s); } goto LA1; LA5: ; { NIM_BOOL LOC10; TY534811 LOC14; Ropeobj180006* LOC15; LOC10 = (NIM_BOOL)0; LOC10 = ((*etyp0).kind == ((Ttypekind294244) 25)); if (!(LOC10)) goto LA11; LOC10 = ((*etyp0).callconv == ((Tcallingconvention294002) 8)); LA11: ; if (!LOC10) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = getclosuretype_537685_839829468((*p0).module, etyp0, ((Tclosuretypekind537681) 1)); LOC14[1] = rdcharloc_540227_839829468((&a0)); LOC15 = (Ropeobj180006*)0; LOC15 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_430), LOC14, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC15, a0.s); } goto LA1; LA12: ; { TY534811 LOC17; Ropeobj180006* LOC18; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_537673_839829468((*p0).module, (*e0).typ); LOC17[1] = rdcharloc_540227_839829468((&a0)); LOC18 = (Ropeobj180006*)0; LOC18 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_430), LOC17, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC18, a0.s); } LA1: ; } N_NIMCALL(void, unaryexprchar_553222_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; TY180507 LOC1; Ropeobj180006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_540227_839829468((&a0)); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, LOC1, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); } N_NIMCALL(void, genord_558475_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { unaryexprchar_553222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_301)); } N_NIMCALL(void, genarraylen_557415_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0) { Tnode294802* a0; Ttype294840* typ0; a0 = (*e0).kindU.S6.sons->data[((NI) 1)]; { if (!((*a0).kind == ((Tnodekind294020) 64))) goto LA3; a0 = (*a0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; typ0 = skiptypes_298099_850551059((*a0).typ, IL64(211106240964864)); switch ((*typ0).kind) { case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { { if (!(op0 == ((Tmagic294524) 8))) goto LA8; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_431)); } goto LA6; LA8: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_432)); } LA6: ; } break; case ((Ttypekind294244) 29): { usestringh_534345_839829468((*p0).module); { if (!(op0 == ((Tmagic294524) 8))) goto LA14; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_433)); } goto LA12; LA14: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_434)); } LA12: ; } break; case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA21: ; if (!!(LOC20)) goto LA22; { if (!(op0 == ((Tmagic294524) 8))) goto LA26; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_435)); } goto LA24; LA26: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_436)); } LA24: ; } goto LA18; LA22: ; { { if (!(op0 == ((Tmagic294524) 8))) goto LA32; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_437)); } goto LA30; LA32: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_438)); } LA30: ; } LA18: ; } break; case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { { NI64 LOC40; Ropeobj180006* LOC41; if (!(op0 == ((Tmagic294524) 8))) goto LA38; LOC40 = (NI64)0; LOC40 = lastord_322004_3876443242(typ0); LOC41 = (Ropeobj180006*)0; LOC41 = rope_180401_2381377266(LOC40); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC41, ((Tstorageloc294812) 0)); } goto LA36; LA38: ; { NI64 LOC43; Ropeobj180006* LOC44; LOC43 = (NI64)0; LOC43 = lengthord_322007_3876443242(typ0); LOC44 = (Ropeobj180006*)0; LOC44 = rope_180401_2381377266(LOC43); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC44, ((Tstorageloc294812) 0)); } LA36: ; } break; default: { internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_439)); } break; } } N_NIMCALL(void, unarystmt_552527_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; TY180507 LOC5; memset((void*)(&a0), 0, sizeof(a0)); { if (!!(((*d0).k == ((Tlockind294808) 0)))) goto LA3; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_442)); } LA3: ; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&a0)); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), frmt0, LOC5, 1); } N_NIMCALL(void, gensetlengthstr_557632_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { binarystmt_552501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_445)); gcusage_556439_839829468(e0); } N_NIMCALL(void, gensetlengthseq_557500_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* t0; NimStringDesc* setlenpattern0; TY537235 LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); t0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!!(LOC3)) goto LA5; setlenpattern0 = copyString(((NimStringDesc*) &T839829468_446)); } goto LA1; LA5: ; { setlenpattern0 = copyString(((NimStringDesc*) &T839829468_447)); } LA1: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468((&a0)); LOC8[1] = rdloc_540188_839829468((&b0)); LOC8[2] = gettypedesc_537673_839829468((*p0).module, t0); LOC8[3] = gettypedesc_537673_839829468((*p0).module, (*t0).sons->data[((NI) 0)]); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), setlenpattern0, LOC8, 4); gcusage_556439_839829468(e0); } N_NIMCALL(Ropeobj180006*, rdsetelemloc_557662_839829468)(Tloc294816* a0, Ttype294840* settype0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = rdcharloc_540227_839829468(a0); { NI64 LOC3; TY534811 LOC6; NI64 LOC7; LOC3 = (NI64)0; LOC3 = firstord_322001_3876443242(settype0); if (!!((LOC3 == IL64(0)))) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = result0; LOC7 = (NI64)0; LOC7 = firstord_322001_3876443242(settype0); LOC6[1] = rope_180401_2381377266(LOC7); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_448), LOC6, 2); } LA4: ; return result0; } N_NIMCALL(void, binarystmtinexcl_557858_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; Tloc294816 b0; TY534811 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); LOC1[1] = rdsetelemloc_557662_839829468((&b0), a0.t); linef_534700_839829468(p0, ((Tcprocsection531011) 2), frmt0, LOC1, 2); } N_NIMCALL(void, binaryexprchar_552809_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NimStringDesc* frmt0) { Tloc294816 a0; Tloc294816 b0; TY534811 LOC1; Ropeobj180006* LOC2; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdcharloc_540227_839829468((&a0)); LOC1[1] = rdcharloc_540227_839829468((&b0)); LOC2 = (Ropeobj180006*)0; LOC2 = ropecg_534407_839829468((*p0).module, frmt0, LOC1, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); } N_NIMCALL(NIM_BOOL, fewcmps_557803_839829468)(Tnode294802* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { if (!!(((*s0).kind == ((Tnodekind294020) 39)))) goto LA3; internalerror_198100_155036129((*s0).info, ((NimStringDesc*) &T839829468_463)); } LA3: ; { NIM_BOOL LOC7; NI64 LOC8; LOC7 = (NIM_BOOL)0; LOC8 = (NI64)0; LOC8 = getsize_322135_3876443242((*s0).typ); LOC7 = (LOC8 <= ((NI64) (intsize_178641_4151366050))); if (!(LOC7)) goto LA9; LOC7 = (((*s0).flags &(1U<<((NU)(((Tnodeflag294427) 4))&15U)))!=0); LA9: ; if (!LOC7) goto LA10; result0 = NIM_FALSE; } goto LA5; LA10: ; { Ttype294840* LOC13; LOC13 = (Ttype294840*)0; LOC13 = elemtype_322394_3876443242((*s0).typ); if (!((IL64(62277025792) &((NU64)1<<((NU)((*LOC13).kind)&63U)))!=0)) goto LA14; result0 = NIM_TRUE; } goto LA5; LA14: ; { NI LOC17; LOC17 = (NI)0; LOC17 = sonslen_297351_850551059(s0); result0 = (LOC17 <= ((NI) 8)); } LA5: ; return result0; } N_NIMCALL(void, binaryexprin_557837_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* a0, Tloc294816* b0, Tloc294816* d0, NimStringDesc* frmt0) { TY534811 LOC1; Ropeobj180006* LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&(*a0))); LOC1[1] = rdsetelemloc_557662_839829468((&(*b0)), (*a0).t); LOC2 = (Ropeobj180006*)0; LOC2 = HEX25_180905_2381377266(frmt0, LOC1, 2); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC2, ((Tstorageloc294812) 0)); } N_NIMCALL(void, geninexpraux_555496_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* a0, Tloc294816* b0, Tloc294816* d0) { Ttype294840* LOC1; NI64 LOC2; LOC1 = (Ttype294840*)0; LOC1 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC2 = (NI64)0; LOC2 = getsize_322135_3876443242(LOC1); switch (((NI) (LOC2))) { case ((NI) 1): { binaryexprin_557837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_467)); } break; case ((NI) 2): { binaryexprin_557837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_468)); } break; case ((NI) 4): { binaryexprin_557837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_469)); } break; case ((NI) 8): { binaryexprin_557837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_470)); } break; default: { binaryexprin_557837_839829468(p0, e0, a0, b0, d0, ((NimStringDesc*) &T839829468_471)); } break; } } N_NIMCALL(void, geninop_558009_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Tloc294816 x0; Tloc294816 y0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); { NIM_BOOL LOC3; Tnode294802* ea0; NI length0; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind294020) 39)); if (!(LOC3)) goto LA4; LOC3 = fewcmps_557803_839829468((*e0).kindU.S6.sons->data[((NI) 1)]); LA4: ; if (!LOC3) goto LA5; { if (!((*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 70) || (*(*e0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 69))) goto LA9; ea0 = (*(*e0).kindU.S6.sons->data[((NI) 2)]).kindU.S6.sons->data[((NI) 0)]; } goto LA7; LA9: ; { ea0 = (*e0).kindU.S6.sons->data[((NI) 2)]; } LA7: ; initlocexpr_541283_839829468(p0, ea0, (&a0)); initloc_534273_839829468((&b0), ((Tlockind294808) 6), (*e0).typ, ((Tstorageloc294812) 0)); b0.r = rope_180277_2381377266(((NimStringDesc*) &T839829468_118)); length0 = sonslen_297351_850551059((*e0).kindU.S6.sons->data[((NI) 1)]); { NI i_558061_839829468; NI HEX3Atmp_558412_839829468; NI res_558415_839829468; i_558061_839829468 = (NI)0; HEX3Atmp_558412_839829468 = (NI)0; HEX3Atmp_558412_839829468 = (NI)(length0 - ((NI) 1)); res_558415_839829468 = ((NI) 0); { while (1) { if (!(res_558415_839829468 <= HEX3Atmp_558412_839829468)) goto LA14; i_558061_839829468 = res_558415_839829468; { TY537238 LOC19; if (!((*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_558061_839829468]).kind == ((Tnodekind294020) 44))) goto LA17; initlocexpr_541283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_558061_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_541283_839829468(p0, (*(*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_558061_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdcharloc_540227_839829468((&a0)); LOC19[1] = rdcharloc_540227_839829468((&x0)); LOC19[2] = rdcharloc_540227_839829468((&y0)); addf_181205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_464), LOC19, 3); } goto LA15; LA17: ; { TY534811 LOC21; initlocexpr_541283_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[i_558061_839829468], (&x0)); memset((void*)LOC21, 0, sizeof(LOC21)); LOC21[0] = rdcharloc_540227_839829468((&a0)); LOC21[1] = rdcharloc_540227_839829468((&x0)); addf_181205_2381377266(&b0.r, ((NimStringDesc*) &T839829468_465), LOC21, 2); } LA15: ; { if (!(i_558061_839829468 < (NI)(length0 - ((NI) 1)))) goto LA24; add_180487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_466)); } LA24: ; res_558415_839829468 += ((NI) 1); } LA14: ; } } add_180487_2381377266(&b0.r, ((NimStringDesc*) &T839829468_117)); putintodest_552468_839829468(p0, d0, (*e0).typ, b0.r, ((Tstorageloc294812) 0)); } goto LA1; LA5: ; { initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); geninexpraux_555496_839829468(p0, e0, (&a0), (&b0), d0); } LA1: ; } N_NIMCALL(void, gensetop_558419_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0) { Tloc294816 a0; Tloc294816 b0; Tloc294816 i0; Ttype294840* settype0; NI size0; NI64 LOC1; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&i0), 0, sizeof(i0)); settype0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106240964864)); LOC1 = (NI64)0; LOC1 = getsize_322135_3876443242(settype0); size0 = ((NI) (LOC1)); switch (size0) { case ((NI) 1): case ((NI) 2): case ((NI) 4): case ((NI) 8): { switch (op0) { case ((Tmagic294524) 39): { NimStringDesc* ts0; NimStringDesc* LOC4; NimStringDesc* LOC5; NimStringDesc* LOC6; LOC4 = (NimStringDesc*)0; LOC5 = (NimStringDesc*)0; LOC5 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC4 = rawNewString(LOC5->Sup.len + 2); appendString(LOC4, ((NimStringDesc*) &T839829468_45)); appendString(LOC4, LOC5); ts0 = LOC4; LOC6 = (NimStringDesc*)0; LOC6 = rawNewString(ts0->Sup.len + ts0->Sup.len + 35); appendString(LOC6, ((NimStringDesc*) &T839829468_449)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_450)); appendString(LOC6, ts0); appendString(LOC6, ((NimStringDesc*) &T839829468_451)); binarystmtinexcl_557858_839829468(p0, e0, d0, LOC6); } break; case ((Tmagic294524) 40): { NimStringDesc* ts0; NimStringDesc* LOC8; NimStringDesc* LOC9; NimStringDesc* LOC10; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nimIntToStr((NI)(size0 * ((NI) 8))); LOC8 = rawNewString(LOC9->Sup.len + 2); appendString(LOC8, ((NimStringDesc*) &T839829468_45)); appendString(LOC8, LOC9); ts0 = LOC8; LOC10 = (NimStringDesc*)0; LOC10 = rawNewString(ts0->Sup.len + ts0->Sup.len + 42); appendString(LOC10, ((NimStringDesc*) &T839829468_452)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_453)); appendString(LOC10, ts0); appendString(LOC10, ((NimStringDesc*) &T839829468_454)); binarystmtinexcl_557858_839829468(p0, e0, d0, LOC10); } break; case ((Tmagic294524) 41): { { if (!(size0 <= ((NI) 4))) goto LA14; unaryexprchar_553222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_455)); } goto LA12; LA14: ; { unaryexprchar_553222_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_456)); } LA12: ; } break; case ((Tmagic294524) 133): { binaryexprchar_552809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_457)); } break; case ((Tmagic294524) 132): { binaryexprchar_552809_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_458)); } break; case ((Tmagic294524) 131): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_341)); } break; case ((Tmagic294524) 134): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_459)); } break; case ((Tmagic294524) 135): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_460)); } break; case ((Tmagic294524) 136): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_461)); } break; case ((Tmagic294524) 137): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_462)); } break; case ((Tmagic294524) 148): { geninop_558009_839829468(p0, e0, d0); } break; default: { internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_472)); } break; } } break; default: { switch (op0) { case ((Tmagic294524) 39): { binarystmtinexcl_557858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_473)); } break; case ((Tmagic294524) 40): { binarystmtinexcl_557858_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_474)); } break; case ((Tmagic294524) 41): { NimStringDesc* LOC30; NimStringDesc* LOC31; LOC30 = (NimStringDesc*)0; LOC31 = (NimStringDesc*)0; LOC31 = nimIntToStr(size0); LOC30 = rawNewString(LOC31->Sup.len + 14); appendString(LOC30, ((NimStringDesc*) &T839829468_475)); appendString(LOC30, LOC31); appendChar(LOC30, 41); unaryexprchar_553222_839829468(p0, e0, d0, LOC30); } break; case ((Tmagic294524) 133): case ((Tmagic294524) 132): { Ttype294840* LOC33; TY538475 LOC39; LOC33 = (Ttype294840*)0; LOC33 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC33, (&i0), NIM_FALSE); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { Ttype294840* LOC38; if (!((*d0).k == ((Tlockind294808) 0))) goto LA36; LOC38 = (Ttype294840*)0; LOC38 = getsystype_340150_3937434831(((Ttypekind294244) 1)); gettemp_539032_839829468(p0, LOC38, d0, NIM_FALSE); } LA36: ; memset((void*)LOC39, 0, sizeof(LOC39)); LOC39[0] = rdloc_540188_839829468((&i0)); LOC39[1] = rope_180401_2381377266(((NI64) (size0))); LOC39[2] = rdloc_540188_839829468((&(*d0))); LOC39[3] = rdloc_540188_839829468((&a0)); LOC39[4] = rdloc_540188_839829468((&b0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), lookupopr_558426_839829468[(op0)- 132], LOC39, 5); } break; case ((Tmagic294524) 131): { NimStringDesc* LOC41; NimStringDesc* LOC42; usestringh_534345_839829468((*p0).module); LOC41 = (NimStringDesc*)0; LOC42 = (NimStringDesc*)0; LOC42 = nimIntToStr(size0); LOC41 = rawNewString(LOC42->Sup.len + 21); appendString(LOC41, ((NimStringDesc*) &T839829468_481)); appendString(LOC41, LOC42); appendString(LOC41, ((NimStringDesc*) &T839829468_482)); binaryexprchar_552809_839829468(p0, e0, d0, LOC41); } break; case ((Tmagic294524) 134): case ((Tmagic294524) 135): case ((Tmagic294524) 136): case ((Tmagic294524) 137): { Ttype294840* LOC44; TY538847 LOC49; LOC44 = (Ttype294840*)0; LOC44 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC44, (&i0), NIM_FALSE); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA47; gettemp_539032_839829468(p0, a0.t, d0, NIM_FALSE); } LA47: ; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_540188_839829468((&i0)); LOC49[1] = rope_180401_2381377266(((NI64) (size0))); LOC49[2] = rdloc_540188_839829468((&(*d0))); LOC49[3] = rdloc_540188_839829468((&a0)); LOC49[4] = rdloc_540188_839829468((&b0)); LOC49[5] = rope_180277_2381377266(lookupopr_558426_839829468[(op0)- 132]); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_483), LOC49, 6); } break; case ((Tmagic294524) 148): { geninop_558009_839829468(p0, e0, d0); } break; default: { internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_484)); } break; } } break; } } static N_INLINE(Ropeobj180006*, genargstringtocstring_541776_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; Tloc294816 a0; TY180507 LOC1; result0 = (Ropeobj180006*)0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_485), LOC1, 1); return result0; } N_NIMCALL(Ropeobj180006*, openarrayloc_541665_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; Tloc294816 a0; Tnode294802* q0; result0 = (Ropeobj180006*)0; memset((void*)(&a0), 0, sizeof(a0)); q0 = skipconv_330882_3876443242(n0); { Tmagic294524 LOC3; Tloc294816 b0; Tloc294816 c0; Tnode294802* LOC6; Tnode294802* LOC7; Tnode294802* LOC8; NimStringDesc* fmt0; Ttype294840* LOC9; TY537238 LOC25; LOC3 = (Tmagic294524)0; LOC3 = getmagic_320502_2616423590(q0); if (!(LOC3 == ((Tmagic294524) 139))) goto LA4; memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&c0), 0, sizeof(c0)); LOC6 = (Tnode294802*)0; LOC6 = HEX5BHEX5D_295238_850551059(q0, ((NI) 1)); initlocexpr_541283_839829468(p0, LOC6, (&a0)); LOC7 = (Tnode294802*)0; LOC7 = HEX5BHEX5D_295238_850551059(q0, ((NI) 2)); initlocexpr_541283_839829468(p0, LOC7, (&b0)); LOC8 = (Tnode294802*)0; LOC8 = HEX5BHEX5D_295238_850551059(q0, ((NI) 3)); initlocexpr_541283_839829468(p0, LOC8, (&c0)); LOC9 = (Ttype294840*)0; LOC9 = skiptypes_298099_850551059(a0.t, IL64(211106243062016)); switch ((*LOC9).kind) { case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { fmt0 = copyString(((NimStringDesc*) &T839829468_486)); } break; case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { { NIM_BOOL LOC14; Ttype294840* LOC15; NIM_BOOL LOC17; LOC14 = (NIM_BOOL)0; LOC15 = (Ttype294840*)0; LOC15 = skiptypes_298099_850551059((*n0).typ, IL64(211106232576256)); LOC14 = ((*LOC15).kind == ((Ttypekind294244) 23)); if (!(LOC14)) goto LA16; LOC17 = (NIM_BOOL)0; LOC17 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC17) goto LA18; LOC17 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA18: ; LOC14 = !(LOC17); LA16: ; if (!LOC14) goto LA19; fmt0 = copyString(((NimStringDesc*) &T839829468_487)); } goto LA12; LA19: ; { fmt0 = copyString(((NimStringDesc*) &T839829468_488)); } LA12: ; } break; default: { NimStringDesc* LOC23; NimStringDesc* LOC24; LOC23 = (NimStringDesc*)0; LOC24 = (NimStringDesc*)0; LOC24 = typetostring_322017_3876443242(a0.t, ((Tprefereddesc322011) 0)); LOC23 = rawNewString(LOC24->Sup.len + 14); appendString(LOC23, ((NimStringDesc*) &T839829468_489)); appendString(LOC23, LOC24); internalerror_198113_155036129(LOC23); fmt0 = copyString(((NimStringDesc*) &T839829468_490)); } break; } memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_540188_839829468((&a0)); LOC25[1] = rdloc_540188_839829468((&b0)); LOC25[2] = rdloc_540188_839829468((&c0)); result0 = HEX25_180905_2381377266(fmt0, LOC25, 3); } goto LA1; LA4: ; { Ttype294840* LOC27; initlocexpr_541283_839829468(p0, n0, (&a0)); LOC27 = (Ttype294840*)0; LOC27 = skiptypes_298099_850551059(a0.t, IL64(211106240964864)); switch ((*LOC27).kind) { case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { TY180507 LOC29; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_540188_839829468((&a0)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_378), LOC29, 1); } break; case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { { NIM_BOOL LOC33; Ttype294840* LOC34; NIM_BOOL LOC36; TY534811 LOC40; LOC33 = (NIM_BOOL)0; LOC34 = (Ttype294840*)0; LOC34 = skiptypes_298099_850551059((*n0).typ, IL64(211106232576256)); LOC33 = ((*LOC34).kind == ((Ttypekind294244) 23)); if (!(LOC33)) goto LA35; LOC36 = (NIM_BOOL)0; LOC36 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC36) goto LA37; LOC36 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA37: ; LOC33 = !(LOC36); LA35: ; if (!LOC33) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = rdloc_540188_839829468((&a0)); LOC40[1] = lenfield_541305_839829468(p0); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_491), LOC40, 2); } goto LA31; LA38: ; { TY534811 LOC42; memset((void*)LOC42, 0, sizeof(LOC42)); LOC42[0] = rdloc_540188_839829468((&a0)); LOC42[1] = lenfield_541305_839829468(p0); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_379), LOC42, 2); } LA31: ; } break; case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { TY534811 LOC44; NI64 LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_540188_839829468((&a0)); LOC45 = (NI64)0; LOC45 = lengthord_322007_3876443242(a0.t); LOC44[1] = rope_180401_2381377266(LOC45); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_380), LOC44, 2); } break; case ((Ttypekind294244) 21): case ((Ttypekind294244) 22): { Ttype294840* LOC47; LOC47 = (Ttype294840*)0; LOC47 = lastson_297377_850551059(a0.t); switch ((*LOC47).kind) { case ((Ttypekind294244) 28): case ((Ttypekind294244) 24): { TY534811 LOC49; memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_540188_839829468((&a0)); LOC49[1] = lenfield_541305_839829468(p0); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_491), LOC49, 2); } break; case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { TY534811 LOC51; Ttype294840* LOC52; NI64 LOC53; memset((void*)LOC51, 0, sizeof(LOC51)); LOC51[0] = rdloc_540188_839829468((&a0)); LOC52 = (Ttype294840*)0; LOC52 = lastson_297377_850551059(a0.t); LOC53 = (NI64)0; LOC53 = lengthord_322007_3876443242(LOC52); LOC51[1] = rope_180401_2381377266(LOC53); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_380), LOC51, 2); } break; default: { NimStringDesc* LOC55; NimStringDesc* LOC56; LOC55 = (NimStringDesc*)0; LOC56 = (NimStringDesc*)0; LOC56 = typetostring_322017_3876443242(a0.t, ((Tprefereddesc322011) 0)); LOC55 = rawNewString(LOC56->Sup.len + 14); appendString(LOC55, ((NimStringDesc*) &T839829468_489)); appendString(LOC55, LOC56); internalerror_198113_155036129(LOC55); } break; } } break; default: { NimStringDesc* LOC58; NimStringDesc* LOC59; LOC58 = (NimStringDesc*)0; LOC59 = (NimStringDesc*)0; LOC59 = typetostring_322017_3876443242(a0.t, ((Tprefereddesc322011) 0)); LOC58 = rawNewString(LOC59->Sup.len + 14); appendString(LOC58, ((NimStringDesc*) &T839829468_489)); appendString(LOC58, LOC59); internalerror_198113_155036129(LOC58); } break; } } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, genarg_541787_839829468)(Tcproc531021* p0, Tnode294802* n_541790_839829468, Tsym294834* param0, Tnode294802* call0) { Ropeobj180006* result0; Tloc294816 a0; result0 = (Ropeobj180006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n_541790_839829468).kind == ((Tnodekind294020) 71))) goto LA3; result0 = genargstringtocstring_541776_839829468(p0, n_541790_839829468); } goto LA1; LA3: ; { Ttype294840* LOC6; Tnode294802* n0; LOC6 = (Ttype294840*)0; LOC6 = skiptypes_298099_850551059((*param0).typ, IL64(211106240964864)); if (!((IL64(281475110928384) &((NU64)1<<((NU)((*LOC6).kind)&63U)))!=0)) goto LA7; { if (!!(((*n_541790_839829468).kind == ((Tnodekind294020) 64)))) goto LA11; n0 = n_541790_839829468; } goto LA9; LA11: ; { n0 = (*n_541790_839829468).kindU.S6.sons->data[((NI) 0)]; } LA9: ; result0 = openarrayloc_541665_839829468(p0, n0); } goto LA1; LA7: ; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ccgintroducedptr_535611_839829468(param0); if (!LOC15) goto LA16; initlocexpr_541283_839829468(p0, n_541790_839829468, (&a0)); result0 = addrloc_540204_839829468((&a0)); } goto LA1; LA16: ; { NIM_BOOL LOC19; NIM_BOOL LOC20; NIM_BOOL LOC21; Tnode294802* callee0; LOC19 = (NIM_BOOL)0; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC21) goto LA22; LOC21 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC20 = ((*(*param0).typ).kind == ((Ttypekind294244) 23)); LA23: ; LOC19 = LOC20; if (!(LOC19)) goto LA24; LOC19 = ((*n_541790_839829468).kind == ((Tnodekind294020) 64)); LA24: ; if (!LOC19) goto LA25; initlocexprsingleuse_541289_839829468(p0, (*n_541790_839829468).kindU.S6.sons->data[((NI) 0)], (&a0)); callee0 = (*call0).kindU.S6.sons->data[((NI) 0)]; { NIM_BOOL LOC29; NIM_BOOL LOC30; LOC29 = (NIM_BOOL)0; LOC30 = (NIM_BOOL)0; LOC30 = ((*callee0).kind == ((Tnodekind294020) 3)); if (!(LOC30)) goto LA31; LOC30 = ((134283296 & (*(*callee0).kindU.S4.sym).flags) == 32); LA31: ; LOC29 = LOC30; if (!(LOC29)) goto LA32; LOC29 = !(((72 & (*(*callee0).kindU.S4.sym).loc.flags) == 0)); LA32: ; if (!LOC29) goto LA33; result0 = addrloc_540204_839829468((&a0)); } goto LA27; LA33: ; { result0 = rdloc_540188_839829468((&a0)); } LA27: ; } goto LA1; LA25: ; { initlocexprsingleuse_541289_839829468(p0, n_541790_839829468, (&a0)); result0 = rdloc_540188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, genargnoparam_541938_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; Tloc294816 a0; result0 = (Ropeobj180006*)0; memset((void*)(&a0), 0, sizeof(a0)); { if (!((*n0).kind == ((Tnodekind294020) 71))) goto LA3; result0 = genargstringtocstring_541776_839829468(p0, n0); } goto LA1; LA3: ; { initlocexprsingleuse_541289_839829468(p0, n0, (&a0)); result0 = rdloc_540188_839829468((&a0)); } LA1: ; return result0; } N_NIMCALL(Ropeobj180006*, getrawproctype_542459_839829468)(Tcproc531021* p0, Ttype294840* t0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = getclosuretype_537685_839829468((*p0).module, t0, ((Tclosuretypekind537681) 0)); return result0; } N_NIMCALL(NIM_BOOL, leftappearsonrightside_541329_839829468)(Tnode294802* le0, Tnode294802* ri0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!!((le0 == NIM_NIL))) goto LA3; { NI i_541364_839829468; NI HEX3Atmp_541376_839829468; NI LOC6; NI res_541379_839829468; i_541364_839829468 = (NI)0; HEX3Atmp_541376_839829468 = (NI)0; LOC6 = (NI)0; LOC6 = len_295081_850551059(ri0); HEX3Atmp_541376_839829468 = (LOC6 - 1); res_541379_839829468 = ((NI) 1); { while (1) { Tnode294802* r0; if (!(res_541379_839829468 <= HEX3Atmp_541376_839829468)) goto LA8; i_541364_839829468 = res_541379_839829468; r0 = HEX5BHEX5D_295238_850551059(ri0, i_541364_839829468); { Tanalysisresult475003 LOC11; LOC11 = (Tanalysisresult475003)0; LOC11 = ispartof_475340_788060399(le0, r0); if (!!((LOC11 == ((Tanalysisresult475003) 0)))) goto LA12; result0 = NIM_TRUE; goto BeforeRet; } LA12: ; res_541379_839829468 += ((NI) 1); } LA8: ; } } } LA3: ; }BeforeRet: ; return result0; } static N_INLINE(NIM_BOOL, hasnoinit_541383_839829468)(Tnode294802* call0) { NIM_BOOL result0; NIM_BOOL LOC1; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((*(*call0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC1)) goto LA2; LOC1 = (((*(*(*call0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, resetloc_540350_839829468)(Tcproc531021* p0, Tloc294816* loc0) { NIM_BOOL containsgcref0; Ttype294840* typ0; { containsgcref0 = containsgarbagecollectedref_322117_3876443242((*loc0).t); typ0 = skiptypes_298099_850551059((*loc0).t, IL64(211106242013440)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedcpptype_535478_839829468(typ0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscomplexvaluetype_540317_839829468(typ0); if (!!(LOC8)) goto LA9; { Tloc294816 nilloc0; if (!containsgcref0) goto LA13; memset((void*)(&nilloc0), 0, sizeof(nilloc0)); initloc_534273_839829468((&nilloc0), ((Tlockind294808) 1), (*loc0).t, ((Tstorageloc294812) 2)); nilloc0.r = rope_180277_2381377266(((NimStringDesc*) &T839829468_174)); genrefassign_540311_839829468(p0, (&(*loc0)), (&nilloc0), 8); } goto LA11; LA13: ; { TY180507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468((&(*loc0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_494), LOC16, 1); } LA11: ; } goto LA6; LA9: ; { { TY180507 LOC22; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 6))&31U)))!=0)) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = addrloc_540204_839829468((&(*loc0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_495), LOC22, 1); } LA20: ; { TY534811 LOC27; if (!!(((*loc0).s == ((Tstorageloc294812) 2)))) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = addrloc_540204_839829468((&(*loc0))); LOC27[1] = gentypeinfo_537941_839829468((*p0).module, (*loc0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_496), LOC27, 2); genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } goto LA23; LA25: ; { TY534811 LOC29; usestringh_534345_839829468((*p0).module); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = addrloc_540204_839829468((&(*loc0))); LOC29[1] = rdloc_540188_839829468((&(*loc0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_152), LOC29, 2); genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 2), (*loc0).t, (&(*loc0)), NIM_TRUE); } LA23: ; } LA6: ; }BeforeRet: ; } N_NIMCALL(Ropeobj180006*, addcomma_542464_839829468)(Ropeobj180006* r0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { if (!(r0 == NIM_NIL)) goto LA3; result0 = r0; } goto LA1; LA3: ; { TY535289 LOC6; Ropeobj180006* LOC7; memset((void*)LOC6, 0, sizeof(LOC6)); LOC7 = (Ropeobj180006*)0; LOC7 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC6, 0); result0 = HEX26_180418_2381377266(r0, LOC7); } LA1: ; return result0; } N_NIMCALL(void, genclosurecall_542452_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0) { Tloc294816 op0; Ropeobj180006* pl0; Ttype294840* typ0; NI length0; Ropeobj180006* rawproc0; NimStringDesc* callpattern0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_541283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); pl0 = (Ropeobj180006*)0; typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_297351_850551059(ri0); { NI i_542613_839829468; NI HEX3Atmp_543214_839829468; NI res_543217_839829468; i_542613_839829468 = (NI)0; HEX3Atmp_543214_839829468 = (NI)0; HEX3Atmp_543214_839829468 = (NI)(length0 - ((NI) 1)); res_543217_839829468 = ((NI) 1); { while (1) { if (!(res_543217_839829468 <= HEX3Atmp_543214_839829468)) goto LA3; i_542613_839829468 = res_543217_839829468; { NI LOC6; Tnode294802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_297327_850551059(typ0); if (!(i_542613_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_542613_839829468]; { NIM_BOOL LOC11; Ropeobj180006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_330706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY535289 LOC18; Ropeobj180006* LOC19; if (!!((pl0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj180006*)0; LOC19 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_180482_2381377266(&pl0, LOC19); } LA16: ; LOC20 = (Ropeobj180006*)0; LOC20 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[i_542613_839829468], (*paramtype0).kindU.S4.sym, ri0); add_180482_2381377266(&pl0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj180006* LOC28; { TY535289 LOC26; Ropeobj180006* LOC27; if (!!((pl0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj180006*)0; LOC27 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_180482_2381377266(&pl0, LOC27); } LA24: ; LOC28 = (Ropeobj180006*)0; LOC28 = genargnoparam_541938_839829468(p0, (*ri0).kindU.S6.sons->data[i_542613_839829468]); add_180482_2381377266(&pl0, LOC28); } LA4: ; res_543217_839829468 += ((NI) 1); } LA3: ; } } rawproc0 = getrawproctype_542459_839829468(p0, typ0); { if (!(((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 14))&31U)))!=0)) goto LA31; callpattern0 = copyString(((NimStringDesc*) &T839829468_492)); } goto LA29; LA31: ; { callpattern0 = copyString(((NimStringDesc*) &T839829468_493)); } LA29: ; { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA36; { NIM_BOOL LOC40; LOC40 = (NIM_BOOL)0; LOC40 = isinvalidreturntype_535550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC40) goto LA41; { NI LOC45; TY535289 LOC48; Ropeobj180006* LOC49; LOC45 = (NI)0; LOC45 = sonslen_297351_850551059(ri0); if (!(((NI) 1) < LOC45)) goto LA46; memset((void*)LOC48, 0, sizeof(LOC48)); LOC49 = (Ropeobj180006*)0; LOC49 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC48, 0); add_180482_2381377266(&pl0, LOC49); } LA46: ; { NIM_BOOL LOC52; NIM_BOOL LOC54; Ropeobj180006* LOC67; NimStringDesc* LOC68; TY537235 LOC69; LOC52 = (NIM_BOOL)0; LOC52 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC52) goto LA53; LOC54 = (NIM_BOOL)0; LOC54 = leftappearsonrightside_541329_839829468(le0, ri0); LOC52 = !(LOC54); LA53: ; if (!LOC52) goto LA55; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA59; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA57; LA59: ; { NIM_BOOL LOC62; NIM_BOOL LOC64; LOC62 = (NIM_BOOL)0; LOC62 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC62)) goto LA63; LOC64 = (NIM_BOOL)0; LOC64 = hasnoinit_541383_839829468(ri0); LOC62 = !(LOC64); LA63: ; if (!LOC62) goto LA65; resetloc_540350_839829468(p0, d0); } goto LA57; LA65: ; LA57: ; LOC67 = (Ropeobj180006*)0; LOC67 = addrloc_540204_839829468((&(*d0))); add_180482_2381377266(&pl0, LOC67); LOC68 = (NimStringDesc*)0; LOC68 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC68, callpattern0); appendString(LOC68, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = op0.r; LOC69[1] = pl0; LOC69[2] = addcomma_542464_839829468(pl0); LOC69[3] = rawproc0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), LOC68, LOC69, 4); } goto LA50; LA55: ; { Tloc294816 tmp0; Ropeobj180006* LOC71; NimStringDesc* LOC72; TY537235 LOC73; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC71 = (Ropeobj180006*)0; LOC71 = addrloc_540204_839829468((&tmp0)); add_180482_2381377266(&pl0, LOC71); LOC72 = (NimStringDesc*)0; LOC72 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC72, callpattern0); appendString(LOC72, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC73, 0, sizeof(LOC73)); LOC73[0] = op0.r; LOC73[1] = pl0; LOC73[2] = addcomma_542464_839829468(pl0); LOC73[3] = rawproc0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), LOC72, LOC73, 4); genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA50: ; } goto LA38; LA41: ; { Tloc294816 list0; TY537235 LOC79; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA77; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA77: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_534273_839829468((&list0), ((Tlockind294808) 9), (*d0).t, ((Tstorageloc294812) 0)); memset((void*)LOC79, 0, sizeof(LOC79)); LOC79[0] = op0.r; LOC79[1] = pl0; LOC79[2] = addcomma_542464_839829468(pl0); LOC79[3] = rawproc0; list0.r = HEX25_180905_2381377266(callpattern0, LOC79, 4); genassignment_541264_839829468(p0, (&(*d0)), (&list0), 0); } LA38: ; } goto LA34; LA36: ; { NimStringDesc* LOC81; TY537235 LOC82; LOC81 = (NimStringDesc*)0; LOC81 = rawNewString(callpattern0->Sup.len + 3); appendString(LOC81, callpattern0); appendString(LOC81, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC82, 0, sizeof(LOC82)); LOC82[0] = op0.r; LOC82[1] = pl0; LOC82[2] = addcomma_542464_839829468(pl0); LOC82[3] = rawproc0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), LOC81, LOC82, 4); } LA34: ; } N_NIMCALL(Ropeobj180006*, genotherarg_541277_839829468)(Tcproc531021* p0, Tnode294802* ri0, NI i0, Ttype294840* typ0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NI LOC3; Tnode294802* paramtype0; LOC3 = (NI)0; LOC3 = sonslen_297327_850551059(typ0); if (!(i0 < LOC3)) goto LA4; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i0]; { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = iscompiletimeonly_330706_3876443242((*paramtype0).typ); if (!LOC8) goto LA9; result0 = NIM_NIL; } goto LA6; LA9: ; { NIM_BOOL LOC12; Tnode294802* LOC16; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*typ0).sons->data[i0]).kind == ((Ttypekind294244) 23)); if (!(LOC12)) goto LA13; LOC12 = ((*(*ri0).kindU.S6.sons->data[i0]).kind == ((Tnodekind294020) 64)); LA13: ; if (!LOC12) goto LA14; LOC16 = (Tnode294802*)0; LOC16 = HEX5BHEX5D_295238_850551059((*ri0).kindU.S6.sons->data[i0], ((NI) 0)); result0 = genargnoparam_541938_839829468(p0, LOC16); } goto LA6; LA14: ; { result0 = genargnoparam_541938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA6: ; } goto LA1; LA4: ; { { if (!!((((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 0))&31U)))!=0))) goto LA21; localerror_198085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_501)); result0 = NIM_NIL; } goto LA19; LA21: ; { result0 = genargnoparam_541938_839829468(p0, (*ri0).kindU.S6.sons->data[i0]); } LA19: ; } LA1: ; return result0; } N_NIMCALL(Tnode294802*, skipaddrderef_543433_839829468)(Tnode294802* node0) { Tnode294802* result0; Tnode294802* n0; NIM_BOOL isaddr0; { result0 = (Tnode294802*)0; n0 = node0; isaddr0 = NIM_FALSE; switch ((*n0).kind) { case ((Tnodekind294020) 63): case ((Tnodekind294020) 64): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; isaddr0 = NIM_TRUE; } break; case ((Tnodekind294020) 47): case ((Tnodekind294020) 65): { n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } break; default: { result0 = n0; goto BeforeRet; } break; } { if (!((*n0).kind == ((Tnodekind294020) 66))) goto LA6; n0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } LA6: ; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isaddr0; if (!(LOC10)) goto LA11; LOC10 = ((*n0).kind == ((Tnodekind294020) 47) || (*n0).kind == ((Tnodekind294020) 65)); LA11: ; if (!LOC10) goto LA12; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA12: ; { if (!((*n0).kind == ((Tnodekind294020) 63) || (*n0).kind == ((Tnodekind294020) 64))) goto LA15; result0 = (*n0).kindU.S6.sons->data[((NI) 0)]; } goto LA8; LA15: ; { result0 = node0; } LA8: ; }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, genthisarg_543475_839829468)(Tcproc531021* p0, Tnode294802* ri_543478_839829468, NI i0, Ttype294840* typ0) { Ropeobj180006* result0; Tnode294802* ri0; Ttype294840* t0; result0 = (Ropeobj180006*)0; { NI LOC3; NimStringDesc* LOC6; LOC3 = (NI)0; LOC3 = sonslen_297327_850551059(typ0); if (!!((i0 < LOC3))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_198185_1689653243(T839829468_503); internalerror_198113_155036129(LOC6); } LA4: ; ri0 = HEX5BHEX5D_295238_850551059(ri_543478_839829468, i0); { while (1) { if (!((*ri0).kind == ((Tnodekind294020) 66))) goto LA8; ri0 = HEX5BHEX5D_295238_850551059(ri0, ((NI) 0)); } LA8: ; } t0 = skiptypes_298099_850551059((*typ0).sons->data[i0], 2048); { Tnode294802* x0; if (!((*t0).kind == ((Ttypekind294244) 23))) goto LA11; { if (!((*ri0).kind == ((Tnodekind294020) 64))) goto LA15; x0 = HEX5BHEX5D_295238_850551059(ri0, ((NI) 0)); } goto LA13; LA15: ; { x0 = ri0; } LA13: ; { if (!((*(*x0).typ).kind == ((Ttypekind294244) 21))) goto LA20; result0 = genargnoparam_541938_839829468(p0, x0); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA20: ; { NIM_BOOL LOC23; Tnode294802* LOC25; Tnode294802* LOC28; LOC23 = (NIM_BOOL)0; LOC23 = ((*x0).kind == ((Tnodekind294020) 65) || (*x0).kind == ((Tnodekind294020) 47)); if (!(LOC23)) goto LA24; LOC25 = (Tnode294802*)0; LOC25 = HEX5BHEX5D_295238_850551059(x0, ((NI) 0)); LOC23 = ((*(*LOC25).typ).kind == ((Ttypekind294244) 21)); LA24: ; if (!LOC23) goto LA26; LOC28 = (Tnode294802*)0; LOC28 = HEX5BHEX5D_295238_850551059(x0, ((NI) 0)); result0 = genargnoparam_541938_839829468(p0, LOC28); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } goto LA18; LA26: ; { result0 = genargnoparam_541938_839829468(p0, x0); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA18: ; } goto LA9; LA11: ; { if (!((*t0).kind == ((Ttypekind294244) 21))) goto LA31; { Tnode294802* LOC37; if (!((*ri0).kind == ((Tnodekind294020) 63) || (*ri0).kind == ((Tnodekind294020) 64))) goto LA35; LOC37 = (Tnode294802*)0; LOC37 = HEX5BHEX5D_295238_850551059(ri0, ((NI) 0)); result0 = genargnoparam_541938_839829468(p0, LOC37); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } goto LA33; LA35: ; { result0 = genargnoparam_541938_839829468(p0, ri0); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_504)); } LA33: ; } goto LA9; LA31: ; { ri0 = skipaddrderef_543433_839829468(ri0); { if (!((*ri0).kind == ((Tnodekind294020) 63) || (*ri0).kind == ((Tnodekind294020) 64))) goto LA42; ri0 = HEX5BHEX5D_295238_850551059(ri0, ((NI) 0)); } LA42: ; result0 = genargnoparam_541938_839829468(p0, ri0); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_257)); } LA9: ; return result0; } N_NIMCALL(Ropeobj180006*, genpatterncall_543699_839829468)(Tcproc531021* p0, Tnode294802* ri_543702_839829468, NimStringDesc* pat0, Ttype294840* typ_543704_839829468) { Ropeobj180006* result0; NI i0; NI j0; result0 = (Ropeobj180006*)0; i0 = ((NI) 0); j0 = ((NI) 1); { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA2; switch (((NU8)(pat0->data[i0]))) { case 64: { { NI LOC6; Ropeobj180006* LOC9; LOC6 = (NI)0; LOC6 = len_295081_850551059(ri_543702_839829468); if (!(j0 < LOC6)) goto LA7; LOC9 = (Ropeobj180006*)0; LOC9 = genotherarg_541277_839829468(p0, ri_543702_839829468, j0, typ_543704_839829468); add_180482_2381377266(&result0, LOC9); { NI k_543728_839829468; NI HEX3Atmp_543904_839829468; NI HEX3Atmp_543905_839829468; NI LOC11; NI res_543908_839829468; k_543728_839829468 = (NI)0; HEX3Atmp_543904_839829468 = (NI)0; HEX3Atmp_543905_839829468 = (NI)0; HEX3Atmp_543904_839829468 = (NI)(j0 + ((NI) 1)); LOC11 = (NI)0; LOC11 = len_295081_850551059(ri_543702_839829468); HEX3Atmp_543905_839829468 = (LOC11 - 1); res_543908_839829468 = HEX3Atmp_543904_839829468; { while (1) { TY535289 LOC14; Ropeobj180006* LOC15; Ropeobj180006* LOC16; if (!(res_543908_839829468 <= HEX3Atmp_543905_839829468)) goto LA13; k_543728_839829468 = res_543908_839829468; memset((void*)LOC14, 0, sizeof(LOC14)); LOC15 = (Ropeobj180006*)0; LOC15 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC14, 0); add_180482_2381377266(&result0, LOC15); LOC16 = (Ropeobj180006*)0; LOC16 = genotherarg_541277_839829468(p0, ri_543702_839829468, k_543728_839829468, typ_543704_839829468); add_180482_2381377266(&result0, LOC16); res_543908_839829468 += ((NI) 1); } LA13: ; } } } LA7: ; i0 += ((NI) 1); } break; case 35: { { Tnode294802* ri0; if (!(((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(43)) || ((NU8)(pat0->data[(NI)(i0 + ((NI) 1))])) == ((NU8)(64)))) goto LA20; ri0 = HEX5BHEX5D_295238_850551059(ri_543702_839829468, j0); { Ttype294840* typ0; TY535289 LOC31; Ropeobj180006* LOC32; TY535289 LOC46; Ropeobj180006* LOC47; if (!((*ri0).kind == ((Tnodekind294020) 27) || (*ri0).kind == ((Tnodekind294020) 29) || (*ri0).kind == ((Tnodekind294020) 30) || (*ri0).kind == ((Tnodekind294020) 31) || (*ri0).kind == ((Tnodekind294020) 26) || (*ri0).kind == ((Tnodekind294020) 28) || (*ri0).kind == ((Tnodekind294020) 32))) goto LA24; typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { Ropeobj180006* LOC30; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(43))) goto LA28; LOC30 = (Ropeobj180006*)0; LOC30 = genargnoparam_541938_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)]); add_180482_2381377266(&result0, LOC30); } LA28: ; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_118), LOC31, 0); add_180482_2381377266(&result0, LOC32); { NI LOC35; Ropeobj180006* LOC38; LOC35 = (NI)0; LOC35 = len_295081_850551059(ri0); if (!(((NI) 1) < LOC35)) goto LA36; LOC38 = (Ropeobj180006*)0; LOC38 = genotherarg_541277_839829468(p0, ri0, ((NI) 1), typ0); add_180482_2381377266(&result0, LOC38); } LA36: ; { NI k_543793_839829468; NI HEX3Atmp_543915_839829468; NI HEX3Atmp_543916_839829468; NI LOC40; NI res_543919_839829468; k_543793_839829468 = (NI)0; HEX3Atmp_543915_839829468 = (NI)0; HEX3Atmp_543916_839829468 = (NI)0; HEX3Atmp_543915_839829468 = (NI)(j0 + ((NI) 1)); LOC40 = (NI)0; LOC40 = len_295081_850551059(ri0); HEX3Atmp_543916_839829468 = (LOC40 - 1); res_543919_839829468 = HEX3Atmp_543915_839829468; { while (1) { TY535289 LOC43; Ropeobj180006* LOC44; Ropeobj180006* LOC45; if (!(res_543919_839829468 <= HEX3Atmp_543916_839829468)) goto LA42; k_543793_839829468 = res_543919_839829468; memset((void*)LOC43, 0, sizeof(LOC43)); LOC44 = (Ropeobj180006*)0; LOC44 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC43, 0); add_180482_2381377266(&result0, LOC44); LOC45 = (Ropeobj180006*)0; LOC45 = genotherarg_541277_839829468(p0, ri0, k_543793_839829468, typ0); add_180482_2381377266(&result0, LOC45); res_543919_839829468 += ((NI) 1); } LA42: ; } } memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (Ropeobj180006*)0; LOC47 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_117), LOC46, 0); add_180482_2381377266(&result0, LOC47); } goto LA22; LA24: ; { localerror_198085_155036129((*ri0).info, ((NimStringDesc*) &T839829468_502)); } LA22: ; i0 += ((NI) 1); } goto LA18; LA20: ; { Ropeobj180006* LOC52; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(46))) goto LA50; LOC52 = (Ropeobj180006*)0; LOC52 = genthisarg_543475_839829468(p0, ri_543702_839829468, j0, typ_543704_839829468); add_180482_2381377266(&result0, LOC52); i0 += ((NI) 1); } goto LA18; LA50: ; { Tnode294802* arg0; Ropeobj180006* LOC58; if (!((NU8)(pat0->data[(NI)(i0 + ((NI) 1))]) == (NU8)(91))) goto LA54; arg0 = skipaddrderef_543433_839829468((*ri_543702_839829468).kindU.S6.sons->data[j0]); { while (1) { if (!((*arg0).kind == ((Tnodekind294020) 63) || (*arg0).kind == ((Tnodekind294020) 64) || (*arg0).kind == ((Tnodekind294020) 66))) goto LA57; arg0 = HEX5BHEX5D_295238_850551059(arg0, ((NI) 0)); } LA57: ; } LOC58 = (Ropeobj180006*)0; LOC58 = genargnoparam_541938_839829468(p0, arg0); add_180482_2381377266(&result0, LOC58); } goto LA18; LA54: ; { Ropeobj180006* LOC60; LOC60 = (Ropeobj180006*)0; LOC60 = genotherarg_541277_839829468(p0, ri_543702_839829468, j0, typ_543704_839829468); add_180482_2381377266(&result0, LOC60); } LA18: ; j0 += ((NI) 1); i0 += ((NI) 1); } break; case 39: { NI idx0; NI stars0; idx0 = (NI)0; stars0 = (NI)0; { NIM_BOOL LOC64; Ttype294840* t0; LOC64 = (NIM_BOOL)0; LOC64 = scancppgenericslot_536827_839829468(pat0, (&i0), (&idx0), (&stars0)); if (!LOC64) goto LA65; t0 = resolvestarsincpptype_536891_839829468(typ_543704_839829468, idx0, stars0); { TY535289 LOC71; Ropeobj180006* LOC72; if (!(t0 == NIM_NIL)) goto LA69; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj180006*)0; LOC72 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_26), LOC71, 0); add_180482_2381377266(&result0, LOC72); } goto LA67; LA69: ; { Ropeobj180006* LOC74; LOC74 = (Ropeobj180006*)0; LOC74 = gettypedesc_537673_839829468((*p0).module, t0); add_180482_2381377266(&result0, LOC74); } LA67: ; } LA65: ; } break; default: { NI start0; start0 = i0; { while (1) { if (!(i0 < (pat0 ? pat0->Sup.len : 0))) goto LA77; { if (!!((((NU8)(pat0->data[i0])) == ((NU8)(64)) || ((NU8)(pat0->data[i0])) == ((NU8)(35)) || ((NU8)(pat0->data[i0])) == ((NU8)(39))))) goto LA80; i0 += ((NI) 1); } goto LA78; LA80: ; { goto LA76; } LA78: ; } LA77: ; } LA76: ; { NimStringDesc* LOC87; if (!(start0 <= (NI)(i0 - ((NI) 1)))) goto LA85; LOC87 = (NimStringDesc*)0; LOC87 = copyStrLast(pat0, start0, (NI)(i0 - ((NI) 1))); add_180487_2381377266(&result0, LOC87); } LA85: ; } break; } } LA2: ; } return result0; } N_NIMCALL(void, fixupcall_541410_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0, Ropeobj180006* callee0, Ropeobj180006* params0) { Ropeobj180006* pl0; TY535289 LOC1; Ropeobj180006* LOC2; Ropeobj180006* LOC3; Ttype294840* typ0; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (Ropeobj180006*)0; LOC2 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_118), LOC1, 0); LOC3 = (Ropeobj180006*)0; LOC3 = HEX26_180418_2381377266(callee0, LOC2); pl0 = HEX26_180418_2381377266(LOC3, params0); typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA6; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = isinvalidreturntype_535550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC10) goto LA11; { TY535289 LOC17; Ropeobj180006* LOC18; if (!!((params0 == NIM_NIL))) goto LA15; memset((void*)LOC17, 0, sizeof(LOC17)); LOC18 = (Ropeobj180006*)0; LOC18 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC17, 0); add_180482_2381377266(&pl0, LOC18); } LA15: ; { NIM_BOOL LOC21; NIM_BOOL LOC23; Ropeobj180006* LOC36; TY535289 LOC37; Ropeobj180006* LOC38; LOC21 = (NIM_BOOL)0; LOC21 = ((3 &(1U<<((NU)((*d0).k)&15U)))!=0); if (LOC21) goto LA22; LOC23 = (NIM_BOOL)0; LOC23 = leftappearsonrightside_541329_839829468(le0, ri0); LOC21 = !(LOC23); LA22: ; if (!LOC21) goto LA24; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA28; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } goto LA26; LA28: ; { NIM_BOOL LOC31; NIM_BOOL LOC33; LOC31 = (NIM_BOOL)0; LOC31 = !(((66 &(1U<<((NU)((*d0).k)&15U)))!=0)); if (!(LOC31)) goto LA32; LOC33 = (NIM_BOOL)0; LOC33 = hasnoinit_541383_839829468(ri0); LOC31 = !(LOC33); LA32: ; if (!LOC31) goto LA34; resetloc_540350_839829468(p0, d0); } goto LA26; LA34: ; LA26: ; LOC36 = (Ropeobj180006*)0; LOC36 = addrloc_540204_839829468((&(*d0))); add_180482_2381377266(&pl0, LOC36); memset((void*)LOC37, 0, sizeof(LOC37)); LOC38 = (Ropeobj180006*)0; LOC38 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_505), LOC37, 0); add_180482_2381377266(&pl0, LOC38); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); } goto LA19; LA24: ; { Tloc294816 tmp0; Ropeobj180006* LOC40; TY535289 LOC41; Ropeobj180006* LOC42; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC40 = (Ropeobj180006*)0; LOC40 = addrloc_540204_839829468((&tmp0)); add_180482_2381377266(&pl0, LOC40); memset((void*)LOC41, 0, sizeof(LOC41)); LOC42 = (Ropeobj180006*)0; LOC42 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_505), LOC41, 0); add_180482_2381377266(&pl0, LOC42); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA19: ; } goto LA8; LA11: ; { TY535289 LOC44; Ropeobj180006* LOC45; memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj180006*)0; LOC45 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_117), LOC44, 0); add_180482_2381377266(&pl0, LOC45); { NIM_BOOL LOC48; NIM_BOOL LOC49; LOC48 = (NIM_BOOL)0; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA50: ; LOC48 = LOC49; if (!(LOC48)) goto LA51; LOC48 = (((*d0).flags &(1U<<((NU)(((Tlocflag294810) 8))&15U)))!=0); LA51: ; if (!LOC48) goto LA52; (*d0).k = ((Tlockind294808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag294810) 8)) % (sizeof(NU16)*8))); } goto LA46; LA52: ; { Tloc294816 list0; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA57; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA57: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_534273_839829468((&list0), ((Tlockind294808) 9), (*d0).t, ((Tstorageloc294812) 0)); list0.r = pl0; genassignment_541264_839829468(p0, (&(*d0)), (&list0), 0); } LA46: ; } LA8: ; } goto LA4; LA6: ; { TY535289 LOC60; Ropeobj180006* LOC61; memset((void*)LOC60, 0, sizeof(LOC60)); LOC61 = (Ropeobj180006*)0; LOC61 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_505), LOC60, 0); add_180482_2381377266(&pl0, LOC61); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); } LA4: ; } N_NIMCALL(void, geninfixcall_543929_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0) { Tloc294816 op0; Ttype294840* typ_543940_839829468; NI length0; NimStringDesc* pat0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_541283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); typ_543940_839829468 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_297351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC5; if (!!(!((pat0 == NIM_NIL)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_198185_1689653243(T839829468_498); internalerror_198113_155036129(LOC5); } LA3: ; { NIM_BOOL LOC8; Ropeobj180006* pl0; Ttype294840* typ0; LOC8 = (NIM_BOOL)0; LOC8 = contains_110056_4286263276(pat0, T839829468_500); if (!LOC8) goto LA9; pl0 = genpatterncall_543699_839829468(p0, ri0, pat0, typ_543940_839829468); typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA13; { NIM_BOOL LOC17; NIM_BOOL LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = (((*d0).flags &(1U<<((NU)(((Tlocflag294810) 8))&15U)))!=0); LA20: ; if (!LOC17) goto LA21; (*d0).k = ((Tlockind294808) 9); unsureAsgnRef((void**) (&(*d0).r), pl0); (*d0).flags &= ~(((NU16)1) << ((((Tlocflag294810) 8)) % (sizeof(NU16)*8))); } goto LA15; LA21: ; { Tloc294816 list0; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA26; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA26: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_534273_839829468((&list0), ((Tlockind294808) 9), (*d0).t, ((Tstorageloc294812) 0)); list0.r = pl0; genassignment_541264_839829468(p0, (&(*d0)), (&list0), 0); } LA15: ; } goto LA11; LA13: ; { TY535289 LOC29; Ropeobj180006* LOC30; memset((void*)LOC29, 0, sizeof(LOC29)); LOC30 = (Ropeobj180006*)0; LOC30 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_497), LOC29, 0); add_180482_2381377266(&pl0, LOC30); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); } LA11: ; } goto LA6; LA9: ; { Ropeobj180006* pl0; Ropeobj180006* params0; pl0 = NIM_NIL; { NI LOC34; Ropeobj180006* LOC37; LOC34 = (NI)0; LOC34 = len_295081_850551059(ri0); if (!(((NI) 1) < LOC34)) goto LA35; LOC37 = (Ropeobj180006*)0; LOC37 = genthisarg_543475_839829468(p0, ri0, ((NI) 1), typ_543940_839829468); add_180482_2381377266(&pl0, LOC37); } LA35: ; add_180482_2381377266(&pl0, op0.r); params0 = (Ropeobj180006*)0; { NI i_544425_839829468; NI HEX3Atmp_544609_839829468; NI res_544612_839829468; i_544425_839829468 = (NI)0; HEX3Atmp_544609_839829468 = (NI)0; HEX3Atmp_544609_839829468 = (NI)(length0 - ((NI) 1)); res_544612_839829468 = ((NI) 2); { while (1) { Ropeobj180006* LOC47; if (!(res_544612_839829468 <= HEX3Atmp_544609_839829468)) goto LA40; i_544425_839829468 = res_544612_839829468; { TY535289 LOC45; Ropeobj180006* LOC46; if (!!((params0 == NIM_NIL))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (Ropeobj180006*)0; LOC46 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC45, 0); add_180482_2381377266(&params0, LOC46); } LA43: ; LOC47 = (Ropeobj180006*)0; LOC47 = genotherarg_541277_839829468(p0, ri0, i_544425_839829468, typ_543940_839829468); add_180482_2381377266(&params0, LOC47); res_544612_839829468 += ((NI) 1); } LA40: ; } } fixupcall_541410_839829468(p0, le0, ri0, d0, pl0, params0); } LA6: ; } N_NIMCALL(void, gennamedparamcall_544616_839829468)(Tcproc531021* p0, Tnode294802* ri0, Tloc294816* d0) { Tloc294816 op0; Ropeobj180006* pl0; TY535289 LOC1; Ttype294840* typ0; NI length0; NimStringDesc* pat0; NI start0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_541283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); memset((void*)LOC1, 0, sizeof(LOC1)); pl0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_506), LOC1, 0); typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_297351_850551059(ri0); pat0 = (*(*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).loc.r).data; { NimStringDesc* LOC6; if (!!(!((pat0 == NIM_NIL)))) goto LA4; LOC6 = (NimStringDesc*)0; LOC6 = HEX24_198185_1689653243(T839829468_507); internalerror_198113_155036129(LOC6); } LA4: ; start0 = ((NI) 3); { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = contains_110046_4286263276(pat0, 32); if (!LOC9) goto LA10; start0 = ((NI) 1); add_180482_2381377266(&pl0, op0.r); { TY535289 LOC16; Ropeobj180006* LOC17; Ropeobj180006* LOC18; if (!(((NI) 1) < length0)) goto LA14; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (Ropeobj180006*)0; LOC17 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_244), LOC16, 0); add_180482_2381377266(&pl0, LOC17); LOC18 = (Ropeobj180006*)0; LOC18 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_180482_2381377266(&pl0, LOC18); start0 = ((NI) 2); } LA14: ; } goto LA7; LA10: ; { { Ropeobj180006* LOC24; TY535289 LOC25; Ropeobj180006* LOC26; if (!(((NI) 1) < length0)) goto LA22; LOC24 = (Ropeobj180006*)0; LOC24 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 1)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym, ri0); add_180482_2381377266(&pl0, LOC24); memset((void*)LOC25, 0, sizeof(LOC25)); LOC26 = (Ropeobj180006*)0; LOC26 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_111), LOC25, 0); add_180482_2381377266(&pl0, LOC26); } LA22: ; add_180482_2381377266(&pl0, op0.r); { TY535289 LOC31; Ropeobj180006* LOC32; Ropeobj180006* LOC33; if (!(((NI) 2) < length0)) goto LA29; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_244), LOC31, 0); add_180482_2381377266(&pl0, LOC32); LOC33 = (Ropeobj180006*)0; LOC33 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 2)], (*(*(*typ0).n).kindU.S6.sons->data[((NI) 2)]).kindU.S4.sym, ri0); add_180482_2381377266(&pl0, LOC33); } LA29: ; } LA7: ; { NI i_545051_839829468; NI HEX3Atmp_545617_839829468; NI res_545620_839829468; i_545051_839829468 = (NI)0; HEX3Atmp_545617_839829468 = (NI)0; HEX3Atmp_545617_839829468 = (NI)(length0 - ((NI) 1)); res_545620_839829468 = start0; { while (1) { Tsym294834* param0; TY535289 LOC42; Ropeobj180006* LOC43; TY535289 LOC44; Ropeobj180006* LOC45; Ropeobj180006* LOC46; if (!(res_545620_839829468 <= HEX3Atmp_545617_839829468)) goto LA36; i_545051_839829468 = res_545620_839829468; { NI LOC39; LOC39 = (NI)0; LOC39 = sonslen_297327_850551059(typ0); if (!(LOC39 <= i_545051_839829468)) goto LA40; internalerror_198100_155036129((*ri0).info, ((NimStringDesc*) &T839829468_508)); } LA40: ; param0 = (*(*(*typ0).n).kindU.S6.sons->data[i_545051_839829468]).kindU.S4.sym; memset((void*)LOC42, 0, sizeof(LOC42)); LOC43 = (Ropeobj180006*)0; LOC43 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_111), LOC42, 0); add_180482_2381377266(&pl0, LOC43); add_180487_2381377266(&pl0, (*(*param0).name).s); memset((void*)LOC44, 0, sizeof(LOC44)); LOC45 = (Ropeobj180006*)0; LOC45 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_244), LOC44, 0); add_180482_2381377266(&pl0, LOC45); LOC46 = (Ropeobj180006*)0; LOC46 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[i_545051_839829468], param0, ri0); add_180482_2381377266(&pl0, LOC46); res_545620_839829468 += ((NI) 1); } LA36: ; } } { if (!!(((*typ0).sons->data[((NI) 0)] == NIM_NIL))) goto LA49; { NIM_BOOL LOC53; LOC53 = (NIM_BOOL)0; LOC53 = isinvalidreturntype_535550_839829468((*typ0).sons->data[((NI) 0)]); if (!LOC53) goto LA54; { NI LOC58; TY535289 LOC61; Ropeobj180006* LOC62; LOC58 = (NI)0; LOC58 = sonslen_297351_850551059(ri0); if (!(((NI) 1) < LOC58)) goto LA59; memset((void*)LOC61, 0, sizeof(LOC61)); LOC62 = (Ropeobj180006*)0; LOC62 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_111), LOC61, 0); add_180482_2381377266(&pl0, LOC62); } LA59: ; { TY535289 LOC71; Ropeobj180006* LOC72; Ropeobj180006* LOC73; TY535289 LOC74; Ropeobj180006* LOC75; if (!((3 &(1U<<((NU)((*d0).k)&15U)))!=0)) goto LA65; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA69; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_TRUE); } LA69: ; memset((void*)LOC71, 0, sizeof(LOC71)); LOC72 = (Ropeobj180006*)0; LOC72 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_509), LOC71, 0); add_180482_2381377266(&pl0, LOC72); LOC73 = (Ropeobj180006*)0; LOC73 = addrloc_540204_839829468((&(*d0))); add_180482_2381377266(&pl0, LOC73); memset((void*)LOC74, 0, sizeof(LOC74)); LOC75 = (Ropeobj180006*)0; LOC75 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_510), LOC74, 0); add_180482_2381377266(&pl0, LOC75); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); } goto LA63; LA65: ; { Tloc294816 tmp0; Ropeobj180006* LOC77; TY535289 LOC78; Ropeobj180006* LOC79; memset((void*)(&tmp0), 0, sizeof(tmp0)); gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], (&tmp0), NIM_TRUE); LOC77 = (Ropeobj180006*)0; LOC77 = addrloc_540204_839829468((&tmp0)); add_180482_2381377266(&pl0, LOC77); memset((void*)LOC78, 0, sizeof(LOC78)); LOC79 = (Ropeobj180006*)0; LOC79 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_510), LOC78, 0); add_180482_2381377266(&pl0, LOC79); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA63: ; } goto LA51; LA54: ; { TY535289 LOC81; Ropeobj180006* LOC82; Tloc294816 list0; memset((void*)LOC81, 0, sizeof(LOC81)); LOC82 = (Ropeobj180006*)0; LOC82 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_511), LOC81, 0); add_180482_2381377266(&pl0, LOC82); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA85; gettemp_539032_839829468(p0, (*typ0).sons->data[((NI) 0)], d0, NIM_FALSE); } LA85: ; memset((void*)(&list0), 0, sizeof(list0)); initloc_534273_839829468((&list0), ((Tlockind294808) 9), NIM_NIL, ((Tstorageloc294812) 0)); list0.r = pl0; genassignment_541264_839829468(p0, (&(*d0)), (&list0), 0); } LA51: ; } goto LA47; LA49: ; { TY535289 LOC88; Ropeobj180006* LOC89; memset((void*)LOC88, 0, sizeof(LOC88)); LOC89 = (Ropeobj180006*)0; LOC89 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_510), LOC88, 0); add_180482_2381377266(&pl0, LOC89); line_534690_839829468(p0, ((Tcprocsection531011) 2), pl0); } LA47: ; } N_NIMCALL(void, genprefixcall_541960_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0) { Tloc294816 op0; Ropeobj180006* params0; Ttype294840* typ0; NI length0; memset((void*)(&op0), 0, sizeof(op0)); initlocexpr_541283_839829468(p0, (*ri0).kindU.S6.sons->data[((NI) 0)], (&op0)); params0 = (Ropeobj180006*)0; typ0 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); length0 = sonslen_297351_850551059(ri0); { NI i_542213_839829468; NI HEX3Atmp_542445_839829468; NI res_542448_839829468; i_542213_839829468 = (NI)0; HEX3Atmp_542445_839829468 = (NI)0; HEX3Atmp_542445_839829468 = (NI)(length0 - ((NI) 1)); res_542448_839829468 = ((NI) 1); { while (1) { if (!(res_542448_839829468 <= HEX3Atmp_542445_839829468)) goto LA3; i_542213_839829468 = res_542448_839829468; { NI LOC6; Tnode294802* paramtype0; LOC6 = (NI)0; LOC6 = sonslen_297327_850551059(typ0); if (!(i_542213_839829468 < LOC6)) goto LA7; paramtype0 = (*(*typ0).n).kindU.S6.sons->data[i_542213_839829468]; { NIM_BOOL LOC11; Ropeobj180006* LOC20; LOC11 = (NIM_BOOL)0; LOC11 = iscompiletimeonly_330706_3876443242((*paramtype0).typ); if (!!(LOC11)) goto LA12; { TY535289 LOC18; Ropeobj180006* LOC19; if (!!((params0 == NIM_NIL))) goto LA16; memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (Ropeobj180006*)0; LOC19 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC18, 0); add_180482_2381377266(&params0, LOC19); } LA16: ; LOC20 = (Ropeobj180006*)0; LOC20 = genarg_541787_839829468(p0, (*ri0).kindU.S6.sons->data[i_542213_839829468], (*paramtype0).kindU.S4.sym, ri0); add_180482_2381377266(&params0, LOC20); } LA12: ; } goto LA4; LA7: ; { Ropeobj180006* LOC28; { TY535289 LOC26; Ropeobj180006* LOC27; if (!!((params0 == NIM_NIL))) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC27 = (Ropeobj180006*)0; LOC27 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC26, 0); add_180482_2381377266(&params0, LOC27); } LA24: ; LOC28 = (Ropeobj180006*)0; LOC28 = genargnoparam_541938_839829468(p0, (*ri0).kindU.S6.sons->data[i_542213_839829468]); add_180482_2381377266(&params0, LOC28); } LA4: ; res_542448_839829468 += ((NI) 1); } LA3: ; } } fixupcall_541410_839829468(p0, le0, ri0, d0, op0.r, params0); } static N_INLINE(void, poststmtactions_534942_839829468)(Tcproc531021* p0) { Ropeobj180006** LOC1; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC1, (*(*p0).module).injectstmt); } N_NIMCALL(void, gencall_545632_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { { Ttype294840* LOC3; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention294002) 8))) goto LA4; genclosurecall_542452_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_543929_839829468(p0, NIM_NIL, e0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_544616_839829468(p0, e0, d0); } goto LA1; LA14: ; { genprefixcall_541960_839829468(p0, NIM_NIL, e0, d0); } LA1: ; poststmtactions_534942_839829468(p0); } N_NIMCALL(void, genreset_556731_839829468)(Tcproc531021* p0, Tnode294802* n0) { Tloc294816 a0; TY534811 LOC1; Ttype294840* LOC2; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = addrloc_540204_839829468((&a0)); LOC2 = (Ttype294840*)0; LOC2 = skiptypes_298099_850551059(a0.t, IL64(211106242013440)); LOC1[1] = gentypeinfo_537941_839829468((*p0).module, LOC2); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_496), LOC1, 2); } N_NIMCALL(void, genecho_556369_839829468)(Tcproc531021* p0, Tnode294802* n0) { NIM_BOOL LOC6; Ropeobj180006* args0; Tloc294816 a0; TY534811 LOC18; NimStringDesc* LOC19; NI LOC20; NimStringDesc* LOC21; TY535289 LOC22; { NimStringDesc* LOC5; if (!!(((*n0).kind == ((Tnodekind294020) 41)))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_198185_1689653243(T839829468_512); internalerror_198113_155036129(LOC5); } LA3: ; LOC6 = (NIM_BOOL)0; LOC6 = includestr_148249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_513)); args0 = NIM_NIL; memset((void*)(&a0), 0, sizeof(a0)); { NI i_556404_839829468; NI HEX3Atmp_556431_839829468; NI LOC8; NI res_556434_839829468; i_556404_839829468 = (NI)0; HEX3Atmp_556431_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_295081_850551059(n0); HEX3Atmp_556431_839829468 = (NI)(LOC8 - ((NI) 1)); res_556434_839829468 = ((NI) 0); { while (1) { if (!(res_556434_839829468 <= HEX3Atmp_556431_839829468)) goto LA10; i_556404_839829468 = res_556434_839829468; { Tnode294802* LOC13; LOC13 = (Tnode294802*)0; LOC13 = skipconv_330882_3876443242((*n0).kindU.S6.sons->data[i_556404_839829468]); if (!((*LOC13).kind == ((Tnodekind294020) 23))) goto LA14; add_180487_2381377266(&args0, ((NimStringDesc*) &T839829468_514)); } goto LA11; LA14: ; { TY180507 LOC17; initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[i_556404_839829468], (&a0)); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rdloc_540188_839829468((&a0)); addf_181205_2381377266(&args0, ((NimStringDesc*) &T839829468_515), LOC17, 1); } LA11: ; res_556434_839829468 += ((NI) 1); } LA10: ; } } memset((void*)LOC18, 0, sizeof(LOC18)); LOC19 = (NimStringDesc*)0; LOC20 = (NI)0; LOC20 = len_295081_850551059(n0); LOC21 = (NimStringDesc*)0; LOC21 = nsuRepeatStr(((NimStringDesc*) &T839829468_517), ((NI) (LOC20))); LOC19 = rawNewString(LOC21->Sup.len + tnl_178644_4151366050->Sup.len + 0); appendString(LOC19, LOC21); appendString(LOC19, tnl_178644_4151366050); LOC18[0] = makecstring_193638_155036129(LOC19); LOC18[1] = args0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_516), LOC18, 2); memset((void*)LOC22, 0, sizeof(LOC22)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_518), LOC22, 0); } N_NIMCALL(void, genseqconstr_557004_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { Tloc294816 arr0; NI LOC5; Ropeobj180006* LOC6; memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA3; gettemp_539032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA3: ; LOC5 = (NI)0; LOC5 = sonslen_297351_850551059(t0); LOC6 = (Ropeobj180006*)0; LOC6 = intliteral_541270_839829468(((NI64) (LOC5))); gennewseqaux_556795_839829468(p0, (&(*d0)), LOC6); { NI i_557031_839829468; NI HEX3Atmp_557039_839829468; NI LOC8; NI res_557042_839829468; i_557031_839829468 = (NI)0; HEX3Atmp_557039_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = sonslen_297351_850551059(t0); HEX3Atmp_557039_839829468 = (NI)(LOC8 - ((NI) 1)); res_557042_839829468 = ((NI) 0); { while (1) { Ttype294840* LOC11; Ttype294840* LOC12; TY534811 LOC13; if (!(res_557042_839829468 <= HEX3Atmp_557039_839829468)) goto LA10; i_557031_839829468 = res_557042_839829468; LOC11 = (Ttype294840*)0; LOC11 = skiptypes_298099_850551059((*t0).typ, IL64(211106232576256)); LOC12 = (Ttype294840*)0; LOC12 = elemtype_322394_3876443242(LOC11); initloc_534273_839829468((&arr0), ((Tlockind294808) 6), LOC12, ((Tstorageloc294812) 3)); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_540188_839829468((&(*d0))); LOC13[1] = intliteral_541270_839829468(((NI64) (i_557031_839829468))); arr0.r = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC13, 2); arr0.s = ((Tstorageloc294812) 3); expr_541248_839829468(p0, (*t0).kindU.S6.sons->data[i_557031_839829468], (&arr0)); res_557042_839829468 += ((NI) 1); } LA10: ; } } gcusage_556439_839829468(t0); } N_NIMCALL(void, genarrtoseq_557046_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { Tloc294816 elem0; Tloc294816 a0; Tloc294816 arr0; NI L0; NI64 LOC9; Ropeobj180006* LOC10; { memset((void*)(&elem0), 0, sizeof(elem0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&arr0), 0, sizeof(arr0)); { if (!((*t0).kind == ((Tnodekind294020) 41))) goto LA3; asgnRefNoCycle((void**) (&(*(*t0).kindU.S6.sons->data[((NI) 1)]).typ), (*t0).typ); genseqconstr_557004_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], d0); goto BeforeRet; } LA3: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA7; gettemp_539032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA7: ; LOC9 = (NI64)0; LOC9 = lengthord_322007_3876443242((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ); L0 = ((NI) (LOC9)); LOC10 = (Ropeobj180006*)0; LOC10 = intliteral_541270_839829468(((NI64) (L0))); gennewseqaux_556795_839829468(p0, (&(*d0)), LOC10); initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], (&a0)); { NI i_557090_839829468; NI HEX3Atmp_557104_839829468; NI res_557107_839829468; i_557090_839829468 = (NI)0; HEX3Atmp_557104_839829468 = (NI)0; HEX3Atmp_557104_839829468 = (NI)(L0 - ((NI) 1)); res_557107_839829468 = ((NI) 0); { while (1) { Ttype294840* LOC14; Ttype294840* LOC15; TY534811 LOC16; Ttype294840* LOC17; Ttype294840* LOC18; TY534811 LOC19; if (!(res_557107_839829468 <= HEX3Atmp_557104_839829468)) goto LA13; i_557090_839829468 = res_557107_839829468; LOC14 = (Ttype294840*)0; LOC14 = skiptypes_298099_850551059((*t0).typ, IL64(211106232576256)); LOC15 = (Ttype294840*)0; LOC15 = elemtype_322394_3876443242(LOC14); initloc_534273_839829468((&elem0), ((Tlockind294808) 6), LOC15, ((Tstorageloc294812) 3)); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468((&(*d0))); LOC16[1] = intliteral_541270_839829468(((NI64) (i_557090_839829468))); elem0.r = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC16, 2); elem0.s = ((Tstorageloc294812) 3); LOC17 = (Ttype294840*)0; LOC17 = skiptypes_298099_850551059((*(*t0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106232576256)); LOC18 = (Ttype294840*)0; LOC18 = elemtype_322394_3876443242(LOC17); initloc_534273_839829468((&arr0), ((Tlockind294808) 6), LOC18, a0.s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_540188_839829468((&a0)); LOC19[1] = intliteral_541270_839829468(((NI64) (i_557090_839829468))); arr0.r = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC19, 2); genassignment_541264_839829468(p0, (&elem0), (&arr0), 3); res_557107_839829468 += ((NI) 1); } LA13: ; } } }BeforeRet: ; } N_NIMCALL(void, gendeepcopy_552374_839829468)(Tcproc531021* p0, Tloc294816* dest0, Tloc294816* src0) { Ttype294840* ty0; ty0 = skiptypes_298099_850551059((*dest0).t, IL64(211106242013440)); switch ((*ty0).kind) { case ((Ttypekind294244) 21): case ((Ttypekind294244) 22): case ((Ttypekind294244) 25): case ((Ttypekind294244) 18): case ((Ttypekind294244) 17): case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { TY537238 LOC2; memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = addrloc_540204_839829468(dest0); LOC2[1] = addrloc_540204_839829468(src0); LOC2[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_519), LOC2, 3); } break; case ((Ttypekind294244) 24): case ((Ttypekind294244) 28): { TY537238 LOC4; memset((void*)LOC4, 0, sizeof(LOC4)); LOC4[0] = addrloc_540204_839829468(dest0); LOC4[1] = rdloc_540188_839829468(src0); LOC4[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_520), LOC4, 3); } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { TY537238 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = addrloc_540204_839829468(dest0); LOC6[1] = addrloc_540204_839829468(src0); LOC6[2] = gentypeinfo_537941_839829468((*p0).module, (*dest0).t); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_521), LOC6, 3); } break; case ((Ttypekind294244) 19): { { Tctypekind531007 LOC10; TY537238 LOC13; NI64 LOC14; LOC10 = (Tctypekind531007)0; LOC10 = maptype_535394_839829468(ty0); if (!(LOC10 == ((Tctypekind531007) 17))) goto LA11; usestringh_534345_839829468((*p0).module); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = rdloc_540188_839829468(dest0); LOC13[1] = rdloc_540188_839829468(src0); LOC14 = (NI64)0; LOC14 = getsize_322135_3876443242((*dest0).t); LOC13[2] = rope_180401_2381377266(LOC14); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_268), LOC13, 3); } goto LA8; LA11: ; { TY534811 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468(dest0); LOC16[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC16, 2); } LA8: ; } break; case ((Ttypekind294244) 26): case ((Ttypekind294244) 2): case ((Ttypekind294244) 1): case ((Ttypekind294244) 14): case ((Ttypekind294244) 29): case ((Ttypekind294244) 31) ... ((Ttypekind294244) 44): case ((Ttypekind294244) 20): case ((Ttypekind294244) 23): { TY534811 LOC18; memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rdloc_540188_839829468(dest0); LOC18[1] = rdloc_540188_839829468(src0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_123), LOC18, 2); } break; default: { NimStringDesc* LOC20; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI294244))->Sup.len + 13); appendString(LOC20, ((NimStringDesc*) &T839829468_522)); appendString(LOC20, reprEnum((NI)(*ty0).kind, (&NTI294244))); internalerror_198113_155036129(LOC20); } break; } } N_NIMCALL(void, genmagicexpr_559033_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tmagic294524 op0) { switch (op0) { case ((Tmagic294524) 127): case ((Tmagic294524) 126): { genandor_556311_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 99) ... ((Tmagic294524) 117): { unaryarith_554646_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 96) ... ((Tmagic294524) 98): { unaryarithoverflow_553633_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 52) ... ((Tmagic294524) 55): { binaryfloatarith_558729_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 56) ... ((Tmagic294524) 93): { binaryarith_553819_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 95): { geneqproc_554214_839829468(p0, e0, d0); } break; case ((Tmagic294524) 45) ... ((Tmagic294524) 51): { binaryarithoverflow_553262_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 149): { genrepr_557339_839829468(p0, e0, d0); } break; case ((Tmagic294524) 259): { gengettypeinfo_557383_839829468(p0, e0, d0); } break; case ((Tmagic294524) 156): { genswap_557638_839829468(p0, e0, d0); } break; case ((Tmagic294524) 25): { { if (!!((((*p0).options &(1U<<((NU)(((Toption171009) 5))&31U)))!=0))) goto LA14; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_385)); } goto LA12; LA14: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_386)); } LA12: ; } break; case ((Tmagic294524) 26): case ((Tmagic294524) 27): { Ttype294840* underlying0; underlying0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 9439232); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = !((((*p0).options &(1U<<((NU)(((Toption171009) 5))&31U)))!=0)); if (LOC20) goto LA21; LOC20 = ((IL64(34084860461056) &((NU64)1<<((NU)((*underlying0).kind)&63U)))!=0); LA21: ; if (!LOC20) goto LA22; binarystmt_552501_839829468(p0, e0, d0, opr_559050_839829468[(op0)- 26]); } goto LA18; LA22: ; { Tloc294816 a0; Tloc294816 b0; Ttype294840* ranged0; Ropeobj180006* res0; NimStringDesc* LOC25; TY534811 LOC31; Ropeobj180006* LOC32; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); ranged0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 8390656); LOC25 = (NimStringDesc*)0; { if (!((*underlying0).kind == ((Ttypekind294244) 35))) goto LA28; LOC25 = copyString(fun64_559055_839829468[(op0)- 26]); } goto LA26; LA28: ; { LOC25 = copyString(fun_559060_839829468[(op0)- 26]); } LA26: ; res0 = binaryarithoverflowraw_553235_839829468(p0, ranged0, (&a0), (&b0), LOC25); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = gettypedesc_537673_839829468((*p0).module, ranged0); LOC31[1] = res0; LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_370), LOC31, 2); putintodest_552468_839829468(p0, (&a0), ranged0, LOC32, ((Tstorageloc294812) 0)); } LA18: ; } break; case ((Tmagic294524) 138): { genstrconcat_556452_839829468(p0, e0, d0); } break; case ((Tmagic294524) 144): { binarystmt_552501_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_394)); } break; case ((Tmagic294524) 145): { genstrappend_556554_839829468(p0, e0, d0); } break; case ((Tmagic294524) 146): { genseqelemappend_556683_839829468(p0, e0, d0); } break; case ((Tmagic294524) 128): { genstrequals_558667_839829468(p0, e0, d0); } break; case ((Tmagic294524) 129): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_402)); } break; case ((Tmagic294524) 130): { binaryexpr_552549_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_403)); } break; case ((Tmagic294524) 157): { genisnil_554620_839829468(p0, e0, d0); } break; case ((Tmagic294524) 120): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_406)); } break; case ((Tmagic294524) 121): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_407)); } break; case ((Tmagic294524) 119): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_408)); } break; case ((Tmagic294524) 118): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_409)); } break; case ((Tmagic294524) 122): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_410)); } break; case ((Tmagic294524) 123): { gendollar_557391_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_411)); } break; case ((Tmagic294524) 124): { expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Tmagic294524) 125): { genrepr_557339_839829468(p0, e0, d0); } break; case ((Tmagic294524) 12): { genof_557331_839829468(p0, e0, d0); } break; case ((Tmagic294524) 29): { gennew_556782_839829468(p0, e0); } break; case ((Tmagic294524) 30): { gennewfinalize_557111_839829468(p0, e0); } break; case ((Tmagic294524) 31): { gennewseq_556824_839829468(p0, e0); } break; case ((Tmagic294524) 32): { gennewseqofcap_556836_839829468(p0, e0, d0); } break; case ((Tmagic294524) 9): { Ttype294840* t0; TY180507 LOC55; Ropeobj180006* LOC56; t0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, 256); memset((void*)LOC55, 0, sizeof(LOC55)); LOC55[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC56 = (Ropeobj180006*)0; LOC56 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_428), LOC55, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC56, ((Tstorageloc294812) 0)); } break; case ((Tmagic294524) 42): { gensomecast_558481_839829468(p0, e0, d0); } break; case ((Tmagic294524) 28): { genord_558475_839829468(p0, e0, d0); } break; case ((Tmagic294524) 35): case ((Tmagic294524) 8): case ((Tmagic294524) 34): case ((Tmagic294524) 36): case ((Tmagic294524) 33): { genarraylen_557415_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 37): case ((Tmagic294524) 38): { { NIM_BOOL LOC63; LOC63 = (NIM_BOOL)0; LOC63 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC63) goto LA64; LOC63 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA64: ; if (!!(LOC63)) goto LA65; unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_440)); } goto LA61; LA65: ; { unaryexpr_553209_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_441)); } LA61: ; } break; case ((Tmagic294524) 43): { unarystmt_552527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_443)); } break; case ((Tmagic294524) 44): { unarystmt_552527_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_444)); } break; case ((Tmagic294524) 151): { gensetlengthstr_557632_839829468(p0, e0, d0); } break; case ((Tmagic294524) 152): { gensetlengthseq_557500_839829468(p0, e0, d0); } break; case ((Tmagic294524) 39): case ((Tmagic294524) 40): case ((Tmagic294524) 41): case ((Tmagic294524) 133): case ((Tmagic294524) 132): case ((Tmagic294524) 131): case ((Tmagic294524) 134): case ((Tmagic294524) 135): case ((Tmagic294524) 136): case ((Tmagic294524) 148): { gensetop_558419_839829468(p0, e0, d0, op0); } break; case ((Tmagic294524) 161): case ((Tmagic294524) 162): case ((Tmagic294524) 159): case ((Tmagic294524) 160): case ((Tmagic294524) 150): case ((Tmagic294524) 163): { Tsym294834* opr0; opr0 = (*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NimStringDesc* LOC78; Ropeobj180006* LOC79; if (!!((((*opr0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0))) goto LA76; LOC78 = (NimStringDesc*)0; LOC78 = HEX24_180856_2381377266((*opr0).loc.r); LOC79 = (Ropeobj180006*)0; LOC79 = cgsym_534403_839829468((*p0).module, LOC78); } LA76: ; gencall_545632_839829468(p0, e0, d0); } break; case ((Tmagic294524) 164): { genreset_556731_839829468(p0, e0); } break; case ((Tmagic294524) 17): { Tnode294802* LOC82; Tnode294802* LOC83; LOC82 = (Tnode294802*)0; LOC82 = HEX5BHEX5D_295238_850551059(e0, ((NI) 1)); LOC83 = (Tnode294802*)0; LOC83 = skipconv_330882_3876443242(LOC82); genecho_556369_839829468(p0, LOC83); } break; case ((Tmagic294524) 158): { genarrtoseq_557046_839829468(p0, e0, d0); } break; case ((Tmagic294524) 223) ... ((Tmagic294524) 257): case ((Tmagic294524) 19) ... ((Tmagic294524) 24): { localerror_198080_155036129((*e0).info, ((Tmsgkind193002) 229), (*(*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).name).s); } break; case ((Tmagic294524) 208): { Tnode294802* n0; n0 = wrapprocforspawn_437501_2218250499((*(*p0).module).module, e0, (*e0).typ, NIM_NIL, NIM_NIL); expr_541248_839829468(p0, n0, d0); } break; case ((Tmagic294524) 155): { Tnode294802* n0; n0 = liftparallel_480822_1773027539((*(*p0).module).module, e0); expr_541248_839829468(p0, n0, d0); } break; case ((Tmagic294524) 209): { Tloc294816 a0; Tloc294816 b0; Tnode294802* x0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); { Tnode294802* LOC91; Tnode294802* LOC94; LOC91 = (Tnode294802*)0; LOC91 = HEX5BHEX5D_295238_850551059(e0, ((NI) 1)); if (!((*LOC91).kind == ((Tnodekind294020) 63) || (*LOC91).kind == ((Tnodekind294020) 64))) goto LA92; LOC94 = (Tnode294802*)0; LOC94 = HEX5BHEX5D_295238_850551059(e0, ((NI) 1)); x0 = HEX5BHEX5D_295238_850551059(LOC94, ((NI) 0)); } goto LA89; LA92: ; { x0 = HEX5BHEX5D_295238_850551059(e0, ((NI) 1)); } LA89: ; initlocexpr_541283_839829468(p0, x0, (&a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 2)], (&b0)); gendeepcopy_552374_839829468(p0, (&a0), (&b0)); } break; case ((Tmagic294524) 140): case ((Tmagic294524) 94): { gencall_545632_839829468(p0, e0, d0); } break; default: { NimStringDesc* LOC98; LOC98 = (NimStringDesc*)0; LOC98 = rawNewString(reprEnum((NI)op0, (&NTI294524))->Sup.len + 14); appendString(LOC98, ((NimStringDesc*) &T839829468_523)); appendString(LOC98, reprEnum((NI)op0, (&NTI294524))); internalerror_198100_155036129((*e0).info, LOC98); } break; } } N_NIMCALL(Ropeobj180006*, gensetnode_551664_839829468)(Tcproc531021* p0, Tnode294802* n0) { Ropeobj180006* result0; Tbitset341004* cs0; NI size0; NI64 LOC1; result0 = (Ropeobj180006*)0; cs0 = (Tbitset341004*)0; LOC1 = (NI64)0; LOC1 = getsize_322135_3876443242((*n0).typ); size0 = ((NI) (LOC1)); tobitset_342001_452470228(n0, (&cs0)); { NI id0; Ropeobj180006* LOC6; if (!(((NI) 8) < size0)) goto LA4; id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC6 = (Ropeobj180006*)0; LOC6 = rope_180401_2381377266(((NI64) (id0))); result0 = HEX26_180418_2381377266((*(*p0).module).tmpbase, LOC6); { TY537238 LOC11; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA9; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_537673_839829468((*p0).module, (*n0).typ); LOC11[1] = result0; LOC11[2] = genrawsetdata_551629_839829468(cs0, size0); addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC11, 3); } LA9: ; } goto LA2; LA4: ; { result0 = genrawsetdata_551629_839829468(cs0, size0); } LA2: ; return result0; } N_NIMCALL(void, gensetconstr_559496_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Tloc294816 idx0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); memset((void*)(&idx0), 0, sizeof(idx0)); { Ropeobj180006* LOC5; if (!(((*e0).flags &(1U<<((NU)(((Tnodeflag294427) 4))&15U)))!=0)) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = gensetnode_551664_839829468(p0, e0); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC5, ((Tstorageloc294812) 0)); } goto LA1; LA3: ; { { if (!((*d0).k == ((Tlockind294808) 0))) goto LA9; gettemp_539032_839829468(p0, (*e0).typ, d0, NIM_FALSE); } LA9: ; { NI64 LOC13; TY180507 LOC16; LOC13 = (NI64)0; LOC13 = getsize_322135_3876443242((*e0).typ); if (!(IL64(8) < LOC13)) goto LA14; usestringh_534345_839829468((*p0).module); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468((&(*d0))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_525), LOC16, 1); { NI i_559537_839829468; NI HEX3Atmp_559603_839829468; NI LOC18; NI res_559606_839829468; i_559537_839829468 = (NI)0; HEX3Atmp_559603_839829468 = (NI)0; LOC18 = (NI)0; LOC18 = sonslen_297351_850551059(e0); HEX3Atmp_559603_839829468 = (NI)(LOC18 - ((NI) 1)); res_559606_839829468 = ((NI) 0); { while (1) { if (!(res_559606_839829468 <= HEX3Atmp_559603_839829468)) goto LA20; i_559537_839829468 = res_559606_839829468; { Ttype294840* LOC25; TY537235 LOC26; if (!((*(*e0).kindU.S6.sons->data[i_559537_839829468]).kind == ((Tnodekind294020) 44))) goto LA23; LOC25 = (Ttype294840*)0; LOC25 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC25, (&idx0), NIM_FALSE); initlocexpr_541283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_559537_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_541283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_559537_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_540188_839829468((&idx0)); LOC26[1] = rdloc_540188_839829468((&(*d0))); LOC26[2] = rdsetelemloc_557662_839829468((&a0), (*e0).typ); LOC26[3] = rdsetelemloc_557662_839829468((&b0), (*e0).typ); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_526), LOC26, 4); } goto LA21; LA23: ; { TY534811 LOC28; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[i_559537_839829468], (&a0)); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = rdloc_540188_839829468((&(*d0))); LOC28[1] = rdsetelemloc_557662_839829468((&a0), (*e0).typ); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_527), LOC28, 2); } LA21: ; res_559606_839829468 += ((NI) 1); } LA20: ; } } } goto LA11; LA14: ; { NimStringDesc* ts0; NimStringDesc* LOC30; NI64 LOC31; NimStringDesc* LOC32; TY180507 LOC33; LOC30 = (NimStringDesc*)0; LOC31 = (NI64)0; LOC31 = getsize_322135_3876443242((*e0).typ); LOC32 = (NimStringDesc*)0; LOC32 = nimInt64ToStr((NI64)(LOC31 * IL64(8))); LOC30 = rawNewString(LOC32->Sup.len + 2); appendString(LOC30, ((NimStringDesc*) &T839829468_45)); appendString(LOC30, LOC32); ts0 = LOC30; memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rdloc_540188_839829468((&(*d0))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_494), LOC33, 1); { NI i_559575_839829468; NI HEX3Atmp_559611_839829468; NI LOC35; NI res_559614_839829468; i_559575_839829468 = (NI)0; HEX3Atmp_559611_839829468 = (NI)0; LOC35 = (NI)0; LOC35 = sonslen_297351_850551059(e0); HEX3Atmp_559611_839829468 = (NI)(LOC35 - ((NI) 1)); res_559614_839829468 = ((NI) 0); { while (1) { if (!(res_559614_839829468 <= HEX3Atmp_559611_839829468)) goto LA37; i_559575_839829468 = res_559614_839829468; { Ttype294840* LOC42; NimStringDesc* LOC43; TY537235 LOC44; if (!((*(*e0).kindU.S6.sons->data[i_559575_839829468]).kind == ((Tnodekind294020) 44))) goto LA40; LOC42 = (Ttype294840*)0; LOC42 = getsystype_340150_3937434831(((Ttypekind294244) 31)); gettemp_539032_839829468(p0, LOC42, (&idx0), NIM_FALSE); initlocexpr_541283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_559575_839829468]).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_541283_839829468(p0, (*(*e0).kindU.S6.sons->data[i_559575_839829468]).kindU.S6.sons->data[((NI) 1)], (&b0)); LOC43 = (NimStringDesc*)0; LOC43 = rawNewString(ts0->Sup.len + ts0->Sup.len + 68); appendString(LOC43, ((NimStringDesc*) &T839829468_528)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_529)); appendString(LOC43, ts0); appendString(LOC43, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC44, 0, sizeof(LOC44)); LOC44[0] = rdloc_540188_839829468((&idx0)); LOC44[1] = rdloc_540188_839829468((&(*d0))); LOC44[2] = rdsetelemloc_557662_839829468((&a0), (*e0).typ); LOC44[3] = rdsetelemloc_557662_839829468((&b0), (*e0).typ); linef_534700_839829468(p0, ((Tcprocsection531011) 2), LOC43, LOC44, 4); } goto LA38; LA40: ; { NimStringDesc* LOC46; TY534811 LOC47; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[i_559575_839829468], (&a0)); LOC46 = (NimStringDesc*)0; LOC46 = rawNewString(ts0->Sup.len + ts0->Sup.len + 36); appendString(LOC46, ((NimStringDesc*) &T839829468_530)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_531)); appendString(LOC46, ts0); appendString(LOC46, ((NimStringDesc*) &T839829468_454)); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = rdloc_540188_839829468((&(*d0))); LOC47[1] = rdsetelemloc_557662_839829468((&a0), (*e0).typ); linef_534700_839829468(p0, ((Tcprocsection531011) 2), LOC46, LOC47, 2); } LA38: ; res_559614_839829468 += ((NI) 1); } LA37: ; } } } LA11: ; } LA1: ; } N_NIMCALL(void, exprcomplexconst_560684_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Ttype294840* t0; Ropeobj180006* LOC1; NI id0; Ropeobj180006* tmp0; Ropeobj180006* LOC2; t0 = getuniquetype_530640_2036603609((*n0).typ); LOC1 = (Ropeobj180006*)0; LOC1 = gettypedesc_537673_839829468((*p0).module, t0); id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC2 = (Ropeobj180006*)0; LOC2 = rope_180401_2381377266(((NI64) (id0))); tmp0 = HEX26_180418_2381377266((*(*p0).module).tmpbase, LOC2); { TY537238 LOC7; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA5; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC7[1] = tmp0; LOC7[2] = genconstexpr_556849_839829468(p0, n0); addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC7, 3); } LA5: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA10; fillloc_534282_839829468(d0, ((Tlockind294808) 8), t0, tmp0, ((Tstorageloc294812) 1)); } goto LA8; LA10: ; { putdataintodest_552436_839829468(p0, d0, t0, tmp0); { if (!!(((285212672 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0))) goto LA15; (*d0).s = ((Tstorageloc294812) 1); } LA15: ; } LA8: ; } N_NIMCALL(NIM_BOOL, handleconstexpr_556853_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; NI LOC6; Ttype294840* t0; Ropeobj180006* LOC10; NI id0; Ropeobj180006* LOC11; Ropeobj180006* LOC12; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = ((*d0).k == ((Tlockind294808) 0)); if (!(LOC4)) goto LA5; LOC6 = (NI)0; LOC6 = len_295081_850551059(n0); LOC4 = (((NI) (((*n0).kind == ((Tnodekind294020) 38)))) < LOC6); LA5: ; LOC3 = LOC4; if (!(LOC3)) goto LA7; LOC3 = isdeepconstexpr_320566_2616423590(n0); LA7: ; if (!LOC3) goto LA8; t0 = getuniquetype_530640_2036603609((*n0).typ); LOC10 = (Ropeobj180006*)0; LOC10 = gettypedesc_537673_839829468((*p0).module, t0); id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), n0, ((NI) ((*(*p0).module).labels))); LOC11 = (Ropeobj180006*)0; LOC11 = rope_180401_2381377266(((NI64) (id0))); LOC12 = (Ropeobj180006*)0; LOC12 = HEX26_180418_2381377266((*(*p0).module).tmpbase, LOC11); fillloc_534282_839829468(d0, ((Tlockind294808) 8), t0, LOC12, ((Tstorageloc294812) 1)); { TY537238 LOC17; if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA15; (*(*p0).module).labels += ((NI) 1); memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = gettypedesc_537673_839829468((*p0).module, t0); LOC17[1] = (*d0).r; LOC17[2] = genconstexpr_556849_839829468(p0, n0); addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_272), LOC17, 3); } LA15: ; result0 = NIM_TRUE; } goto LA1; LA8: ; { result0 = NIM_FALSE; } LA1: ; return result0; } N_NIMCALL(void, genarrayconstr_560207_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 arr0; memset((void*)(&arr0), 0, sizeof(arr0)); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_556853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA8; gettemp_539032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA8: ; { NI i_560234_839829468; NI HEX3Atmp_560242_839829468; NI LOC11; NI res_560245_839829468; i_560234_839829468 = (NI)0; HEX3Atmp_560242_839829468 = (NI)0; LOC11 = (NI)0; LOC11 = sonslen_297351_850551059(n0); HEX3Atmp_560242_839829468 = (NI)(LOC11 - ((NI) 1)); res_560245_839829468 = ((NI) 0); { while (1) { Ttype294840* LOC14; Ttype294840* LOC15; TY534811 LOC16; if (!(res_560245_839829468 <= HEX3Atmp_560242_839829468)) goto LA13; i_560234_839829468 = res_560245_839829468; LOC14 = (Ttype294840*)0; LOC14 = skiptypes_298099_850551059((*n0).typ, IL64(211106232576256)); LOC15 = (Ttype294840*)0; LOC15 = elemtype_322394_3876443242(LOC14); initloc_534273_839829468((&arr0), ((Tlockind294808) 6), LOC15, (*d0).s); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468((&(*d0))); LOC16[1] = intliteral_541270_839829468(((NI64) (i_560234_839829468))); arr0.r = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_138), LOC16, 2); expr_541248_839829468(p0, (*n0).kindU.S6.sons->data[i_560234_839829468], (&arr0)); res_560245_839829468 += ((NI) 1); } LA13: ; } } } LA4: ; } N_NIMCALL(void, gentupleconstr_559618_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 rec0; memset((void*)(&rec0), 0, sizeof(rec0)); { NIM_BOOL LOC3; Ttype294840* t0; Ropeobj180006* LOC6; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_556853_839829468(p0, n0, d0); if (!!(LOC3)) goto LA4; t0 = getuniquetype_530640_2036603609((*n0).typ); LOC6 = (Ropeobj180006*)0; LOC6 = gettypedesc_537673_839829468((*p0).module, t0); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA9; gettemp_539032_839829468(p0, t0, d0, NIM_FALSE); } LA9: ; { NI i_559646_839829468; NI HEX3Atmp_559803_839829468; NI LOC12; NI res_559806_839829468; i_559646_839829468 = (NI)0; HEX3Atmp_559803_839829468 = (NI)0; LOC12 = (NI)0; LOC12 = sonslen_297351_850551059(n0); HEX3Atmp_559803_839829468 = (NI)(LOC12 - ((NI) 1)); res_559806_839829468 = ((NI) 0); { while (1) { Tnode294802* it0; TY534811 LOC19; if (!(res_559806_839829468 <= HEX3Atmp_559803_839829468)) goto LA14; i_559646_839829468 = res_559806_839829468; it0 = (*n0).kindU.S6.sons->data[i_559646_839829468]; { if (!((*it0).kind == ((Tnodekind294020) 34))) goto LA17; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA17: ; initloc_534273_839829468((&rec0), ((Tlockind294808) 6), (*it0).typ, (*d0).s); memset((void*)LOC19, 0, sizeof(LOC19)); LOC19[0] = rdloc_540188_839829468((&(*d0))); LOC19[1] = rope_180401_2381377266(((NI64) (i_559646_839829468))); rec0.r = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_185), LOC19, 2); expr_541248_839829468(p0, it0, (&rec0)); res_559806_839829468 += ((NI) 1); } LA14: ; } } } LA4: ; } N_NIMCALL(Tsym294834*, lookupfieldagain_555154_839829468)(Tcproc531021* p0, Ttype294840* ty_555157_839829468, Tsym294834* field0, Ropeobj180006** r0) { Tsym294834* result0; Ttype294840* ty0; result0 = (Tsym294834*)0; ty0 = ty_555157_839829468; { while (1) { if (!!((ty0 == NIM_NIL))) goto LA2; ty0 = skiptypes_298099_850551059(ty0, IL64(211106247215360)); result0 = lookupinrecord_301119_2984716966((*ty0).n, (*field0).name); { if (!!((result0 == NIM_NIL))) goto LA5; goto LA1; } LA5: ; { NIM_BOOL LOC9; LOC9 = (NIM_BOOL)0; LOC9 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC9) goto LA10; LOC9 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA10: ; if (!!(LOC9)) goto LA11; add_180487_2381377266(r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; ty0 = getuniquetype_530640_2036603609((*ty0).sons->data[((NI) 0)]); } LA2: ; } LA1: ; { if (!(result0 == NIM_NIL)) goto LA15; internalerror_198100_155036129((*field0).info, ((NimStringDesc*) &T839829468_532)); } LA15: ; return result0; } N_NIMCALL(void, genfieldcheck_555504_839829468)(Tcproc531021* p0, Tnode294802* e0, Ropeobj180006* obj0, Tsym294834* field0, Ttype294840* origty0) { Tloc294816 test0; Tloc294816 u0; Tloc294816 v0; memset((void*)(&test0), 0, sizeof(test0)); memset((void*)(&u0), 0, sizeof(u0)); memset((void*)(&v0), 0, sizeof(v0)); { NI i_555525_839829468; NI HEX3Atmp_556039_839829468; NI LOC2; NI res_556042_839829468; i_555525_839829468 = (NI)0; HEX3Atmp_556039_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(e0); HEX3Atmp_556039_839829468 = (NI)(LOC2 - ((NI) 1)); res_556042_839829468 = ((NI) 1); { while (1) { Tnode294802* it0; Tsym294834* op0; Tnode294802* disc0; Ropeobj180006* o0; Tsym294834* d0; NI id0; Tnode294802* LOC9; Ropeobj180006* strlit0; if (!(res_556042_839829468 <= HEX3Atmp_556039_839829468)) goto LA4; i_555525_839829468 = res_556042_839829468; it0 = (*e0).kindU.S6.sons->data[i_555525_839829468]; op0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!((*op0).magic == ((Tmagic294524) 99))) goto LA7; it0 = (*it0).kindU.S6.sons->data[((NI) 1)]; } LA7: ; disc0 = skipconv_330882_3876443242((*it0).kindU.S6.sons->data[((NI) 2)]); initloc_534273_839829468((&test0), ((Tlockind294808) 0), (*it0).typ, ((Tstorageloc294812) 2)); initlocexpr_541283_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&u0)); o0 = obj0; d0 = lookupfieldagain_555154_839829468(p0, origty0, (*disc0).kindU.S4.sym, &o0); initloc_534273_839829468((&v0), ((Tlockind294808) 6), (*d0).typ, ((Tstorageloc294812) 0)); v0.r = o0; add_180487_2381377266(&v0.r, ((NimStringDesc*) &T839829468_257)); add_180482_2381377266(&v0.r, (*d0).loc.r); geninexpraux_555496_839829468(p0, it0, (&u0), (&v0), (&test0)); LOC9 = (Tnode294802*)0; LOC9 = newstrnode_295677_850551059(((Tnodekind294020) 20), (*(*field0).name).s); id0 = nodetabletestorset_344682_1142335848((&(*(*p0).module).datacache), LOC9, ((NI) ((*(*p0).module).labels))); { if (!(id0 == ((NI) ((*(*p0).module).labels)))) goto LA12; strlit0 = getstrlit_551468_839829468((*p0).module, (*(*field0).name).s); } goto LA10; LA12: ; { Ropeobj180006* LOC15; LOC15 = (Ropeobj180006*)0; LOC15 = rope_180401_2381377266(((NI64) (id0))); strlit0 = HEX26_180418_2381377266((*(*p0).module).tmpbase, LOC15); } LA10: ; { TY534811 LOC20; if (!((*op0).magic == ((Tmagic294524) 99))) goto LA18; memset((void*)LOC20, 0, sizeof(LOC20)); LOC20[0] = rdloc_540188_839829468((&test0)); LOC20[1] = strlit0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_534), LOC20, 2); } goto LA16; LA18: ; { TY534811 LOC22; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = rdloc_540188_839829468((&test0)); LOC22[1] = strlit0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_535), LOC22, 2); } LA16: ; res_556042_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genobjconstr_556903_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 tmp0; Ttype294840* t0; NIM_BOOL isref0; Ropeobj180006* r0; Ropeobj180006* LOC13; Ttype294840* ty0; { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = handleconstexpr_556853_839829468(p0, e0, d0); if (!LOC3) goto LA4; goto BeforeRet; } LA4: ; memset((void*)(&tmp0), 0, sizeof(tmp0)); t0 = skiptypes_298099_850551059((*e0).typ, IL64(211106232576256)); gettemp_539032_839829468(p0, t0, (&tmp0), NIM_FALSE); isref0 = ((*t0).kind == ((Ttypekind294244) 22)); r0 = rdloc_540188_839829468((&tmp0)); { Ttype294840* LOC10; TY180507 LOC11; if (!isref0) goto LA8; rawgennew_556741_839829468(p0, (&tmp0), NIM_NIL); LOC10 = (Ttype294840*)0; LOC10 = lastson_297377_850551059(t0); t0 = skiptypes_298099_850551059(LOC10, IL64(211106232576256)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = r0; r0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_124), LOC11, 1); gcusage_556439_839829468(e0); } goto LA6; LA8: ; { constructloc_540388_839829468(p0, (&tmp0), NIM_FALSE); } LA6: ; LOC13 = (Ropeobj180006*)0; LOC13 = gettypedesc_537673_839829468((*p0).module, t0); ty0 = getuniquetype_530640_2036603609(t0); { NI i_556944_839829468; NI HEX3Atmp_556997_839829468; NI LOC15; NI res_557000_839829468; i_556944_839829468 = (NI)0; HEX3Atmp_556997_839829468 = (NI)0; LOC15 = (NI)0; LOC15 = len_295081_850551059(e0); HEX3Atmp_556997_839829468 = (LOC15 - 1); res_557000_839829468 = ((NI) 1); { while (1) { Tnode294802* it0; Tloc294816 tmp20; Tsym294834* field0; if (!(res_557000_839829468 <= HEX3Atmp_556997_839829468)) goto LA17; i_556944_839829468 = res_557000_839829468; it0 = (*e0).kindU.S6.sons->data[i_556944_839829468]; memset((void*)(&tmp20), 0, sizeof(tmp20)); tmp20.r = r0; field0 = lookupfieldagain_555154_839829468(p0, ty0, (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym, &tmp20.r); { if (!((*field0).loc.r == NIM_NIL)) goto LA20; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_533)); } LA20: ; { NIM_BOOL LOC24; NI LOC25; LOC24 = (NIM_BOOL)0; LOC25 = (NI)0; LOC25 = len_295081_850551059(it0); LOC24 = (LOC25 == ((NI) 3)); if (!(LOC24)) goto LA26; LOC24 = (((*p0).options &(1U<<((NU)(((Toption171009) 2))&31U)))!=0); LA26: ; if (!LOC24) goto LA27; genfieldcheck_555504_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 2)], r0, field0, ty0); } LA27: ; add_180487_2381377266(&tmp20.r, ((NimStringDesc*) &T839829468_257)); add_180482_2381377266(&tmp20.r, (*field0).loc.r); tmp20.k = ((Tlockind294808) 1); tmp20.t = (*field0).loc.t; { if (!isref0) goto LA31; tmp20.s = ((Tstorageloc294812) 3); } goto LA29; LA31: ; { tmp20.s = ((Tstorageloc294812) 2); } LA29: ; expr_541248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], (&tmp20)); res_557000_839829468 += ((NI) 1); } LA17: ; } } { if (!((*d0).k == ((Tlockind294808) 0))) goto LA36; genericAssign((void*)(&(*d0)), (void*)(&tmp0), (&NTI294816)); } goto LA34; LA36: ; { genassignment_541264_839829468(p0, (&(*d0)), (&tmp0), 0); } LA34: ; }BeforeRet: ; } N_NIMCALL(void, gencast_558538_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Ttype294840* destt0; Ttype294840* srct0; destt0 = skiptypes_298099_850551059((*e0).typ, IL64(211106233624832)); srct0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106233624832)); { NIM_BOOL LOC3; Ropeobj180006* lbl0; Tloc294816 tmp0; TY180507 LOC7; TY537238 LOC8; TY180507 LOC9; Ropeobj180006* LOC10; LOC3 = (NIM_BOOL)0; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*destt0).kind)&63U)))!=0); if (LOC3) goto LA4; LOC3 = ((IL64(1030792609808) &((NU64)1<<((NU)((*srct0).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA5; (*p0).labels += ((NI) 1); lbl0 = rope_180401_2381377266(((NI64) ((*p0).labels))); memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = lbl0; tmp0.r = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_536), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_537673_839829468((*p0).module, srct0); LOC8[1] = gettypedesc_537673_839829468((*p0).module, destt0); LOC8[2] = lbl0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 0), ((NimStringDesc*) &T839829468_537), LOC8, 3); tmp0.k = ((Tlockind294808) 6); tmp0.t = srct0; tmp0.s = ((Tstorageloc294812) 2); tmp0.flags = 0; expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = lbl0; LOC10 = (Ropeobj180006*)0; LOC10 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_538), LOC9, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC10, tmp0.s); } goto LA1; LA5: ; { gensomecast_558481_839829468(p0, e0, d0); } LA1: ; } N_NIMCALL(void, genconv_558633_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Ttype294840* desttype0; desttype0 = skiptypes_298099_850551059((*e0).typ, 8390656); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = comparetypes_328214_3876443242(desttype0, (*(*e0).kindU.S6.sons->data[((NI) 1)]).typ, ((Tdistinctcompare326427) 1), 0); if (!LOC3) goto LA4; expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], d0); } goto LA1; LA4: ; { gensomecast_558481_839829468(p0, e0, d0); } LA1: ; } static N_INLINE(NIM_BOOL, iscppref_554807_839829468)(Tcproc531021* p0, Ttype294840* typ0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; NIM_BOOL LOC3; Ttype294840* LOC6; Ttype294840* LOC8; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; LOC2 = LOC3; if (!(LOC2)) goto LA5; LOC6 = (Ttype294840*)0; LOC6 = skiptypes_298099_850551059(typ0, IL64(211106232576256)); LOC2 = ((*LOC6).kind == ((Ttypekind294244) 23)); LA5: ; LOC1 = LOC2; if (!(LOC1)) goto LA7; LOC8 = (Ttype294840*)0; LOC8 = skiptypes_298099_850551059(typ0, IL64(211106232576256)); LOC1 = !((((*LOC8).flags &(1U<<((NU)(((Ttypeflag294431) 18))&31U)))!=0)); LA7: ; result0 = LOC1; return result0; } N_NIMCALL(void, genaddr_555051_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { { Ttype294840* LOC3; Tloc294816 a0; Ropeobj180006* LOC6; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((6291456 &((NU64)1<<((NU)((*LOC3).kind)&63U)))!=0)) goto LA4; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC6 = (Ropeobj180006*)0; LOC6 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_52), a0.r); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC6, a0.s); } goto LA1; LA4: ; { NIM_BOOL LOC8; Tctypekind531007 LOC9; LOC8 = (NIM_BOOL)0; LOC9 = (Tctypekind531007)0; LOC9 = maptype_535394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LOC8 = (LOC9 == ((Tctypekind531007) 17)); if (LOC8) goto LA10; LOC8 = iscppref_554807_839829468(p0, (*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); LA10: ; if (!LOC8) goto LA11; expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA11: ; { Tloc294816 a0; Ropeobj180006* LOC14; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC14 = (Ropeobj180006*)0; LOC14 = addrloc_540204_839829468((&a0)); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC14, a0.s); } LA1: ; } N_NIMCALL(void, genarrayelem_556093_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* ty0; Ttype294840* LOC1; Ropeobj180006* first0; NI64 LOC2; Ttype294840* LOC47; Ttype294840* LOC48; TY537238 LOC49; Ropeobj180006* LOC50; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, x0, (&a0)); initlocexpr_541283_839829468(p0, y0, (&b0)); LOC1 = (Ttype294840*)0; LOC1 = skiptypes_298099_850551059(a0.t, IL64(211106242013440)); ty0 = skiptypes_298099_850551059(LOC1, IL64(211106247256320)); LOC2 = (NI64)0; LOC2 = firstord_322001_3876443242(ty0); first0 = intliteral_541270_839829468(LOC2); { NIM_BOOL LOC5; LOC5 = (NIM_BOOL)0; LOC5 = (((*p0).options &(1U<<((NU)(((Toption171009) 4))&31U)))!=0); if (!(LOC5)) goto LA6; LOC5 = !((((*ty0).flags &(1U<<((NU)(((Ttypeflag294431) 0))&31U)))!=0)); LA6: ; if (!LOC5) goto LA7; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = isconstexpr_320510_2616423590(y0); if (!!(LOC11)) goto LA12; { NI64 LOC16; LOC16 = (NI64)0; LOC16 = firstord_322001_3876443242(ty0); if (!(LOC16 == IL64(0))) goto LA17; { NIM_BOOL LOC21; NI64 LOC22; NI64 LOC23; NI64 LOC25; NI64 LOC26; TY534811 LOC29; NI64 LOC30; LOC21 = (NIM_BOOL)0; LOC22 = (NI64)0; LOC22 = firstord_322001_3876443242(b0.t); LOC23 = (NI64)0; LOC23 = firstord_322001_3876443242(ty0); LOC21 = (LOC22 < LOC23); if (LOC21) goto LA24; LOC25 = (NI64)0; LOC25 = lastord_322004_3876443242(ty0); LOC26 = (NI64)0; LOC26 = lastord_322004_3876443242(b0.t); LOC21 = (LOC25 < LOC26); LA24: ; if (!LOC21) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdcharloc_540227_839829468((&b0)); LOC30 = (NI64)0; LOC30 = lastord_322004_3876443242(ty0); LOC29[1] = intliteral_541270_839829468(LOC30); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_539), LOC29, 2); } LA27: ; } goto LA14; LA17: ; { TY537238 LOC32; NI64 LOC33; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rdcharloc_540227_839829468((&b0)); LOC32[1] = first0; LOC33 = (NI64)0; LOC33 = lastord_322004_3876443242(ty0); LOC32[2] = intliteral_541270_839829468(LOC33); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_540), LOC32, 3); } LA14: ; } goto LA9; LA12: ; { NI64 idx0; idx0 = getordvalue_322129_3876443242(y0); { NIM_BOOL LOC37; NI64 LOC38; NI64 LOC40; LOC37 = (NIM_BOOL)0; LOC38 = (NI64)0; LOC38 = firstord_322001_3876443242(ty0); LOC37 = (idx0 < LOC38); if (LOC37) goto LA39; LOC40 = (NI64)0; LOC40 = lastord_322004_3876443242(ty0); LOC37 = (LOC40 < idx0); LA39: ; if (!LOC37) goto LA41; localerror_198080_155036129((*x0).info, ((Tmsgkind193002) 86), ((NimStringDesc*) &T839829468_490)); } LA41: ; } LA9: ; } LA7: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA45; (*d0).s = a0.s; } LA45: ; LOC47 = (Ttype294840*)0; LOC47 = skiptypes_298099_850551059(ty0, IL64(211106240964864)); LOC48 = (Ttype294840*)0; LOC48 = elemtype_322394_3876443242(LOC47); memset((void*)LOC49, 0, sizeof(LOC49)); LOC49[0] = rdloc_540188_839829468((&a0)); LOC49[1] = rdcharloc_540227_839829468((&b0)); LOC49[2] = first0; LOC50 = (Ropeobj180006*)0; LOC50 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_541), LOC49, 3); putintodest_552468_839829468(p0, d0, LOC48, LOC50, a0.s); } N_NIMCALL(void, genopenarrayelem_556169_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* LOC10; Ttype294840* LOC11; TY534811 LOC12; Ropeobj180006* LOC13; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, x0, (&a0)); initlocexpr_541283_839829468(p0, y0, (&b0)); { TY534811 LOC5; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 4))&31U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&b0)); LOC5[1] = rdloc_540188_839829468((&a0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_542), LOC5, 2); } LA3: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA8; (*d0).s = a0.s; } LA8: ; LOC10 = (Ttype294840*)0; LOC10 = skiptypes_298099_850551059(a0.t, IL64(211106240964864)); LOC11 = (Ttype294840*)0; LOC11 = elemtype_322394_3876443242(LOC10); memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rdloc_540188_839829468((&a0)); LOC12[1] = rdcharloc_540227_839829468((&b0)); LOC13 = (Ropeobj180006*)0; LOC13 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC12, 2); putintodest_552468_839829468(p0, d0, LOC11, LOC13, a0.s); } N_NIMCALL(void, genseqelem_556205_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* ty0; Ttype294840* LOC27; Ttype294840* LOC28; TY534811 LOC29; Ropeobj180006* LOC30; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, x0, (&a0)); initlocexpr_541283_839829468(p0, y0, (&b0)); ty0 = skiptypes_298099_850551059(a0.t, IL64(211106242013440)); { Ttype294840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype294840*)0; LOC5 = lastson_297377_850551059(ty0); ty0 = skiptypes_298099_850551059(LOC5, IL64(211106242013440)); } LA3: ; { if (!(((*p0).options &(1U<<((NU)(((Toption171009) 4))&31U)))!=0)) goto LA8; { TY537238 LOC14; if (!((*ty0).kind == ((Ttypekind294244) 28))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_540188_839829468((&b0)); LOC14[1] = rdloc_540188_839829468((&a0)); LOC14[2] = lenfield_541305_839829468(p0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_543), LOC14, 3); } goto LA10; LA12: ; { TY537238 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rdloc_540188_839829468((&b0)); LOC16[1] = rdloc_540188_839829468((&a0)); LOC16[2] = lenfield_541305_839829468(p0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_544), LOC16, 3); } LA10: ; } LA8: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA19; (*d0).s = ((Tstorageloc294812) 3); } LA19: ; { Ttype294840* LOC23; TY180507 LOC26; LOC23 = (Ttype294840*)0; LOC23 = skiptypes_298099_850551059(a0.t, IL64(211106240964864)); if (!((6291456 &((NU64)1<<((NU)((*LOC23).kind)&63U)))!=0)) goto LA24; memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = a0.r; a0.r = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_124), LOC26, 1); } LA24: ; LOC27 = (Ttype294840*)0; LOC27 = skiptypes_298099_850551059(a0.t, IL64(211106240964864)); LOC28 = (Ttype294840*)0; LOC28 = elemtype_322394_3876443242(LOC27); memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = rdloc_540188_839829468((&a0)); LOC29[1] = rdcharloc_540227_839829468((&b0)); LOC30 = (Ropeobj180006*)0; LOC30 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_187), LOC29, 2); putintodest_552468_839829468(p0, d0, LOC28, LOC30, a0.s); } N_NIMCALL(void, gencstringelem_556144_839829468)(Tcproc531021* p0, Tnode294802* x0, Tnode294802* y0, Tloc294816* d0) { Tloc294816 a0; Tloc294816 b0; Ttype294840* ty0; Ttype294840* LOC5; Ttype294840* LOC6; TY534811 LOC7; Ropeobj180006* LOC8; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, x0, (&a0)); initlocexpr_541283_839829468(p0, y0, (&b0)); ty0 = skiptypes_298099_850551059(a0.t, IL64(211106242013440)); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ttype294840*)0; LOC5 = skiptypes_298099_850551059(ty0, IL64(211106240964864)); LOC6 = (Ttype294840*)0; LOC6 = elemtype_322394_3876443242(LOC5); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_540188_839829468((&a0)); LOC7[1] = rdcharloc_540227_839829468((&b0)); LOC8 = (Ropeobj180006*)0; LOC8 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_138), LOC7, 2); putintodest_552468_839829468(p0, d0, LOC6, LOC8, a0.s); } N_NIMCALL(void, gentupleelem_555124_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; NI i0; Ropeobj180006* LOC5; Ttype294840* ty0; Ropeobj180006* r0; TY180507 LOC8; memset((void*)(&a0), 0, sizeof(a0)); i0 = (NI)0; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!((*d0).k == ((Tlockind294808) 0))) goto LA3; (*d0).s = a0.s; } LA3: ; LOC5 = (Ropeobj180006*)0; LOC5 = gettypedesc_537673_839829468((*p0).module, a0.t); ty0 = getuniquetype_530640_2036603609(a0.t); r0 = rdloc_540188_839829468((&a0)); switch ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind) { case ((Tnodekind294020) 6) ... ((Tnodekind294020) 15): { i0 = ((NI) ((*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval)); } break; default: { internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_545)); } break; } memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rope_180401_2381377266(((NI64) (i0))); addf_181205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC8, 1); putintodest_552468_839829468(p0, d0, (*ty0).sons->data[i0], r0, a0.s); } N_NIMCALL(void, genbracketexpr_556277_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Ttype294840* ty0; ty0 = skiptypes_298099_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); { Ttype294840* LOC5; if (!((6291456 &((NU64)1<<((NU)((*ty0).kind)&63U)))!=0)) goto LA3; LOC5 = (Ttype294840*)0; LOC5 = lastson_297377_850551059(ty0); ty0 = skiptypes_298099_850551059(LOC5, IL64(211106242013440)); } LA3: ; switch ((*ty0).kind) { case ((Ttypekind294244) 16): case ((Ttypekind294244) 4): { genarrayelem_556093_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind294244) 27): case ((Ttypekind294244) 48): { genopenarrayelem_556169_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind294244) 24): case ((Ttypekind294244) 28): { genseqelem_556205_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind294244) 29): { gencstringelem_556144_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (*n0).kindU.S6.sons->data[((NI) 1)], d0); } break; case ((Ttypekind294244) 18): { gentupleelem_555124_839829468(p0, n0, d0); } break; default: { NimStringDesc* LOC12; LOC12 = (NimStringDesc*)0; LOC12 = rawNewString(reprEnum((NI)(*ty0).kind, (&NTI294244))->Sup.len + 21); appendString(LOC12, ((NimStringDesc*) &T839829468_547)); appendString(LOC12, reprEnum((NI)(*ty0).kind, (&NTI294244))); appendChar(LOC12, 41); internalerror_198100_155036129((*n0).info, LOC12); } break; } } N_NIMCALL(void, genderef_545921_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, NIM_BOOL enforcederef0) { Tctypekind531007 mt0; { mt0 = maptype_535394_839829468((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((393216 &(1U<<((NU)(mt0)&31U)))!=0); if (!(LOC3)) goto LA4; LOC3 = !(enforcederef0); LA4: ; if (!LOC3) goto LA5; expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); { Ttype294840* LOC9; LOC9 = (Ttype294840*)0; LOC9 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); if (!((*LOC9).kind == ((Ttypekind294244) 22))) goto LA10; (*d0).s = ((Tstorageloc294812) 3); } LA10: ; } goto LA1; LA5: ; { Tloc294816 a0; Ttype294840* typ0; memset((void*)(&a0), 0, sizeof(a0)); typ0 = skiptypes_298099_850551059((*(*e0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NIM_BOOL LOC15; NIM_BOOL LOC16; NIM_BOOL LOC17; NIM_BOOL LOC20; Tnode294802* LOC25; Tnode294802* LOC26; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC17 = (NIM_BOOL)0; LOC17 = ((*typ0).kind == ((Ttypekind294244) 23)); if (!(LOC17)) goto LA18; LOC17 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 18))&31U)))!=0)); LA18: ; LOC16 = LOC17; if (!(LOC16)) goto LA19; LOC20 = (NIM_BOOL)0; LOC20 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC20) goto LA21; LOC20 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA21: ; LOC16 = LOC20; LA19: ; LOC15 = LOC16; if (!(LOC15)) goto LA22; LOC15 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 64)); LA22: ; if (!LOC15) goto LA23; LOC25 = (Tnode294802*)0; LOC25 = HEX5BHEX5D_295238_850551059(e0, ((NI) 0)); LOC26 = (Tnode294802*)0; LOC26 = HEX5BHEX5D_295238_850551059(LOC25, ((NI) 0)); initlocexprsingleuse_541289_839829468(p0, LOC26, d0); goto BeforeRet; } goto LA13; LA23: ; { initlocexprsingleuse_541289_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA13: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA30; switch ((*typ0).kind) { case ((Ttypekind294244) 22): { (*d0).s = ((Tstorageloc294812) 3); } break; case ((Ttypekind294244) 23): { (*d0).s = ((Tstorageloc294812) 0); { NIM_BOOL LOC36; NIM_BOOL LOC37; NIM_BOOL LOC39; Ropeobj180006* LOC44; LOC36 = (NIM_BOOL)0; LOC37 = (NIM_BOOL)0; LOC37 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 18))&31U)))!=0)); if (!(LOC37)) goto LA38; LOC39 = (NIM_BOOL)0; LOC39 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC39) goto LA40; LOC39 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA40: ; LOC37 = LOC39; LA38: ; LOC36 = LOC37; if (!(LOC36)) goto LA41; LOC36 = ((*e0).kind == ((Tnodekind294020) 65)); LA41: ; if (!LOC36) goto LA42; LOC44 = (Ropeobj180006*)0; LOC44 = rdloc_540188_839829468((&a0)); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC44, a0.s); goto BeforeRet; } LA42: ; } break; case ((Ttypekind294244) 21): { (*d0).s = ((Tstorageloc294812) 0); } break; default: { NimStringDesc* LOC47; LOC47 = (NimStringDesc*)0; LOC47 = rawNewString(reprEnum((NI)(*typ0).kind, (&NTI294244))->Sup.len + 9); appendString(LOC47, ((NimStringDesc*) &T839829468_548)); appendString(LOC47, reprEnum((NI)(*typ0).kind, (&NTI294244))); internalerror_198100_155036129((*e0).info, LOC47); } break; } } goto LA28; LA30: ; { NIM_BOOL LOC49; LOC49 = (NIM_BOOL)0; LOC49 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC49) goto LA50; LOC49 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA50: ; if (!LOC49) goto LA51; { NIM_BOOL LOC55; NIM_BOOL LOC56; Ropeobj180006* LOC61; LOC55 = (NIM_BOOL)0; LOC56 = (NIM_BOOL)0; LOC56 = ((*typ0).kind == ((Ttypekind294244) 23)); if (!(LOC56)) goto LA57; LOC56 = !((((*typ0).flags &(1U<<((NU)(((Ttypeflag294431) 18))&31U)))!=0)); LA57: ; LOC55 = LOC56; if (!(LOC55)) goto LA58; LOC55 = ((*e0).kind == ((Tnodekind294020) 65)); LA58: ; if (!LOC55) goto LA59; LOC61 = (Ropeobj180006*)0; LOC61 = rdloc_540188_839829468((&a0)); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC61, a0.s); goto BeforeRet; } LA59: ; } goto LA28; LA51: ; LA28: ; { NIM_BOOL LOC64; Ropeobj180006* LOC68; LOC64 = (NIM_BOOL)0; LOC64 = enforcederef0; if (!(LOC64)) goto LA65; LOC64 = (mt0 == ((Tctypekind531007) 18)); LA65: ; if (!LOC64) goto LA66; LOC68 = (Ropeobj180006*)0; LOC68 = rdloc_540188_839829468((&a0)); putintodest_552468_839829468(p0, d0, (*a0.t).sons->data[((NI) 0)], LOC68, a0.s); } goto LA62; LA66: ; { TY180507 LOC70; Ropeobj180006* LOC71; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rdloc_540188_839829468((&a0)); LOC71 = (Ropeobj180006*)0; LOC71 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_124), LOC70, 1); putintodest_552468_839829468(p0, d0, (*e0).typ, LOC71, a0.s); } LA62: ; } LA1: ; }BeforeRet: ; } N_NIMCALL(Ttype294840*, genrecordfieldaux_555096_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0, Tloc294816* a0) { Ttype294840* result0; Ropeobj180006* LOC9; result0 = (Ttype294840*)0; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], a0); { if (!!(((*(*e0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind294020) 3)))) goto LA3; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_549)); } LA3: ; { if (!((*d0).k == ((Tlockind294808) 0))) goto LA7; (*d0).s = (*a0).s; } LA7: ; LOC9 = (Ropeobj180006*)0; LOC9 = gettypedesc_537673_839829468((*p0).module, (*a0).t); result0 = getuniquetype_530640_2036603609((*a0).t); return result0; } N_NIMCALL(void, genrecordfield_555448_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* ty0; Ropeobj180006* r0; Tsym294834* f0; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_555096_839829468(p0, e0, d0, (&a0)); r0 = rdloc_540188_839829468((&a0)); f0 = (*(*e0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; { TY180507 LOC5; if (!((*ty0).kind == ((Ttypekind294244) 18))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_180401_2381377266(((NI64) ((*f0).position))); addf_181205_2381377266(&r0, ((NimStringDesc*) &T839829468_546), LOC5, 1); putintodest_552468_839829468(p0, d0, (*f0).typ, r0, a0.s); } goto LA1; LA3: ; { Tsym294834* field0; TY180507 LOC11; field0 = lookupfieldagain_555154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA9; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_550)); } LA9: ; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*field0).loc.r; addf_181205_2381377266(&r0, ((NimStringDesc*) &T839829468_551), LOC11, 1); putintodest_552468_839829468(p0, d0, (*field0).typ, r0, a0.s); } LA1: ; } N_NIMCALL(void, gencheckedrecordfield_556046_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0) { { Tloc294816 a0; Ttype294840* ty0; Ropeobj180006* r0; Tsym294834* f0; Tsym294834* field0; TY180507 LOC9; Ropeobj180006* LOC10; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 2))&31U)))!=0)) goto LA3; memset((void*)(&a0), 0, sizeof(a0)); ty0 = genrecordfieldaux_555096_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0, (&a0)); r0 = rdloc_540188_839829468((&a0)); f0 = (*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; field0 = lookupfieldagain_555154_839829468(p0, ty0, f0, &r0); { if (!((*field0).loc.r == NIM_NIL)) goto LA7; internalerror_198100_155036129((*e0).info, ((NimStringDesc*) &T839829468_532)); } LA7: ; genfieldcheck_555504_839829468(p0, e0, r0, field0, ty0); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = (*field0).loc.r; LOC10 = (Ropeobj180006*)0; LOC10 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_551), LOC9, 1); add_180482_2381377266(&r0, LOC10); putintodest_552468_839829468(p0, d0, (*field0).typ, r0, a0.s); } goto LA1; LA3: ; { genrecordfield_555448_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], d0); } LA1: ; } N_NIMCALL(NI, startblock_545978_839829468)(Tcproc531021* p0, NimStringDesc* start0, Ropeobj180006** args0, NI args0Len0) { NI result0; result0 = (NI)0; linecg_534707_839829468(p0, ((Tcprocsection531011) 2), start0, args0, args0Len0); (*p0).labels += ((NI) 1); result0 = ((*p0).blocks ? (*p0).blocks->Sup.len : 0); (*p0).blocks = (TY531095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock531019), ((NI) ((NI)(result0 + ((NI) 1))))); (*p0).blocks->data[result0].id = ((NI) ((*p0).labels)); (*p0).blocks->data[result0].nestedtrystmts = ((NI16) (((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0))); (*p0).blocks->data[result0].nestedexceptstmts = ((NI16) ((*p0).inexceptblock)); return result0; } N_NIMCALL(Ropeobj180006*, blockbody_546025_839829468)(Tblock531019* b0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = (*b0).sections[(((Tcprocsection531011) 0))- 0]; { TY180507 LOC5; if (!(((NI16) 0) < (*b0).framelen)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_180401_2381377266(((NI64) ((*b0).framelen))); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_554), LOC5, 1); } LA3: ; add_180482_2381377266(&result0, (*b0).sections[(((Tcprocsection531011) 1))- 0]); add_180482_2381377266(&result0, (*b0).sections[(((Tcprocsection531011) 2))- 0]); return result0; } N_NIMCALL(void, endblock_546035_839829468)(Tcproc531021* p0, Ropeobj180006* blockend0) { NI topblock0; Ropeobj180006* LOC1; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); LOC1 = (Ropeobj180006*)0; LOC1 = blockbody_546025_839829468((&(*p0).blocks->data[topblock0])); add_180482_2381377266(&(*p0).blocks->data[(NI)(topblock0 - ((NI) 1))].sections[(((Tcprocsection531011) 2))- 0], LOC1); (*p0).blocks = (TY531095*) setLengthSeq(&((*p0).blocks)->Sup, sizeof(Tblock531019), ((NI) (topblock0))); line_534690_839829468(p0, ((Tcprocsection531011) 2), blockend0); } N_NIMCALL(void, endblock_546060_839829468)(Tcproc531021* p0) { NI topblock0; Ropeobj180006* blockend0; NI16 framelen0; topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); { TY180507 LOC5; if (!!(((*p0).blocks->data[topblock0].label == NIM_NIL))) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = (*p0).blocks->data[topblock0].label; blockend0 = ropecg_534407_839829468(NIM_NIL, ((NimStringDesc*) &T839829468_552), LOC5, 1); } goto LA1; LA3: ; { TY535289 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); blockend0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_160), LOC7, 0); } LA1: ; framelen0 = (*p0).blocks->data[topblock0].framelen; { TY180507 LOC12; if (!(((NI16) 0) < framelen0)) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_180401_2381377266(((NI64) (framelen0))); addf_181205_2381377266(&blockend0, ((NimStringDesc*) &T839829468_553), LOC12, 1); } LA10: ; endblock_546035_839829468(p0, blockend0); } N_NIMCALL(void, genblock_548083_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { NI oldbreakidx_548099_839829468; TY535289 LOC8; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_299441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind294808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_539032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; oldbreakidx_548099_839829468 = (*p0).breakidx; memset((void*)LOC8, 0, sizeof(LOC8)); (*p0).breakidx = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC8, 0); { Tsym294834* sym0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)))) goto LA11; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; (*sym0).loc.k = ((Tlockind294808) 10); (*sym0).position = (NI)((*p0).breakidx + ((NI) 1)); } LA11: ; expr_541248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], d0); endblock_546060_839829468(p0); (*p0).breakidx = oldbreakidx_548099_839829468; } N_NIMCALL(void, genstmtlistexpr_560402_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { NI length0; length0 = sonslen_297351_850551059(n0); { NI i_560420_839829468; NI HEX3Atmp_560424_839829468; NI res_560427_839829468; i_560420_839829468 = (NI)0; HEX3Atmp_560424_839829468 = (NI)0; HEX3Atmp_560424_839829468 = (NI)(length0 - ((NI) 2)); res_560427_839829468 = ((NI) 0); { while (1) { if (!(res_560427_839829468 <= HEX3Atmp_560424_839829468)) goto LA3; i_560420_839829468 = res_560427_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[i_560420_839829468]); res_560427_839829468 += ((NI) 1); } LA3: ; } } { if (!(((NI) 0) < length0)) goto LA6; expr_541248_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); } LA6: ; } N_NIMCALL(void, genif_546982_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 a0; Ropeobj180006* lelse0; Ropeobj180006* lend0; memset((void*)(&a0), 0, sizeof(a0)); lelse0 = (Ropeobj180006*)0; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_299441_850551059((*n0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind294808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_539032_839829468(p0, (*n0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_534823_839829468(p0, n0); lend0 = getlabel_541217_839829468(p0); { NI i_547011_839829468; NI HEX3Atmp_547435_839829468; NI LOC9; NI res_547438_839829468; i_547011_839829468 = (NI)0; HEX3Atmp_547435_839829468 = (NI)0; LOC9 = (NI)0; LOC9 = sonslen_297351_850551059(n0); HEX3Atmp_547435_839829468 = (NI)(LOC9 - ((NI) 1)); res_547438_839829468 = ((NI) 0); { while (1) { Tnode294802* it0; if (!(res_547438_839829468 <= HEX3Atmp_547435_839829468)) goto LA11; i_547011_839829468 = res_547438_839829468; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC14)) goto LA15; LOC14 = isemptytype_299441_850551059((*n0).typ); LA15: ; if (!LOC14) goto LA16; (*d0).k = ((Tlockind294808) 0); } LA16: ; it0 = (*n0).kindU.S6.sons->data[i_547011_839829468]; { NI LOC20; TY535289 LOC23; NI LOC24; TY534811 LOC25; LOC20 = (NI)0; LOC20 = len_295081_850551059(it0); if (!(LOC20 == ((NI) 2))) goto LA21; memset((void*)LOC23, 0, sizeof(LOC23)); LOC24 = (NI)0; LOC24 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC23, 0); initlocexprsingleuse_541289_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], (&a0)); lelse0 = getlabel_541217_839829468(p0); (*p0).labels += ((NI) 1); memset((void*)LOC25, 0, sizeof(LOC25)); LOC25[0] = rdloc_540188_839829468((&a0)); LOC25[1] = lelse0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_555), LOC25, 2); { NIM_BOOL LOC28; Ropeobj180006** LOC32; Ropeobj180006** LOC33; LOC28 = (NIM_BOOL)0; LOC28 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC28) goto LA29; LOC28 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA29: ; if (!LOC28) goto LA30; LOC32 = (Ropeobj180006**)0; LOC32 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180487_2381377266(LOC32, ((NimStringDesc*) &T839829468_223)); expr_541248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); LOC33 = (Ropeobj180006**)0; LOC33 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180487_2381377266(LOC33, ((NimStringDesc*) &T839829468_280)); } goto LA26; LA30: ; { expr_541248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)], d0); } LA26: ; endblock_546060_839829468(p0); { NI LOC37; TY180507 LOC40; LOC37 = (NI)0; LOC37 = sonslen_297351_850551059(n0); if (!(((NI) 1) < LOC37)) goto LA38; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = lend0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_556), LOC40, 1); } LA38: ; fixlabel_541230_839829468(p0, lelse0); } goto LA18; LA21: ; { NI LOC42; TY535289 LOC45; NI LOC46; LOC42 = (NI)0; LOC42 = len_295081_850551059(it0); if (!(LOC42 == ((NI) 1))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_541248_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 0)], d0); endblock_546060_839829468(p0); } goto LA18; LA43: ; { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_557)); } LA18: ; res_547438_839829468 += ((NI) 1); } LA11: ; } } { NI LOC50; LOC50 = (NI)0; LOC50 = sonslen_297351_850551059(n0); if (!(((NI) 1) < LOC50)) goto LA51; fixlabel_541230_839829468(p0, lend0); } LA51: ; } N_NIMCALL(void, downconv_560581_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC3) goto LA4; LOC3 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; expr_541248_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], d0); } goto LA1; LA5: ; { Ttype294840* dest0; Tnode294802* arg0; Ttype294840* src0; Tloc294816 a0; Ropeobj180006* r0; NIM_BOOL isref0; Ttype294840* LOC10; dest0 = skiptypes_298099_850551059((*n0).typ, IL64(211106247256320)); arg0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { while (1) { if (!((*arg0).kind == ((Tnodekind294020) 66))) goto LA9; arg0 = (*arg0).kindU.S6.sons->data[((NI) 0)]; } LA9: ; } src0 = skiptypes_298099_850551059((*arg0).typ, IL64(211106247256320)); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, arg0, (&a0)); r0 = rdloc_540188_839829468((&a0)); LOC10 = (Ttype294840*)0; LOC10 = skiptypes_298099_850551059((*arg0).typ, IL64(211106232576256)); isref0 = ((14680064 &((NU64)1<<((NU)((*LOC10).kind)&63U)))!=0); { if (!isref0) goto LA13; add_180487_2381377266(&r0, ((NimStringDesc*) &T839829468_558)); } goto LA11; LA13: ; { add_180487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); } LA11: ; { NI i_560650_839829468; NI HEX3Atmp_560677_839829468; NI LOC17; NI res_560680_839829468; i_560650_839829468 = (NI)0; HEX3Atmp_560677_839829468 = (NI)0; LOC17 = (NI)0; LOC17 = inheritancediff_328252_3876443242(dest0, src0); HEX3Atmp_560677_839829468 = (LOC17 > 0? (LOC17) : -(LOC17)); res_560680_839829468 = ((NI) 2); { while (1) { if (!(res_560680_839829468 <= HEX3Atmp_560677_839829468)) goto LA19; i_560650_839829468 = res_560680_839829468; add_180487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); res_560680_839829468 += ((NI) 1); } LA19: ; } } { if (!isref0) goto LA22; { NIM_BOOL LOC26; Ttype294840* LOC28; TY534811 LOC31; LOC26 = (NIM_BOOL)0; LOC26 = ((*d0).k == ((Tlockind294808) 0)); if (!(LOC26)) goto LA27; LOC28 = (Ttype294840*)0; LOC28 = skiptypes_298099_850551059((*n0).typ, IL64(211106232576256)); LOC26 = ((14680064 &((NU64)1<<((NU)((*LOC28).kind)&63U)))!=0); LA27: ; if (!LOC26) goto LA29; gettemp_539032_839829468(p0, (*n0).typ, d0, NIM_FALSE); memset((void*)LOC31, 0, sizeof(LOC31)); LOC31[0] = rdloc_540188_839829468((&(*d0))); LOC31[1] = r0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_559), LOC31, 2); } goto LA24; LA29: ; { r0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_52), r0); putintodest_552468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA24: ; } goto LA20; LA22: ; { putintodest_552468_839829468(p0, d0, (*n0).typ, r0, a0.s); } LA20: ; } LA1: ; } N_NIMCALL(void, upconv_560431_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* dest0; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); dest0 = skiptypes_298099_850551059((*n0).typ, IL64(211106247256320)); { NIM_BOOL LOC3; NIM_BOOL LOC5; Ropeobj180006* r0; Ropeobj180006* nilcheck0; Ttype294840* t0; LOC3 = (NIM_BOOL)0; LOC3 = (((*p0).options &(1U<<((NU)(((Toption171009) 1))&31U)))!=0); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = isobjlackingtypefield_535515_839829468(dest0); LOC3 = !(LOC5); LA4: ; if (!LOC3) goto LA6; r0 = rdloc_540188_839829468((&a0)); nilcheck0 = NIM_NIL; t0 = skiptypes_298099_850551059(a0.t, IL64(211106232576256)); { while (1) { Ttype294840* LOC23; if (!((14680064 &((NU64)1<<((NU)((*t0).kind)&63U)))!=0)) goto LA9; { if (!!(((*t0).kind == ((Ttypekind294244) 23)))) goto LA12; nilcheck0 = r0; } LA12: ; { NIM_BOOL LOC16; NIM_BOOL LOC18; TY180507 LOC22; LOC16 = (NIM_BOOL)0; LOC16 = !(((*t0).kind == ((Ttypekind294244) 23))); if (LOC16) goto LA17; LOC18 = (NIM_BOOL)0; LOC18 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC18) goto LA19; LOC18 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA19: ; LOC16 = !(LOC18); LA17: ; if (!LOC16) goto LA20; memset((void*)LOC22, 0, sizeof(LOC22)); LOC22[0] = r0; r0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_124), LOC22, 1); } LA20: ; LOC23 = (Ttype294840*)0; LOC23 = lastson_297377_850551059(t0); t0 = skiptypes_298099_850551059(LOC23, IL64(211106232576256)); } LA9: ; } { NIM_BOOL LOC26; LOC26 = (NIM_BOOL)0; LOC26 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC26) goto LA27; LOC26 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA27: ; if (!!(LOC26)) goto LA28; { while (1) { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = ((*t0).kind == ((Ttypekind294244) 17)); if (!(LOC32)) goto LA33; LOC32 = !(((*t0).sons->data[((NI) 0)] == NIM_NIL)); LA33: ; if (!LOC32) goto LA31; add_180487_2381377266(&r0, ((NimStringDesc*) &T839829468_153)); t0 = skiptypes_298099_850551059((*t0).sons->data[((NI) 0)], IL64(211106247215360)); } LA31: ; } } LA28: ; { TY537238 LOC38; if (!!((nilcheck0 == NIM_NIL))) goto LA36; memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = nilcheck0; LOC38[1] = r0; LOC38[2] = gentypeinfo_537941_839829468((*p0).module, dest0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_560), LOC38, 3); } goto LA34; LA36: ; { TY534811 LOC40; memset((void*)LOC40, 0, sizeof(LOC40)); LOC40[0] = r0; LOC40[1] = gentypeinfo_537941_839829468((*p0).module, dest0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_561), LOC40, 2); } LA34: ; } LA6: ; { TY534811 LOC45; Ropeobj180006* LOC46; if (!!(((*(*(*n0).kindU.S6.sons->data[((NI) 0)]).typ).kind == ((Ttypekind294244) 17)))) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC45[0] = gettypedesc_537673_839829468((*p0).module, (*n0).typ); LOC45[1] = rdloc_540188_839829468((&a0)); LOC46 = (Ropeobj180006*)0; LOC46 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_430), LOC45, 2); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC46, a0.s); } goto LA41; LA43: ; { TY534811 LOC48; Ropeobj180006* LOC49; memset((void*)LOC48, 0, sizeof(LOC48)); LOC48[0] = gettypedesc_537673_839829468((*p0).module, dest0); LOC48[1] = addrloc_540204_839829468((&a0)); LOC49 = (Ropeobj180006*)0; LOC49 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_429), LOC48, 2); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC49, a0.s); } LA41: ; } N_NIMCALL(void, genrangechck_558591_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0, NimStringDesc* magic0) { Tloc294816 a0; Ttype294840* dest0; memset((void*)(&a0), 0, sizeof(a0)); dest0 = skiptypes_298099_850551059((*n0).typ, IL64(211106240964864)); { NIM_BOOL LOC3; Ttype294840* LOC5; TY534811 LOC8; Ropeobj180006* LOC9; LOC3 = (NIM_BOOL)0; LOC3 = !((((*p0).options &(1U<<((NU)(((Toption171009) 3))&31U)))!=0)); if (LOC3) goto LA4; LOC5 = (Ttype294840*)0; LOC5 = skiptypes_298099_850551059(dest0, 1048576); LOC3 = ((IL64(34084860461056) &((NU64)1<<((NU)((*LOC5).kind)&63U)))!=0); LA4: ; if (!LOC3) goto LA6; initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = gettypedesc_537673_839829468((*p0).module, dest0); LOC8[1] = rdcharloc_540227_839829468((&a0)); LOC9 = (Ropeobj180006*)0; LOC9 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_430), LOC8, 2); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC9, a0.s); } goto LA1; LA6: ; { TY538475 LOC11; Ropeobj180006* LOC12; initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = gettypedesc_537673_839829468((*p0).module, dest0); LOC11[1] = rdcharloc_540227_839829468((&a0)); LOC11[2] = genliteral_551476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], dest0); LOC11[3] = genliteral_551476_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 2)], dest0); LOC11[4] = rope_180277_2381377266(magic0); LOC12 = (Ropeobj180006*)0; LOC12 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_562), LOC11, 5); putintodest_552468_839829468(p0, d0, dest0, LOC12, a0.s); } LA1: ; } N_NIMCALL(void, convstrtocstr_558643_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* LOC1; TY180507 LOC2; Ropeobj180006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype294840*)0; LOC1 = skiptypes_298099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_540188_839829468((&a0)); LOC3 = (Ropeobj180006*)0; LOC3 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_485), LOC2, 1); putintodest_552468_839829468(p0, d0, LOC1, LOC3, a0.s); } N_NIMCALL(void, convcstrtostr_558655_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { Tloc294816 a0; Ttype294840* LOC1; TY180507 LOC2; Ropeobj180006* LOC3; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (Ttype294840*)0; LOC1 = skiptypes_298099_850551059((*n0).typ, IL64(211106240964864)); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rdloc_540188_839829468((&a0)); LOC3 = (Ropeobj180006*)0; LOC3 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_411), LOC2, 1); putintodest_552468_839829468(p0, d0, LOC1, LOC3, a0.s); gcusage_556439_839829468(n0); } static N_INLINE(NIM_BOOL, isroutine_299324_850551059)(Tsym294834* s0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = ((258048 &(1U<<((NU)((*s0).kind)&31U)))!=0); return result0; } static N_INLINE(NIM_BOOL, isconstclosure_559810_839829468)(Tnode294802* n0) { NIM_BOOL result0; NIM_BOOL LOC1; NIM_BOOL LOC2; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC2 = (NIM_BOOL)0; LOC2 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC2)) goto LA3; LOC2 = isroutine_299324_850551059((*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym); LA3: ; LOC1 = LOC2; if (!(LOC1)) goto LA4; LOC1 = ((*(*n0).kindU.S6.sons->data[((NI) 1)]).kind == ((Tnodekind294020) 23)); LA4: ; result0 = LOC1; return result0; } N_NIMCALL(void, genclosure_559836_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { { NIM_BOOL LOC3; Ropeobj180006* tmp0; Ropeobj180006* LOC6; TY537238 LOC7; LOC3 = (NIM_BOOL)0; LOC3 = isconstclosure_559810_839829468(n0); if (!LOC3) goto LA4; (*(*p0).module).labels += ((NI) 1); LOC6 = (Ropeobj180006*)0; LOC6 = rope_180401_2381377266(((NI64) ((*(*p0).module).labels))); tmp0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_566), LOC6); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = gettypedesc_537673_839829468((*p0).module, (*n0).typ); LOC7[1] = tmp0; LOC7[2] = genconstexpr_556849_839829468(p0, n0); addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 8))- 0], ((NimStringDesc*) &T839829468_524), LOC7, 3); putintodest_552468_839829468(p0, d0, (*n0).typ, tmp0, ((Tstorageloc294812) 1)); } goto LA1; LA4: ; { Tloc294816 tmp0; Tloc294816 a0; Tloc294816 b0; TY537238 LOC14; memset((void*)(&tmp0), 0, sizeof(tmp0)); memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&b0), 0, sizeof(b0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&b0)); { Tnode294802* LOC11; LOC11 = (Tnode294802*)0; LOC11 = skipconv_330882_3876443242((*n0).kindU.S6.sons->data[((NI) 0)]); if (!((*LOC11).kind == ((Tnodekind294020) 155))) goto LA12; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_567)); } LA12: ; gettemp_539032_839829468(p0, (*n0).typ, (&tmp0), NIM_FALSE); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rdloc_540188_839829468((&tmp0)); LOC14[1] = rdloc_540188_839829468((&a0)); LOC14[2] = rdloc_540188_839829468((&b0)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_568), LOC14, 3); putlocintodest_541258_839829468(p0, d0, (&tmp0)); } LA1: ; } static N_INLINE(Ropeobj180006*, assignlabel_546020_839829468)(Tblock531019* b0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = rope_180401_2381377266(((NI64) ((*b0).id))); unsureAsgnRef((void**) (&(*b0).label), HEX26_180452_2381377266(((NimStringDesc*) &T839829468_296), LOC1)); result0 = (*b0).label; return result0; } N_NIMCALL(void, gencomputedgoto_547744_839829468)(Tcproc531021* p0, Tnode294802* n0) { NI casepos0; NI arraysize0; NI id0; Ropeobj180006* tmp0; TY180507 LOC27; Ropeobj180006* gotoarray0; TY534811 LOC28; TY180507 LOC33; NI topblock0; Ropeobj180006* oldbody0; Ropeobj180006* tailb0; Ropeobj180006* taila0; Tnode294802* casestmt0; Tloc294816 a_547871_839829468; TY534811 LOC41; { casepos0 = ((NI) -1); arraysize0 = (NI)0; { NI i_547768_839829468; NI HEX3Atmp_547934_839829468; NI LOC2; NI res_547937_839829468; i_547768_839829468 = (NI)0; HEX3Atmp_547934_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_295081_850551059(n0); HEX3Atmp_547934_839829468 = (LOC2 - 1); res_547937_839829468 = ((NI) 0); { while (1) { Tnode294802* it0; if (!(res_547937_839829468 <= HEX3Atmp_547934_839829468)) goto LA4; i_547768_839829468 = res_547937_839829468; it0 = (*n0).kindU.S6.sons->data[i_547768_839829468]; { NI64 asize0; if (!((*it0).kind == ((Tnodekind294020) 97))) goto LA7; { Tnode294802* LOC11; LOC11 = (Tnode294802*)0; LOC11 = lastson_297364_850551059(it0); if (!!(((*LOC11).kind == ((Tnodekind294020) 85)))) goto LA12; localerror_198085_155036129((*it0).info, ((NimStringDesc*) &T839829468_570)); goto BeforeRet; } LA12: ; casepos0 = i_547768_839829468; asize0 = lengthord_322007_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); { if (!(IL64(10000) < asize0)) goto LA16; localerror_198085_155036129((*it0).info, ((NimStringDesc*) &T839829468_571)); goto BeforeRet; } LA16: ; arraysize0 = ((NI) (asize0)); { NI64 LOC20; LOC20 = (NI64)0; LOC20 = firstord_322001_3876443242((*(*it0).kindU.S6.sons->data[((NI) 0)]).typ); if (!!((LOC20 == IL64(0)))) goto LA21; localerror_198085_155036129((*it0).info, ((NimStringDesc*) &T839829468_572)); goto BeforeRet; } LA21: ; } LA7: ; res_547937_839829468 += ((NI) 1); } LA4: ; } } { if (!(casepos0 < ((NI) 0))) goto LA25; localerror_198085_155036129((*n0).info, ((NimStringDesc*) &T839829468_573)); goto BeforeRet; } LA25: ; id0 = (NI)(((NI) ((*p0).labels)) + ((NI) 1)); (*p0).labels += (NI)(arraysize0 + ((NI) 1)); memset((void*)LOC27, 0, sizeof(LOC27)); LOC27[0] = rope_180401_2381377266(((NI64) (id0))); tmp0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_574), LOC27, 1); memset((void*)LOC28, 0, sizeof(LOC28)); LOC28[0] = tmp0; LOC28[1] = rope_180401_2381377266(((NI64) (arraysize0))); gotoarray0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_575), LOC28, 2); { NI i_547819_839829468; NI HEX3Atmp_547942_839829468; NI res_547945_839829468; i_547819_839829468 = (NI)0; HEX3Atmp_547942_839829468 = (NI)0; HEX3Atmp_547942_839829468 = (NI)(arraysize0 - ((NI) 1)); res_547945_839829468 = ((NI) 1); { while (1) { TY180507 LOC32; if (!(res_547945_839829468 <= HEX3Atmp_547942_839829468)) goto LA31; i_547819_839829468 = res_547945_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); LOC32[0] = rope_180401_2381377266(((NI64) ((NI)(((NI) (id0)) + i_547819_839829468)))); addf_181205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_576), LOC32, 1); res_547945_839829468 += ((NI) 1); } LA31: ; } } memset((void*)LOC33, 0, sizeof(LOC33)); LOC33[0] = rope_180401_2381377266(((NI64) ((NI)(((NI) (id0)) + arraysize0)))); addf_181205_2381377266(&gotoarray0, ((NimStringDesc*) &T839829468_577), LOC33, 1); line_534690_839829468(p0, ((Tcprocsection531011) 0), gotoarray0); topblock0 = (NI)(((*p0).blocks ? (*p0).blocks->Sup.len : 0) - ((NI) 1)); oldbody0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]), NIM_NIL); { NI j_547854_839829468; NI HEX3Atmp_547950_839829468; NI HEX3Atmp_547951_839829468; NI LOC35; NI res_547954_839829468; j_547854_839829468 = (NI)0; HEX3Atmp_547950_839829468 = (NI)0; HEX3Atmp_547951_839829468 = (NI)0; HEX3Atmp_547950_839829468 = (NI)(casepos0 + ((NI) 1)); LOC35 = (NI)0; LOC35 = len_295081_850551059(n0); HEX3Atmp_547951_839829468 = (LOC35 - 1); res_547954_839829468 = HEX3Atmp_547950_839829468; { while (1) { if (!(res_547954_839829468 <= HEX3Atmp_547951_839829468)) goto LA37; j_547854_839829468 = res_547954_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[j_547854_839829468]); res_547954_839829468 += ((NI) 1); } LA37: ; } } tailb0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]), NIM_NIL); { NI j_547866_839829468; NI HEX3Atmp_547959_839829468; NI res_547962_839829468; j_547866_839829468 = (NI)0; HEX3Atmp_547959_839829468 = (NI)0; HEX3Atmp_547959_839829468 = (NI)(casepos0 - ((NI) 1)); res_547962_839829468 = ((NI) 0); { while (1) { if (!(res_547962_839829468 <= HEX3Atmp_547959_839829468)) goto LA40; j_547866_839829468 = res_547962_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[j_547866_839829468]); res_547962_839829468 += ((NI) 1); } LA40: ; } } taila0 = (*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]; asgnRefNoCycle((void**) (&(*p0).blocks->data[topblock0].sections[(((Tcprocsection531011) 2))- 0]), HEX26_180418_2381377266(oldbody0, taila0)); casestmt0 = (*n0).kindU.S6.sons->data[casepos0]; memset((void*)(&a_547871_839829468), 0, sizeof(a_547871_839829468)); initlocexpr_541283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a_547871_839829468)); memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = tmp0; LOC41[1] = rdloc_540188_839829468((&a_547871_839829468)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_578), LOC41, 2); { NI i_547894_839829468; NI HEX3Atmp_547978_839829468; NI LOC43; NI res_547981_839829468; i_547894_839829468 = (NI)0; HEX3Atmp_547978_839829468 = (NI)0; LOC43 = (NI)0; LOC43 = len_295081_850551059(casestmt0); HEX3Atmp_547978_839829468 = (LOC43 - 1); res_547981_839829468 = ((NI) 1); { while (1) { TY535289 LOC46; NI LOC47; Tnode294802* it0; Tnode294802* LOC57; Ropeobj180006** LOC58; Ropeobj180006** LOC59; Tloc294816 a0; TY534811 LOC60; if (!(res_547981_839829468 <= HEX3Atmp_547978_839829468)) goto LA45; i_547894_839829468 = res_547981_839829468; memset((void*)LOC46, 0, sizeof(LOC46)); LOC47 = (NI)0; LOC47 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC46, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_547894_839829468]; { NI j_547910_839829468; NI HEX3Atmp_547970_839829468; NI LOC49; NI res_547973_839829468; j_547910_839829468 = (NI)0; HEX3Atmp_547970_839829468 = (NI)0; LOC49 = (NI)0; LOC49 = len_295081_850551059(it0); HEX3Atmp_547970_839829468 = (NI)(LOC49 - ((NI) 2)); res_547973_839829468 = ((NI) 0); { while (1) { NI64 val0; TY180507 LOC56; if (!(res_547973_839829468 <= HEX3Atmp_547970_839829468)) goto LA51; j_547910_839829468 = res_547973_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_547910_839829468]).kind == ((Tnodekind294020) 44))) goto LA54; localerror_198085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA54: ; val0 = getordvalue_322129_3876443242((*it0).kindU.S6.sons->data[j_547910_839829468]); memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = intliteral_541270_839829468((NI64)((NI64)(val0 + ((NI64) (id0))) + IL64(1))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_580), LOC56, 1); res_547973_839829468 += ((NI) 1); } LA51: ; } } LOC57 = (Tnode294802*)0; LOC57 = lastson_297364_850551059(it0); genstmts_541244_839829468(p0, LOC57); LOC58 = (Ropeobj180006**)0; LOC58 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC58, tailb0); LOC59 = (Ropeobj180006**)0; LOC59 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); add_180482_2381377266(LOC59, taila0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*casestmt0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC60, 0, sizeof(LOC60)); LOC60[0] = tmp0; LOC60[1] = rdloc_540188_839829468((&a0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_578), LOC60, 2); endblock_546060_839829468(p0); res_547981_839829468 += ((NI) 1); } LA45: ; } } }BeforeRet: ; } N_NIMCALL(void, genwhilestmt_547985_839829468)(Tcproc531021* p0, Tnode294802* t0) { Tloc294816 a0; NI oldbreakidx_548011_839829468; TY535289 LOC1; Tnode294802* loopbody0; memset((void*)(&a0), 0, sizeof(a0)); (*p0).withinloop += ((NI) 1); genlinedir_534823_839829468(p0, t0); oldbreakidx_548011_839829468 = (*p0).breakidx; memset((void*)LOC1, 0, sizeof(LOC1)); (*p0).breakidx = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_569), LOC1, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); { NIM_BOOL LOC4; Ropeobj180006* label0; TY534811 LOC8; LOC4 = (NIM_BOOL)0; LOC4 = !(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 6))); if (LOC4) goto LA5; LOC4 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval == IL64(0)); LA5: ; if (!LOC4) goto LA6; label0 = assignlabel_546020_839829468((&(*p0).blocks->data[(*p0).breakidx])); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468((&a0)); LOC8[1] = label0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_555), LOC8, 2); } LA6: ; loopbody0 = (*t0).kindU.S6.sons->data[((NI) 1)]; { NIM_BOOL LOC11; LOC11 = (NIM_BOOL)0; LOC11 = stmtscontainpragma_530083_2036603609(loopbody0, ((Tspecialword277003) 182)); if (!(LOC11)) goto LA12; LOC11 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 1))&7U)))!=0); LA12: ; if (!LOC11) goto LA13; { NIM_BOOL LOC17; NI LOC18; LOC17 = (NIM_BOOL)0; LOC18 = (NI)0; LOC18 = len_295081_850551059(loopbody0); LOC17 = (LOC18 == ((NI) 2)); if (!(LOC17)) goto LA19; LOC17 = ((*(*loopbody0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)); LA19: ; if (!LOC17) goto LA20; loopbody0 = (*loopbody0).kindU.S6.sons->data[((NI) 1)]; } LA20: ; gencomputedgoto_547744_839829468(p0, loopbody0); } goto LA9; LA13: ; { genstmts_541244_839829468(p0, loopbody0); } LA9: ; { TY535289 LOC27; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 19))&31U)))!=0)) goto LA25; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_581), LOC27, 0); } LA25: ; endblock_546060_839829468(p0); (*p0).breakidx = oldbreakidx_548011_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, gengotovar_546258_839829468)(Tcproc531021* p0, Tnode294802* value0) { { if (!!(((*value0).kind >= ((Tnodekind294020) 5) && (*value0).kind <= ((Tnodekind294020) 15)))) goto LA3; localerror_198085_155036129((*value0).info, ((NimStringDesc*) &T839829468_582)); } goto LA1; LA3: ; { TY180507 LOC6; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_180401_2381377266((*value0).kindU.S1.intval); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_583), LOC6, 1); } LA1: ; } N_NIMCALL(void, varindynamiclib_540812_839829468)(Tcgen531027* m0, Tsym294834* sym0) { Tlib294820* lib0; Ropeobj180006* extname0; Ropeobj180006* tmp0; TY537235 LOC1; NimStringDesc* LOC2; TY534811 LOC3; lib0 = (*sym0).annex; extname0 = (*sym0).loc.r; loaddynamiclib_561481_839829468(m0, lib0); (*sym0).loc.flags |= ((NU16)1)<<((((Tlocflag294810) 0))%(sizeof(NU16)*8)); tmp0 = mangledynlibproc_540816_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), tmp0); (*m0).labels += ((NI) 2); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = tmp0; LOC1[1] = gettypedesc_537673_839829468(m0, (*sym0).typ); LOC1[2] = (*lib0).name; LOC2 = (NimStringDesc*)0; LOC2 = HEX24_180856_2381377266(extname0); LOC1[3] = makecstring_193638_155036129(LOC2); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 16))- 0], ((NimStringDesc*) &T839829468_584), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = (*sym0).loc.r; LOC3[1] = gettypedesc_537673_839829468(m0, (*sym0).loc.t); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 9))- 0], ((NimStringDesc*) &T839829468_585), LOC3, 2); } N_NIMCALL(void, assignglobalvar_540819_839829468)(Tcproc531021* p0, Tsym294834* s0) { { { Ropeobj180006* LOC5; if (!((*s0).loc.k == ((Tlockind294808) 0))) goto LA3; LOC5 = (Ropeobj180006*)0; LOC5 = manglename_535205_839829468(s0); fillloc_534282_839829468((&(*s0).loc), ((Tlockind294808) 3), (*s0).typ, LOC5, ((Tstorageloc294812) 3)); } LA3: ; { Tcgen531027* q0; if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag294810) 4))&15U)))!=0)) goto LA8; q0 = findpendingmodule_534241_839829468((*p0).module, s0); { NIM_BOOL LOC12; NIM_BOOL LOC14; LOC12 = (NIM_BOOL)0; LOC12 = !((q0 == NIM_NIL)); if (!(LOC12)) goto LA13; LOC14 = (NIM_BOOL)0; LOC14 = containsorincl_270862_2627731572((&(*q0).declaredthings), (*s0).Sup.id); LOC12 = !(LOC14); LA13: ; if (!LOC12) goto LA15; varindynamiclib_540812_839829468(q0, s0); } goto LA10; LA15: ; { asgnRefNoCycle((void**) (&(*s0).loc.r), mangledynlibproc_540816_839829468(s0)); } LA10: ; goto BeforeRet; } LA8: ; useheader_534369_839829468((*p0).module, s0); { if (!(((*s0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)) goto LA20; goto BeforeRet; } LA20: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 22))&31U)))!=0)) goto LA24; declarethreadvar_540676_839829468((*p0).module, s0, (((*s0).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0)); } goto LA22; LA24: ; { Ropeobj180006* decl0; Ropeobj180006* td0; decl0 = NIM_NIL; td0 = gettypedesc_537673_839829468((*p0).module, (*s0).loc.t); { TY180507 LOC43; if (!(*s0).constraint == 0) goto LA29; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 5))&31U)))!=0)) goto LA33; add_180487_2381377266(&decl0, ((NimStringDesc*) &T839829468_240)); } LA33: ; add_180482_2381377266(&decl0, td0); { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 8))&31U)))!=0)) goto LA37; add_180487_2381377266(&decl0, ((NimStringDesc*) &T839829468_121)); } LA37: ; { if (!(((*s0).flags &(1U<<((NU)(((Tsymflag294184) 7))&31U)))!=0)) goto LA41; add_180487_2381377266(&decl0, ((NimStringDesc*) &T839829468_122)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = (*s0).loc.r; addf_181205_2381377266(&decl0, ((NimStringDesc*) &T839829468_242), LOC43, 1); } goto LA27; LA29: ; { NimStringDesc* LOC45; TY534811 LOC46; LOC45 = (NimStringDesc*)0; LOC45 = rawNewString((*(*s0).constraint).kindU.S3.strval->Sup.len + 3); appendString(LOC45, (*(*s0).constraint).kindU.S3.strval); appendString(LOC45, ((NimStringDesc*) &T839829468_497)); memset((void*)LOC46, 0, sizeof(LOC46)); LOC46[0] = td0; LOC46[1] = (*s0).loc.r; decl0 = HEX25_180905_2381377266(LOC45, LOC46, 2); } LA27: ; add_180482_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 9))- 0], decl0); } LA22: ; { if (!(((NI) 0) < (*p0).withinloop)) goto LA49; resetloc_540350_839829468(p0, (&(*s0).loc)); } LA49: ; { TY537238 LOC55; NimStringDesc* LOC56; NimStringDesc* LOC57; if (!(((*(*(*p0).module).module).options & 163840) == 163840)) goto LA53; memset((void*)LOC55, 0, sizeof(LOC55)); LOC56 = (NimStringDesc*)0; LOC56 = rawNewString((*(*(*s0).owner).name).s->Sup.len + (*(*s0).name).s->Sup.len + 1); appendString(LOC56, (*(*(*s0).owner).name).s); appendChar(LOC56, 46); appendString(LOC56, (*(*s0).name).s); LOC57 = (NimStringDesc*)0; LOC57 = nsuNormalize(LOC56); LOC55[0] = makecstring_193638_155036129(LOC57); LOC55[1] = (*s0).loc.r; LOC55[2] = gentypeinfo_537941_839829468((*p0).module, (*s0).typ); appcg_534632_839829468((*p0).module, &(*(*p0).module).s[(((Tcfilesection531005) 15))- 0], ((NimStringDesc*) &T839829468_586), LOC55, 3); } LA53: ; }BeforeRet: ; } N_NIMCALL(Ropeobj180006*, gentraverseprocforglobal_540032_839829468)(Tcgen531027* m0, Tsym294834* s0) { Ropeobj180006* result0; Ropeobj180006* LOC1; Ttraversalclosure539019 c0; Tcproc531021* p0; Ropeobj180006* sloc0; Ropeobj180006* header0; TY180507 LOC8; Ropeobj180006* generatedproc0; TY537235 LOC9; Ropeobj180006** LOC10; Ropeobj180006** LOC11; Ropeobj180006** LOC12; TY180507 LOC13; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = gentypeinfo_537941_839829468(m0, (*s0).loc.t); memset((void*)(&c0), 0, sizeof(c0)); p0 = newproc_531206_3723162438(NIM_NIL, m0); sloc0 = (*s0).loc.r; result0 = gettempname_535598_839829468(m0); { NIM_BOOL LOC4; LOC4 = (NIM_BOOL)0; LOC4 = (((*s0).flags &(1U<<((NU)(((Tsymflag294184) 22))&31U)))!=0); if (!(LOC4)) goto LA5; LOC4 = emulatedthreadvars_534949_839829468(); LA5: ; if (!LOC4) goto LA6; accessthreadlocalvar_534945_839829468(p0, s0); sloc0 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_288), sloc0); } LA6: ; c0.visitorfrmt = copyString(((NimStringDesc*) &T839829468_587)); c0.p = p0; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = result0; header0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_588), LOC8, 1); gentraverseproc_539022_839829468((&c0), sloc0, (*s0).loc.t); memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = header0; LOC10 = (Ropeobj180006**)0; LOC10 = s_531179_3723162438(p0, ((Tcprocsection531011) 0)); LOC9[1] = (*LOC10); LOC11 = (Ropeobj180006**)0; LOC11 = s_531179_3723162438(p0, ((Tcprocsection531011) 1)); LOC9[2] = (*LOC11); LOC12 = (Ropeobj180006**)0; LOC12 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); LOC9[3] = (*LOC12); generatedproc0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_190), LOC9, 4); memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = header0; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 7))- 0], ((NimStringDesc*) &T839829468_191), LOC13, 1); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 10))- 0], generatedproc0); return result0; } N_NIMCALL(void, registergcroot_545762_839829468)(Tcproc531021* p0, Tsym294834* v0) { { NIM_BOOL LOC3; Ropeobj180006* prc0; Ropeobj180006** LOC7; TY180507 LOC8; LOC3 = (NIM_BOOL)0; LOC3 = ((240 &(1U<<((NU)(gselectedgc_171133_2607990831)&7U)))!=0); if (!(LOC3)) goto LA4; LOC3 = containsgarbagecollectedref_322117_3876443242((*v0).loc.t); LA4: ; if (!LOC3) goto LA5; prc0 = gentraverseprocforglobal_540032_839829468((*p0).module, v0); LOC7 = (Ropeobj180006**)0; LOC7 = procsec_531194_3723162438((*(*p0).module).initproc, ((Tcprocsection531011) 1)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = prc0; appcg_534632_839829468((*p0).module, LOC7, ((NimStringDesc*) &T839829468_589), LOC8, 1); } LA5: ; } static N_INLINE(NIM_BOOL, isassignedimmediately_545781_839829468)(Tnode294802* n0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { if (!((*n0).kind == ((Tnodekind294020) 1))) goto LA3; result0 = NIM_FALSE; goto BeforeRet; } LA3: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = isinvalidreturntype_535550_839829468((*n0).typ); if (!LOC7) goto LA8; result0 = NIM_FALSE; goto BeforeRet; } LA8: ; result0 = NIM_TRUE; }BeforeRet: ; return result0; } N_NIMCALL(void, genasgncall_545695_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* d0) { { Ttype294840* LOC3; LOC3 = (Ttype294840*)0; LOC3 = skiptypes_298099_850551059((*(*ri0).kindU.S6.sons->data[((NI) 0)]).typ, 2048); if (!((*LOC3).callconv == ((Tcallingconvention294002) 8))) goto LA4; genclosurecall_542452_839829468(p0, le0, ri0, d0); } goto LA1; LA4: ; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC7)) goto LA8; LOC7 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; geninfixcall_543929_839829468(p0, le0, ri0, d0); } goto LA1; LA9: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = ((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC12)) goto LA13; LOC12 = (((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 28))&31U)))!=0); LA13: ; if (!LOC12) goto LA14; gennamedparamcall_544616_839829468(p0, ri0, d0); } goto LA1; LA14: ; { genprefixcall_541960_839829468(p0, le0, ri0, d0); } LA1: ; poststmtactions_534942_839829468(p0); } static N_INLINE(void, loadinto_545928_839829468)(Tcproc531021* p0, Tnode294802* le0, Tnode294802* ri0, Tloc294816* a0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; LOC3 = (NIM_BOOL)0; LOC3 = ((*ri0).kind == ((Tnodekind294020) 27) || (*ri0).kind == ((Tnodekind294020) 29) || (*ri0).kind == ((Tnodekind294020) 30) || (*ri0).kind == ((Tnodekind294020) 31) || (*ri0).kind == ((Tnodekind294020) 26) || (*ri0).kind == ((Tnodekind294020) 28) || (*ri0).kind == ((Tnodekind294020) 32)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = !(((*(*ri0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3))); if (LOC5) goto LA6; LOC5 = ((*(*(*ri0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).magic == ((Tmagic294524) 0)); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; genasgncall_545695_839829468(p0, le0, ri0, a0); } goto LA1; LA7: ; { if (!((*ri0).kind == ((Tnodekind294020) 47) || (*ri0).kind == ((Tnodekind294020) 65))) goto LA10; genderef_545921_839829468(p0, ri0, a0, NIM_TRUE); } goto LA1; LA10: ; { expr_541248_839829468(p0, ri0, a0); } LA1: ; } N_NIMCALL(void, gensinglevar_546276_839829468)(Tcproc531021* p0, Tnode294802* a0) { Tsym294834* v0; Tcproc531021* targetproc0; { v0 = (*(*a0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { if (!!(((1082130432 & (*v0).flags) == 0))) goto LA3; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag294184) 30))&31U)))!=0)) goto LA7; gengotovar_546258_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 2)]); } LA7: ; goto BeforeRet; } LA3: ; targetproc0 = p0; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag294184) 3))&31U)))!=0)) goto LA11; { NIM_BOOL LOC15; NIM_BOOL LOC16; LOC15 = (NIM_BOOL)0; LOC16 = (NIM_BOOL)0; LOC16 = (((*v0).flags & 96) == 32); if (!(LOC16)) goto LA17; LOC16 = ((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 1)); LA17: ; LOC15 = LOC16; if (!(LOC15)) goto LA18; LOC15 = !((((*v0).loc.flags & 72) == 0)); LA18: ; if (!LOC15) goto LA19; goto BeforeRet; } LA19: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag294184) 9))&31U)))!=0)) goto LA23; targetproc0 = (*(*p0).module).preinitproc; } LA23: ; assignglobalvar_540819_839829468(targetproc0, v0); genobjectinit_540242_839829468((*(*p0).module).preinitproc, ((Tcprocsection531011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = (((*v0).flags &(1U<<((NU)(((Tsymflag294184) 6))&31U)))!=0); if (!(LOC27)) goto LA28; LOC27 = !((generatedheader_534201_839829468 == NIM_NIL)); LA28: ; if (!LOC27) goto LA29; genvarprototypeaux_546254_839829468(generatedheader_534201_839829468, v0); } LA29: ; registergcroot_545762_839829468(p0, v0); } goto LA9; LA11: ; { Tnode294802* value0; NIM_BOOL imm0; value0 = (*a0).kindU.S6.sons->data[((NI) 2)]; imm0 = isassignedimmediately_545781_839829468(value0); { NIM_BOOL LOC34; NIM_BOOL LOC35; NIM_BOOL LOC36; NIM_BOOL LOC38; NIM_BOOL LOC42; Ropeobj180006* decl0; Tloc294816 tmp0; LOC34 = (NIM_BOOL)0; LOC35 = (NIM_BOOL)0; LOC36 = (NIM_BOOL)0; LOC36 = imm0; if (!(LOC36)) goto LA37; LOC38 = (NIM_BOOL)0; LOC38 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC38) goto LA39; LOC38 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA39: ; LOC36 = LOC38; LA37: ; LOC35 = LOC36; if (!(LOC35)) goto LA40; LOC35 = ((*p0).splitdecls == ((NI) 0)); LA40: ; LOC34 = LOC35; if (!(LOC34)) goto LA41; LOC42 = (NIM_BOOL)0; LOC42 = containshiddenpointer_322120_3876443242((*v0).typ); LOC34 = !(LOC42); LA41: ; if (!LOC34) goto LA43; genlinedir_534823_839829468(p0, a0); decl0 = localvardecl_540532_839829468(p0, v0); memset((void*)(&tmp0), 0, sizeof(tmp0)); { NIM_BOOL LOC47; NIM_BOOL LOC48; Tnode294802* LOC50; Tnode294802* LOC52; Ropeobj180006* params0; Ttype294840* typ0; TY534811 LOC66; LOC47 = (NIM_BOOL)0; LOC48 = (NIM_BOOL)0; LOC48 = ((*value0).kind == ((Tnodekind294020) 27) || (*value0).kind == ((Tnodekind294020) 29) || (*value0).kind == ((Tnodekind294020) 30) || (*value0).kind == ((Tnodekind294020) 31) || (*value0).kind == ((Tnodekind294020) 26) || (*value0).kind == ((Tnodekind294020) 28) || (*value0).kind == ((Tnodekind294020) 32)); if (!(LOC48)) goto LA49; LOC50 = (Tnode294802*)0; LOC50 = HEX5BHEX5D_295238_850551059(value0, ((NI) 0)); LOC48 = ((*LOC50).kind == ((Tnodekind294020) 3)); LA49: ; LOC47 = LOC48; if (!(LOC47)) goto LA51; LOC52 = (Tnode294802*)0; LOC52 = HEX5BHEX5D_295238_850551059(value0, ((NI) 0)); LOC47 = (((*(*LOC52).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 24))&31U)))!=0); LA51: ; if (!LOC47) goto LA53; params0 = (Ropeobj180006*)0; typ0 = skiptypes_298099_850551059((*(*value0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106232576256)); { NI i_546619_839829468; NI HEX3Atmp_546825_839829468; NI LOC56; NI res_546828_839829468; i_546619_839829468 = (NI)0; HEX3Atmp_546825_839829468 = (NI)0; LOC56 = (NI)0; LOC56 = len_295081_850551059(value0); HEX3Atmp_546825_839829468 = (LOC56 - 1); res_546828_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC65; if (!(res_546828_839829468 <= HEX3Atmp_546825_839829468)) goto LA58; i_546619_839829468 = res_546828_839829468; { TY535289 LOC63; Ropeobj180006* LOC64; if (!!((params0 == NIM_NIL))) goto LA61; memset((void*)LOC63, 0, sizeof(LOC63)); LOC64 = (Ropeobj180006*)0; LOC64 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_110), LOC63, 0); add_180482_2381377266(&params0, LOC64); } LA61: ; LOC65 = (Ropeobj180006*)0; LOC65 = genotherarg_541277_839829468(p0, value0, i_546619_839829468, typ0); add_180482_2381377266(&params0, LOC65); res_546828_839829468 += ((NI) 1); } LA58: ; } } memset((void*)LOC66, 0, sizeof(LOC66)); LOC66[0] = decl0; LOC66[1] = params0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_590), LOC66, 2); } goto LA45; LA53: ; { TY534811 LOC68; initlocexprsingleuse_541289_839829468(p0, value0, (&tmp0)); memset((void*)LOC68, 0, sizeof(LOC68)); LOC68[0] = decl0; LOC68[1] = rdloc_540188_839829468((&tmp0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_591), LOC68, 2); } LA45: ; goto BeforeRet; } LA43: ; assignlocalvar_540614_839829468(p0, v0); initlocalvar_540398_839829468(p0, v0, imm0); } LA9: ; { if (!!(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 1)))) goto LA71; genlinedir_534823_839829468(targetproc0, a0); loadinto_545928_839829468(targetproc0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&(*v0).loc)); } LA71: ; }BeforeRet: ; } N_NIMCALL(void, genclosurevar_546832_839829468)(Tcproc531021* p0, Tnode294802* a0) { NIM_BOOL immediateasgn0; immediateasgn0 = !(((*(*a0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 1))); { Tloc294816 v0; if (!immediateasgn0) goto LA3; memset((void*)(&v0), 0, sizeof(v0)); initlocexpr_541283_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (&v0)); genlinedir_534823_839829468(p0, a0); loadinto_545928_839829468(p0, (*a0).kindU.S6.sons->data[((NI) 0)], (*a0).kindU.S6.sons->data[((NI) 2)], (&v0)); } LA3: ; } N_NIMCALL(void, genvartuple_545794_839829468)(Tcproc531021* p0, Tnode294802* n0) { Tloc294816 tup0; Tloc294816 field0; NI L0; NIM_BOOL uselowering0; Ttype294840* t0; { memset((void*)(&tup0), 0, sizeof(tup0)); memset((void*)(&field0), 0, sizeof(field0)); { if (!!(((*n0).kind == ((Tnodekind294020) 36)))) goto LA3; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA3: ; L0 = sonslen_297351_850551059(n0); uselowering0 = NIM_FALSE; { NI i_545822_839829468; NI HEX3Atmp_545905_839829468; NI res_545908_839829468; i_545822_839829468 = (NI)0; HEX3Atmp_545905_839829468 = (NI)0; HEX3Atmp_545905_839829468 = (NI)(L0 - ((NI) 3)); res_545908_839829468 = ((NI) 0); { while (1) { if (!(res_545908_839829468 <= HEX3Atmp_545905_839829468)) goto LA7; i_545822_839829468 = res_545908_839829468; { Tnode294802* LOC10; LOC10 = (Tnode294802*)0; LOC10 = HEX5BHEX5D_295238_850551059(n0, i_545822_839829468); if (!!(((*LOC10).kind == ((Tnodekind294020) 3)))) goto LA11; uselowering0 = NIM_TRUE; goto LA5; } LA11: ; res_545908_839829468 += ((NI) 1); } LA7: ; } } LA5: ; { Tnode294802* LOC17; if (!uselowering0) goto LA15; LOC17 = (Tnode294802*)0; LOC17 = lowertupleunpacking_435037_2218250499(n0, (*p0).prc); genstmts_541244_839829468(p0, LOC17); goto BeforeRet; } LA15: ; genlinedir_534823_839829468(p0, n0); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[(NI)(L0 - ((NI) 1))], (&tup0)); t0 = getuniquetype_530640_2036603609(tup0.t); { NI i_545846_839829468; NI HEX3Atmp_545914_839829468; NI res_545917_839829468; i_545846_839829468 = (NI)0; HEX3Atmp_545914_839829468 = (NI)0; HEX3Atmp_545914_839829468 = (NI)(L0 - ((NI) 3)); res_545917_839829468 = ((NI) 0); { while (1) { if (!(res_545917_839829468 <= HEX3Atmp_545914_839829468)) goto LA20; i_545846_839829468 = res_545917_839829468; { Tsym294834* v0; v0 = (*(*n0).kindU.S6.sons->data[i_545846_839829468]).kindU.S4.sym; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag294184) 23))&31U)))!=0)) goto LA24; goto LA21; } LA24: ; { if (!(((*v0).flags &(1U<<((NU)(((Tsymflag294184) 3))&31U)))!=0)) goto LA28; assignglobalvar_540819_839829468(p0, v0); genobjectinit_540242_839829468(p0, ((Tcprocsection531011) 1), (*v0).typ, (&(*v0).loc), NIM_TRUE); registergcroot_545762_839829468(p0, v0); } goto LA26; LA28: ; { Tnode294802* LOC31; NIM_BOOL LOC32; assignlocalvar_540614_839829468(p0, v0); LOC31 = (Tnode294802*)0; LOC31 = HEX5BHEX5D_295238_850551059(n0, (NI)(L0 - ((NI) 1))); LOC32 = (NIM_BOOL)0; LOC32 = isassignedimmediately_545781_839829468(LOC31); initlocalvar_540398_839829468(p0, v0, LOC32); } LA26: ; initloc_534273_839829468((&field0), ((Tlockind294808) 6), (*t0).sons->data[i_545846_839829468], tup0.s); { TY534811 LOC37; if (!((*t0).kind == ((Ttypekind294244) 18))) goto LA35; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = rdloc_540188_839829468((&tup0)); LOC37[1] = rope_180401_2381377266(((NI64) (i_545846_839829468))); field0.r = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_185), LOC37, 2); } goto LA33; LA35: ; { TY534811 LOC43; { if (!!(((*(*(*t0).n).kindU.S6.sons->data[i_545846_839829468]).kind == ((Tnodekind294020) 3)))) goto LA41; internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_592)); } LA41: ; memset((void*)LOC43, 0, sizeof(LOC43)); LOC43[0] = rdloc_540188_839829468((&tup0)); LOC43[1] = manglerecfieldname_536361_839829468((*(*(*t0).n).kindU.S6.sons->data[i_545846_839829468]).kindU.S4.sym, t0); field0.r = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_90), LOC43, 2); } LA33: ; putlocintodest_541258_839829468(p0, (&(*v0).loc), (&field0)); } LA21: ; res_545917_839829468 += ((NI) 1); } LA20: ; } } }BeforeRet: ; } N_NIMCALL(void, genvarstmt_546854_839829468)(Tcproc531021* p0, Tnode294802* n0) { { NI i_546869_839829468; NI HEX3Atmp_546902_839829468; NI LOC2; NI res_546905_839829468; i_546869_839829468 = (NI)0; HEX3Atmp_546902_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(n0); HEX3Atmp_546902_839829468 = (NI)(LOC2 - ((NI) 1)); res_546905_839829468 = ((NI) 0); { while (1) { if (!(res_546905_839829468 <= HEX3Atmp_546902_839829468)) goto LA4; i_546869_839829468 = res_546905_839829468; { Tnode294802* a0; a0 = (*n0).kindU.S6.sons->data[i_546869_839829468]; { if (!((*a0).kind == ((Tnodekind294020) 125))) goto LA8; goto LA5; } LA8: ; { if (!((*a0).kind == ((Tnodekind294020) 35))) goto LA12; { if (!((*(*a0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3))) goto LA16; gensinglevar_546276_839829468(p0, a0); } goto LA14; LA16: ; { genclosurevar_546832_839829468(p0, a0); } LA14: ; } goto LA10; LA12: ; { genvartuple_545794_839829468(p0, a0); } LA10: ; } LA5: ; res_546905_839829468 += ((NI) 1); } LA4: ; } } } static N_INLINE(NIM_BOOL, emitlazily_534248_839829468)(Tsym294834* s0) { NIM_BOOL result0; NIM_BOOL LOC1; Tsym294834* LOC3; result0 = (NIM_BOOL)0; LOC1 = (NIM_BOOL)0; LOC1 = ((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 2))&63U)))!=0); if (LOC1) goto LA2; LOC3 = (Tsym294834*)0; LOC3 = getmodule_301123_2984716966(s0); LOC1 = (((*LOC3).flags &(1U<<((NU)(((Tsymflag294184) 25))&31U)))!=0); LA2: ; result0 = LOC1; return result0; } N_NIMCALL(void, genconststmt_546909_839829468)(Tcproc531021* p0, Tnode294802* t0) { { NI i_546924_839829468; NI HEX3Atmp_546975_839829468; NI LOC2; NI res_546978_839829468; i_546924_839829468 = (NI)0; HEX3Atmp_546975_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(t0); HEX3Atmp_546975_839829468 = (NI)(LOC2 - ((NI) 1)); res_546978_839829468 = ((NI) 0); { while (1) { if (!(res_546978_839829468 <= HEX3Atmp_546975_839829468)) goto LA4; i_546924_839829468 = res_546978_839829468; { Tnode294802* it0; Tsym294834* c0; it0 = (*t0).kindU.S6.sons->data[i_546924_839829468]; { if (!((*it0).kind == ((Tnodekind294020) 125))) goto LA8; goto LA5; } LA8: ; { if (!!(((*it0).kind == ((Tnodekind294020) 102)))) goto LA12; internalerror_198100_155036129((*t0).info, ((NimStringDesc*) &T839829468_593)); } LA12: ; c0 = (*(*it0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC16; LOC16 = (NIM_BOOL)0; LOC16 = containscompiletimeonly_330721_3876443242((*c0).typ); if (!LOC16) goto LA17; goto LA5; } goto LA14; LA17: ; { NIM_BOOL LOC20; NIM_BOOL LOC21; NI LOC24; LOC20 = (NIM_BOOL)0; LOC21 = (NIM_BOOL)0; LOC21 = ((17629200 &((NU64)1<<((NU)((*(*c0).typ).kind)&63U)))!=0); if (!(LOC21)) goto LA22; LOC21 = !((((*c0).loc.flags &(1U<<((NU)(((Tlocflag294810) 3))&15U)))!=0)); LA22: ; LOC20 = LOC21; if (!(LOC20)) goto LA23; LOC24 = (NI)0; LOC24 = len_295081_850551059((*c0).ast); LOC20 = !((LOC24 == ((NI) 0))); LA23: ; if (!LOC20) goto LA25; { NIM_BOOL LOC29; LOC29 = (NIM_BOOL)0; LOC29 = emitlazily_534248_839829468(c0); if (!!(LOC29)) goto LA30; requestconstimpl_541240_839829468(p0, c0); } LA30: ; } goto LA14; LA25: ; LA14: ; } LA5: ; res_546978_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, gencasestringbranch_549100_839829468)(Tcproc531021* p0, Tnode294802* b0, Tloc294816* e0, Ropeobj180006* labl0, Ropeobj180006** branches0, NI branches0Len0) { Tloc294816 x0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); length0 = sonslen_297351_850551059(b0); { NI i_549122_839829468; NI HEX3Atmp_549410_839829468; NI res_549413_839829468; i_549122_839829468 = (NI)0; HEX3Atmp_549410_839829468 = (NI)0; HEX3Atmp_549410_839829468 = (NI)(length0 - ((NI) 2)); res_549413_839829468 = ((NI) 0); { while (1) { NI j0; NI64 LOC4; TY537238 LOC5; if (!(res_549413_839829468 <= HEX3Atmp_549410_839829468)) goto LA3; i_549122_839829468 = res_549413_839829468; initlocexpr_541283_839829468(p0, (*b0).kindU.S6.sons->data[i_549122_839829468], (&x0)); LOC4 = (NI64)0; LOC4 = hashstring_530100_2036603609((*(*b0).kindU.S6.sons->data[i_549122_839829468]).kindU.S3.strval); j0 = ((NI) ((NI64)(LOC4 & ((NI64) ((branches0Len0-1)))))); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468(e0); LOC5[1] = rdloc_540188_839829468((&x0)); LOC5[2] = labl0; appcg_534632_839829468((*p0).module, &branches0[j0], ((NimStringDesc*) &T839829468_595), LOC5, 3); res_549413_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, exprblock_546103_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { TY535289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); expr_541248_839829468(p0, n0, d0); endblock_546060_839829468(p0); } N_NIMCALL(Ropeobj180006*, gencasesecondpass_548965_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NI labid0, NI until0) { Ropeobj180006* result0; Ropeobj180006* lend0; result0 = (Ropeobj180006*)0; lend0 = getlabel_541217_839829468(p0); { NI i_548984_839829468; NI res_549017_839829468; i_548984_839829468 = (NI)0; res_549017_839829468 = ((NI) 1); { while (1) { TY180507 LOC10; if (!(res_549017_839829468 <= until0)) goto LA3; i_548984_839829468 = res_549017_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC6)) goto LA7; LOC6 = isemptytype_299441_850551059((*t0).typ); LA7: ; if (!LOC6) goto LA8; (*d0).k = ((Tlockind294808) 0); } LA8: ; memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rope_180401_2381377266(((NI64) ((NI)(labid0 + i_548984_839829468)))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_599), LOC10, 1); { NI length0; TY180507 LOC15; if (!((*(*t0).kindU.S6.sons->data[i_548984_839829468]).kind == ((Tnodekind294020) 85))) goto LA13; length0 = sonslen_297351_850551059((*t0).kindU.S6.sons->data[i_548984_839829468]); exprblock_546103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_548984_839829468]).kindU.S6.sons->data[(NI)(length0 - ((NI) 1))], d0); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = lend0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_556), LOC15, 1); } goto LA11; LA13: ; { exprblock_546103_839829468(p0, (*(*t0).kindU.S6.sons->data[i_548984_839829468]).kindU.S6.sons->data[((NI) 0)], d0); } LA11: ; res_549017_839829468 += ((NI) 1); } LA3: ; } } result0 = lend0; return result0; } N_NIMCALL(void, gencasegenericbranch_548910_839829468)(Tcproc531021* p0, Tnode294802* b0, Tloc294816* e0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, Ropeobj180006* labl0) { Tloc294816 x0; Tloc294816 y0; NI length0; memset((void*)(&x0), 0, sizeof(x0)); memset((void*)(&y0), 0, sizeof(y0)); length0 = sonslen_297351_850551059(b0); { NI i_548932_839829468; NI HEX3Atmp_548958_839829468; NI res_548961_839829468; i_548932_839829468 = (NI)0; HEX3Atmp_548958_839829468 = (NI)0; HEX3Atmp_548958_839829468 = (NI)(length0 - ((NI) 2)); res_548961_839829468 = ((NI) 0); { while (1) { if (!(res_548961_839829468 <= HEX3Atmp_548958_839829468)) goto LA3; i_548932_839829468 = res_548961_839829468; { TY537235 LOC8; if (!((*(*b0).kindU.S6.sons->data[i_548932_839829468]).kind == ((Tnodekind294020) 44))) goto LA6; initlocexpr_541283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_548932_839829468]).kindU.S6.sons->data[((NI) 0)], (&x0)); initlocexpr_541283_839829468(p0, (*(*b0).kindU.S6.sons->data[i_548932_839829468]).kindU.S6.sons->data[((NI) 1)], (&y0)); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdcharloc_540227_839829468(e0); LOC8[1] = rdcharloc_540227_839829468((&x0)); LOC8[2] = rdcharloc_540227_839829468((&y0)); LOC8[3] = labl0; linecg_534707_839829468(p0, ((Tcprocsection531011) 2), rangeformat0, LOC8, 4); } goto LA4; LA6: ; { TY537238 LOC10; initlocexpr_541283_839829468(p0, (*b0).kindU.S6.sons->data[i_548932_839829468], (&x0)); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = rdcharloc_540227_839829468(e0); LOC10[1] = rdcharloc_540227_839829468((&x0)); LOC10[2] = labl0; linecg_534707_839829468(p0, ((Tcprocsection531011) 2), eqformat0, LOC10, 3); } LA4: ; res_548961_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(Ropeobj180006*, genifforcaseuntil_549021_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0, NI until0, Tloc294816* a0) { Ropeobj180006* result0; NI labid0; result0 = (Ropeobj180006*)0; labid0 = (*p0).labels; { NI i_549042_839829468; NI res_549083_839829468; i_549042_839829468 = (NI)0; res_549083_839829468 = ((NI) 1); { while (1) { if (!(res_549083_839829468 <= until0)) goto LA3; i_549042_839829468 = res_549083_839829468; (*p0).labels += ((NI) 1); { Ropeobj180006* LOC8; Ropeobj180006* LOC9; if (!((*(*t0).kindU.S6.sons->data[i_549042_839829468]).kind == ((Tnodekind294020) 85))) goto LA6; LOC8 = (Ropeobj180006*)0; LOC8 = rope_180401_2381377266(((NI64) ((*p0).labels))); LOC9 = (Ropeobj180006*)0; LOC9 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_296), LOC8); gencasegenericbranch_548910_839829468(p0, (*t0).kindU.S6.sons->data[i_549042_839829468], a0, rangeformat0, eqformat0, LOC9); } goto LA4; LA6: ; { TY180507 LOC11; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rope_180401_2381377266(((NI64) ((*p0).labels))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_598), LOC11, 1); } LA4: ; res_549083_839829468 += ((NI) 1); } LA3: ; } } { NI LOC14; NI gototarget0; TY180507 LOC17; TY180507 LOC18; LOC14 = (NI)0; LOC14 = len_295081_850551059(t0); if (!(until0 < (NI)(LOC14 - ((NI) 1)))) goto LA15; (*p0).labels += ((NI) 1); gototarget0 = (*p0).labels; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = rope_180401_2381377266(((NI64) (gototarget0))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_598), LOC17, 1); result0 = gencasesecondpass_548965_839829468(p0, t0, d0, ((NI) (labid0)), until0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = rope_180401_2381377266(((NI64) (gototarget0))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_599), LOC18, 1); } goto LA12; LA15: ; { result0 = gencasesecondpass_548965_839829468(p0, t0, d0, ((NI) (labid0)), until0); } LA12: ; return result0; } N_NIMCALL(void, gencasegeneric_549087_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0, NimStringDesc* rangeformat0, NimStringDesc* eqformat0) { Tloc294816 a0; Ropeobj180006* lend0; NI LOC1; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); LOC1 = (NI)0; LOC1 = sonslen_297351_850551059(t0); lend0 = genifforcaseuntil_549021_839829468(p0, t0, d0, rangeformat0, eqformat0, (NI)(LOC1 - ((NI) 1)), (&a0)); fixlabel_541230_839829468(p0, lend0); } N_NIMCALL(void, genstringcase_549417_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { NI strings0; strings0 = ((NI) 0); { NI i_549435_839829468; NI HEX3Atmp_549550_839829468; NI LOC2; NI res_549553_839829468; i_549435_839829468 = (NI)0; HEX3Atmp_549550_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(t0); HEX3Atmp_549550_839829468 = (NI)(LOC2 - ((NI) 1)); res_549553_839829468 = ((NI) 1); { while (1) { if (!(res_549553_839829468 <= HEX3Atmp_549550_839829468)) goto LA4; i_549435_839829468 = res_549553_839829468; { NI LOC9; if (!((*(*t0).kindU.S6.sons->data[i_549435_839829468]).kind == ((Tnodekind294020) 85))) goto LA7; LOC9 = (NI)0; LOC9 = sonslen_297351_850551059((*t0).kindU.S6.sons->data[i_549435_839829468]); strings0 += (NI)(LOC9 - ((NI) 1)); } LA7: ; res_549553_839829468 += ((NI) 1); } LA4: ; } } { NI bitmask0; NI LOC14; TY193350* branches0; Tloc294816 a0; NI labid0; TY534811 LOC26; TY535289 LOC35; Ropeobj180006* lend0; NI LOC42; if (!(((NI) 8) < strings0)) goto LA12; LOC14 = (NI)0; LOC14 = nextpoweroftwo_101629_1009420244(strings0); bitmask0 = (NI)(LOC14 - ((NI) 1)); branches0 = (TY193350*)0; branches0 = (TY193350*) newSeq((&NTI193350), ((NI) ((NI)(bitmask0 + ((NI) 1))))); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); labid0 = (*p0).labels; { NI i_549484_839829468; NI HEX3Atmp_549560_839829468; NI LOC16; NI res_549563_839829468; i_549484_839829468 = (NI)0; HEX3Atmp_549560_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_297351_850551059(t0); HEX3Atmp_549560_839829468 = (NI)(LOC16 - ((NI) 1)); res_549563_839829468 = ((NI) 1); { while (1) { if (!(res_549563_839829468 <= HEX3Atmp_549560_839829468)) goto LA18; i_549484_839829468 = res_549563_839829468; (*p0).labels += ((NI) 1); { Ropeobj180006* LOC23; Ropeobj180006* LOC24; if (!((*(*t0).kindU.S6.sons->data[i_549484_839829468]).kind == ((Tnodekind294020) 85))) goto LA21; LOC23 = (Ropeobj180006*)0; LOC23 = rope_180401_2381377266(((NI64) ((*p0).labels))); LOC24 = (Ropeobj180006*)0; LOC24 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_296), LOC23); gencasestringbranch_549100_839829468(p0, (*t0).kindU.S6.sons->data[i_549484_839829468], (&a0), LOC24, branches0->data, branches0->Sup.len); } goto LA19; LA21: ; { } LA19: ; res_549563_839829468 += ((NI) 1); } LA18: ; } } memset((void*)LOC26, 0, sizeof(LOC26)); LOC26[0] = rdloc_540188_839829468((&a0)); LOC26[1] = rope_180401_2381377266(((NI64) (bitmask0))); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_596), LOC26, 2); { NI j_549518_839829468; NI HEX3Atmp_549568_839829468; NI res_549571_839829468; j_549518_839829468 = (NI)0; HEX3Atmp_549568_839829468 = (NI)0; HEX3Atmp_549568_839829468 = (branches0 ? (branches0->Sup.len-1) : -1); res_549571_839829468 = ((NI) 0); { while (1) { if (!(res_549571_839829468 <= HEX3Atmp_549568_839829468)) goto LA29; j_549518_839829468 = res_549571_839829468; { TY534811 LOC34; if (!!((branches0->data[j_549518_839829468] == NIM_NIL))) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = intliteral_541270_839829468(((NI64) (j_549518_839829468))); LOC34[1] = branches0->data[j_549518_839829468]; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_597), LOC34, 2); } LA32: ; res_549571_839829468 += ((NI) 1); } LA29: ; } } memset((void*)LOC35, 0, sizeof(LOC35)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC35, 0); { NI LOC38; TY180507 LOC41; LOC38 = (NI)0; LOC38 = sonslen_297351_850551059(t0); if (!!(((*(*t0).kindU.S6.sons->data[(NI)(LOC38 - ((NI) 1))]).kind == ((Tnodekind294020) 85)))) goto LA39; memset((void*)LOC41, 0, sizeof(LOC41)); LOC41[0] = rope_180401_2381377266(((NI64) ((*p0).labels))); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_598), LOC41, 1); } LA39: ; LOC42 = (NI)0; LOC42 = sonslen_297351_850551059(t0); lend0 = gencasesecondpass_548965_839829468(p0, t0, d0, ((NI) (labid0)), (NI)(LOC42 - ((NI) 1))); fixlabel_541230_839829468(p0, lend0); } goto LA10; LA12: ; { gencasegeneric_549087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_490), ((NimStringDesc*) &T839829468_595)); } LA10: ; } N_NIMCALL(void, gengotoforcase_547673_839829468)(Tcproc531021* p0, Tnode294802* casestmt0) { { { NI i_547695_839829468; NI HEX3Atmp_547737_839829468; NI LOC2; NI res_547740_839829468; i_547695_839829468 = (NI)0; HEX3Atmp_547737_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_295081_850551059(casestmt0); HEX3Atmp_547737_839829468 = (LOC2 - 1); res_547740_839829468 = ((NI) 1); { while (1) { TY535289 LOC5; NI LOC6; Tnode294802* it0; Tnode294802* LOC16; if (!(res_547740_839829468 <= HEX3Atmp_547737_839829468)) goto LA4; i_547695_839829468 = res_547740_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC6 = (NI)0; LOC6 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC5, 0); it0 = (*casestmt0).kindU.S6.sons->data[i_547695_839829468]; { NI j_547711_839829468; NI HEX3Atmp_547730_839829468; NI LOC8; NI res_547733_839829468; j_547711_839829468 = (NI)0; HEX3Atmp_547730_839829468 = (NI)0; LOC8 = (NI)0; LOC8 = len_295081_850551059(it0); HEX3Atmp_547730_839829468 = (NI)(LOC8 - ((NI) 2)); res_547733_839829468 = ((NI) 0); { while (1) { NI64 val0; TY180507 LOC15; if (!(res_547733_839829468 <= HEX3Atmp_547730_839829468)) goto LA10; j_547711_839829468 = res_547733_839829468; { if (!((*(*it0).kindU.S6.sons->data[j_547711_839829468]).kind == ((Tnodekind294020) 44))) goto LA13; localerror_198085_155036129((*it0).info, ((NimStringDesc*) &T839829468_579)); goto BeforeRet; } LA13: ; val0 = getordvalue_322129_3876443242((*it0).kindU.S6.sons->data[j_547711_839829468]); memset((void*)LOC15, 0, sizeof(LOC15)); LOC15[0] = rope_180401_2381377266(val0); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_602), LOC15, 1); res_547733_839829468 += ((NI) 1); } LA10: ; } } LOC16 = (Tnode294802*)0; LOC16 = lastson_297364_850551059(it0); genstmts_541244_839829468(p0, LOC16); endblock_546060_839829468(p0); res_547740_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; } N_NIMCALL(NIM_BOOL, branchhastoobigrange_549576_839829468)(Tnode294802* b0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { NI i_549591_839829468; NI HEX3Atmp_549609_839829468; NI LOC2; NI res_549612_839829468; i_549591_839829468 = (NI)0; HEX3Atmp_549609_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(b0); HEX3Atmp_549609_839829468 = (NI)(LOC2 - ((NI) 2)); res_549612_839829468 = ((NI) 0); { while (1) { if (!(res_549612_839829468 <= HEX3Atmp_549609_839829468)) goto LA4; i_549591_839829468 = res_549612_839829468; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*b0).kindU.S6.sons->data[i_549591_839829468]).kind == ((Tnodekind294020) 44)); if (!(LOC7)) goto LA8; LOC7 = (IL64(256) < (NI64)((*(*(*b0).kindU.S6.sons->data[i_549591_839829468]).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval - (*(*(*b0).kindU.S6.sons->data[i_549591_839829468]).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval)); LA8: ; if (!LOC7) goto LA9; result0 = NIM_TRUE; goto BeforeRet; } LA9: ; res_549612_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; return result0; } N_NIMCALL(NI, ifswitchsplitpoint_549616_839829468)(Tcproc531021* p0, Tnode294802* n0) { NI result0; result0 = (NI)0; { NI i_549631_839829468; NI HEX3Atmp_549655_839829468; NI LOC2; NI res_549658_839829468; i_549631_839829468 = (NI)0; HEX3Atmp_549655_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_295081_850551059(n0); HEX3Atmp_549655_839829468 = (NI)(LOC2 - ((NI) 1)); res_549658_839829468 = ((NI) 1); { while (1) { Tnode294802* branch0; Tnode294802* stmtblock0; if (!(res_549658_839829468 <= HEX3Atmp_549655_839829468)) goto LA4; i_549631_839829468 = res_549658_839829468; branch0 = HEX5BHEX5D_295238_850551059(n0, i_549631_839829468); stmtblock0 = lastson_297364_850551059(branch0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = stmtscontainpragma_530083_2036603609(stmtblock0, ((Tspecialword277003) 181)); if (!LOC7) goto LA8; result0 = i_549631_839829468; } goto LA5; LA8: ; { if (!!(((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 0))&7U)))!=0))) goto LA11; { NIM_BOOL LOC15; LOC15 = (NIM_BOOL)0; LOC15 = ((*branch0).kind == ((Tnodekind294020) 85)); if (!(LOC15)) goto LA16; LOC15 = branchhastoobigrange_549576_839829468(branch0); LA16: ; if (!LOC15) goto LA17; result0 = i_549631_839829468; } LA17: ; } goto LA5; LA11: ; LA5: ; res_549658_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genordinalcase_549725_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { NI splitpoint0; Tloc294816 a0; Ropeobj180006* lend0; splitpoint0 = ifswitchsplitpoint_549616_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); { if (!(((NI) 0) < splitpoint0)) goto LA3; lend0 = genifforcaseuntil_549021_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601), splitpoint0, (&a0)); } goto LA1; LA3: ; { lend0 = NIM_NIL; } LA1: ; { NI LOC8; TY180507 LOC11; NIM_BOOL hasdefault0; TY535289 LOC37; LOC8 = (NI)0; LOC8 = len_295081_850551059(n0); if (!((NI)(splitpoint0 + ((NI) 1)) < LOC8)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = rdcharloc_540227_839829468((&a0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_603), LOC11, 1); hasdefault0 = NIM_FALSE; { NI i_549758_839829468; NI HEX3Atmp_549817_839829468; NI HEX3Atmp_549818_839829468; NI LOC13; NI res_549821_839829468; i_549758_839829468 = (NI)0; HEX3Atmp_549817_839829468 = (NI)0; HEX3Atmp_549818_839829468 = (NI)0; HEX3Atmp_549817_839829468 = (NI)(splitpoint0 + ((NI) 1)); LOC13 = (NI)0; LOC13 = len_295081_850551059(n0); HEX3Atmp_549818_839829468 = (LOC13 - 1); res_549821_839829468 = HEX3Atmp_549817_839829468; { while (1) { Tnode294802* branch0; Tnode294802* LOC28; TY535289 LOC29; if (!(res_549821_839829468 <= HEX3Atmp_549818_839829468)) goto LA15; i_549758_839829468 = res_549821_839829468; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC18)) goto LA19; LOC18 = isemptytype_299441_850551059((*n0).typ); LA19: ; if (!LOC18) goto LA20; (*d0).k = ((Tlockind294808) 0); } LA20: ; branch0 = HEX5BHEX5D_295238_850551059(n0, i_549758_839829468); { if (!((*branch0).kind == ((Tnodekind294020) 85))) goto LA24; gencaserange_539028_839829468(p0, branch0); } goto LA22; LA24: ; { TY535289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_181), LOC27, 0); hasdefault0 = NIM_TRUE; } LA22: ; LOC28 = (Tnode294802*)0; LOC28 = lastson_297364_850551059(branch0); exprblock_546103_839829468(p0, LOC28, d0); memset((void*)LOC29, 0, sizeof(LOC29)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_182), LOC29, 0); res_549821_839829468 += ((NI) 1); } LA15: ; } } { NIM_BOOL LOC32; TY535289 LOC36; LOC32 = (NIM_BOOL)0; LOC32 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 3))&7U)))!=0); if (!(LOC32)) goto LA33; LOC32 = !(hasdefault0); LA33: ; if (!LOC32) goto LA34; memset((void*)LOC36, 0, sizeof(LOC36)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_604), LOC36, 0); } LA34: ; memset((void*)LOC37, 0, sizeof(LOC37)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC37, 0); } LA9: ; { if (!!((lend0 == NIM_NIL))) goto LA40; fixlabel_541230_839829468(p0, lend0); } LA40: ; } N_NIMCALL(void, gencase_549827_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { Ttype294840* LOC8; genlinedir_534823_839829468(p0, t0); { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_299441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind294808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_539032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (Ttype294840*)0; LOC8 = skiptypes_298099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106242013440)); switch ((*LOC8).kind) { case ((Ttypekind294244) 28): { genstringcase_549417_839829468(p0, t0, d0); } break; case ((Ttypekind294244) 36) ... ((Ttypekind294244) 39): { gencasegeneric_549087_839829468(p0, t0, d0, ((NimStringDesc*) &T839829468_600), ((NimStringDesc*) &T839829468_601)); } break; default: { { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = ((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC14)) goto LA15; LOC14 = (((*(*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 30))&31U)))!=0); LA15: ; if (!LOC14) goto LA16; gengotoforcase_547673_839829468(p0, t0); } goto LA12; LA16: ; { genordinalcase_549725_839829468(p0, t0, d0); } LA12: ; } break; } } static N_INLINE(Tnode294802*, pop_320246_1689653243)(Tnodeseq294796** s0) { Tnode294802* result0; NI L0; result0 = (Tnode294802*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (Tnodeseq294796*) setLengthSeq(&((*s0))->Sup, sizeof(Tnode294802*), ((NI) (L0))); return result0; } N_NIMCALL(void, blockleaveactions_547442_839829468)(Tcproc531021* p0, NI howmanytrys0, NI howmanyexcepts0) { Tnodeseq294796* stack0; NI alreadypoppedcnt0; stack0 = (Tnodeseq294796*)0; stack0 = (Tnodeseq294796*) newSeq((&NTI294796), ((NI) 0)); alreadypoppedcnt0 = (*p0).inexceptblock; { NI i_547471_839829468; NI res_547596_839829468; i_547471_839829468 = (NI)0; res_547596_839829468 = ((NI) 1); { while (1) { Tnode294802* trystmt0; Tnode294802* finallystmt0; if (!(res_547596_839829468 <= howmanytrys0)) goto LA3; i_547471_839829468 = res_547596_839829468; { NIM_BOOL LOC6; LOC6 = (NIM_BOOL)0; LOC6 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC6) goto LA7; LOC6 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA7: ; if (!!(LOC6)) goto LA8; { if (!(((NI) 0) < alreadypoppedcnt0)) goto LA12; alreadypoppedcnt0 -= ((NI) 1); } goto LA10; LA12: ; { TY535289 LOC15; memset((void*)LOC15, 0, sizeof(LOC15)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_605), LOC15, 0); } LA10: ; } LA8: ; trystmt0 = pop_320246_1689653243((&(*p0).nestedtrystmts)); stack0 = (Tnodeseq294796*) incrSeqV2(&(stack0)->Sup, sizeof(Tnode294802*)); asgnRefNoCycle((void**) (&stack0->data[stack0->Sup.len]), trystmt0); ++stack0->Sup.len; finallystmt0 = lastson_297364_850551059(trystmt0); { if (!((*finallystmt0).kind == ((Tnodekind294020) 107))) goto LA18; genstmts_541244_839829468(p0, (*finallystmt0).kindU.S6.sons->data[((NI) 0)]); } LA18: ; res_547596_839829468 += ((NI) 1); } LA3: ; } } { NI i_547546_839829468; NI HEX3Atmp_547601_839829468; NI res_547604_839829468; i_547546_839829468 = (NI)0; HEX3Atmp_547601_839829468 = (NI)0; HEX3Atmp_547601_839829468 = (NI)(howmanytrys0 - ((NI) 1)); res_547604_839829468 = HEX3Atmp_547601_839829468; { while (1) { if (!(((NI) 0) <= res_547604_839829468)) goto LA22; i_547546_839829468 = res_547604_839829468; (*p0).nestedtrystmts = (Tnodeseq294796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode294802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), stack0->data[i_547546_839829468]); ++(*p0).nestedtrystmts->Sup.len; res_547604_839829468 -= ((NI) 1); } LA22: ; } } { NIM_BOOL LOC25; LOC25 = (NIM_BOOL)0; LOC25 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC25) goto LA26; LOC25 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA26: ; if (!!(LOC25)) goto LA27; { NI i_547587_839829468; NI HEX3Atmp_547610_839829468; NI res_547613_839829468; i_547587_839829468 = (NI)0; HEX3Atmp_547610_839829468 = (NI)0; HEX3Atmp_547610_839829468 = (NI)(howmanyexcepts0 - ((NI) 1)); res_547613_839829468 = HEX3Atmp_547610_839829468; { while (1) { TY535289 LOC32; if (!(((NI) 0) <= res_547613_839829468)) goto LA31; i_547587_839829468 = res_547613_839829468; memset((void*)LOC32, 0, sizeof(LOC32)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_606), LOC32, 0); res_547613_839829468 -= ((NI) 1); } LA31: ; } } } LA27: ; } N_NIMCALL(void, genreturnstmt_547617_839829468)(Tcproc531021* p0, Tnode294802* t0) { TY535289 LOC14; { { if (!(((*t0).flags &(1U<<((NU)(((Tnodeflag294427) 14))&15U)))!=0)) goto LA3; goto BeforeRet; } LA3: ; (*p0).beforeretneeded = NIM_TRUE; genlinedir_534823_839829468(p0, t0); { if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)))) goto LA7; genstmts_541244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; blockleaveactions_547442_839829468(p0, ((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0), (*p0).inexceptblock); { Ropeobj180006* safepoint0; TY180507 LOC13; if (!(((NI) 0) < ((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0))) goto LA11; safepoint0 = (*p0).finallysafepoints->data[(NI)(((*p0).finallysafepoints ? (*p0).finallysafepoints->Sup.len : 0) - ((NI) 1))]; memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_607), LOC13, 1); } LA11: ; memset((void*)LOC14, 0, sizeof(LOC14)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_608), LOC14, 0); }BeforeRet: ; } N_NIMCALL(void, genbreakstmt_548444_839829468)(Tcproc531021* p0, Tnode294802* t0) { NI idx0; Ropeobj180006* label0; TY180507 LOC16; idx0 = (*p0).breakidx; { Tsym294834* sym0; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)))) goto LA3; sym0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; idx0 = (NI)((*sym0).position - ((NI) 1)); } goto LA1; LA3: ; { { while (1) { NIM_BOOL LOC8; LOC8 = (NIM_BOOL)0; LOC8 = (((NI) 0) <= idx0); if (!(LOC8)) goto LA9; LOC8 = !((*p0).blocks->data[idx0].isloop); LA9: ; if (!LOC8) goto LA7; idx0 -= ((NI) 1); } LA7: ; } { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = (idx0 < ((NI) 0)); if (LOC12) goto LA13; LOC12 = !((*p0).blocks->data[idx0].isloop); LA13: ; if (!LOC12) goto LA14; internalerror_198100_155036129((*t0).info, ((NimStringDesc*) &T839829468_609)); } LA14: ; } LA1: ; label0 = assignlabel_546020_839829468((&(*p0).blocks->data[idx0])); blockleaveactions_547442_839829468(p0, (NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) ((*p0).blocks->data[idx0].nestedtrystmts))), (NI)((*p0).inexceptblock - ((NI) ((*p0).blocks->data[idx0].nestedexceptstmts)))); genlinedir_534823_839829468(p0, t0); memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = label0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_556), LOC16, 1); } N_NIMCALL(NIM_BOOL, fielddiscriminantcheckneeded_551080_839829468)(Tcproc531021* p0, Tnode294802* asgn0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; { Tnode294802* le0; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 2))&31U)))!=0)) goto LA3; le0 = (*asgn0).kindU.S6.sons->data[((NI) 0)]; { Tsym294834* field0; if (!((*le0).kind == ((Tnodekind294020) 46))) goto LA7; field0 = (*(*(*le0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag294184) 18))&31U)))!=0); } goto LA5; LA7: ; { Tsym294834* field0; if (!((*le0).kind == ((Tnodekind294020) 45))) goto LA10; field0 = (*(*le0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym; result0 = (((*field0).flags &(1U<<((NU)(((Tsymflag294184) 18))&31U)))!=0); } goto LA5; LA10: ; LA5: ; } LA3: ; return result0; } N_NIMCALL(Ropeobj180006*, discriminatortabledecl_538094_839829468)(Tcgen531027* m0, Ttype294840* objtype0, Tsym294834* d0) { Ropeobj180006* result0; Ropeobj180006* LOC1; Ropeobj180006* tmp0; TY534811 LOC2; NI64 LOC3; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_130)); tmp0 = discriminatortablename_538057_839829468(m0, objtype0, d0); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = tmp0; LOC3 = (NI64)0; LOC3 = lengthord_322007_3876443242((*d0).typ); LOC2[1] = rope_180401_2381377266((NI64)(LOC3 + IL64(1))); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_203), LOC2, 2); return result0; } N_NIMCALL(void, gendiscriminantcheck_551144_839829468)(Tcproc531021* p0, Tloc294816* a0, Tloc294816* tmp0, Ttype294840* objtype0, Tsym294834* field0) { Ttype294840* t0; Ropeobj180006* LOC1; NI64 L0; TY537235 LOC8; t0 = skiptypes_298099_850551059(objtype0, IL64(211106240964864)); LOC1 = (Ropeobj180006*)0; LOC1 = gentypeinfo_537941_839829468((*p0).module, t0); L0 = lengthord_322007_3876443242((*field0).typ); { NIM_BOOL LOC4; TY180507 LOC7; LOC4 = (NIM_BOOL)0; LOC4 = containsorincl_270862_2627731572((&(*(*p0).module).declaredthings), (*field0).Sup.id); if (!!(LOC4)) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = discriminatortabledecl_538094_839829468((*p0).module, t0, field0); appcg_534640_839829468((*p0).module, ((Tcfilesection531005) 9), ((NimStringDesc*) &T839829468_610), LOC7, 1); } LA5: ; memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = rdloc_540188_839829468(a0); LOC8[1] = rdloc_540188_839829468(tmp0); LOC8[2] = discriminatortablename_538057_839829468((*p0).module, t0, field0); LOC8[3] = intliteral_541270_839829468((NI64)(L0 + IL64(1))); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_611), LOC8, 4); } N_NIMCALL(void, asgnfielddiscriminant_551209_839829468)(Tcproc531021* p0, Tnode294802* e0) { Tloc294816 a0; Tloc294816 tmp0; Tnode294802* dotexpr0; memset((void*)(&a0), 0, sizeof(a0)); memset((void*)(&tmp0), 0, sizeof(tmp0)); dotexpr0 = (*e0).kindU.S6.sons->data[((NI) 0)]; { if (!((*dotexpr0).kind == ((Tnodekind294020) 46))) goto LA3; dotexpr0 = (*dotexpr0).kindU.S6.sons->data[((NI) 0)]; } LA3: ; initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); gettemp_539032_839829468(p0, a0.t, (&tmp0), NIM_FALSE); expr_541248_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)], (&tmp0)); gendiscriminantcheck_551144_839829468(p0, (&a0), (&tmp0), (*(*dotexpr0).kindU.S6.sons->data[((NI) 0)]).typ, (*(*dotexpr0).kindU.S6.sons->data[((NI) 1)]).kindU.S4.sym); genassignment_541264_839829468(p0, (&a0), (&tmp0), 0); } N_NIMCALL(void, genasgn_551239_839829468)(Tcproc531021* p0, Tnode294802* e0, NIM_BOOL fastasgn0) { genlinedir_534823_839829468(p0, e0); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = ((*(*e0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 3)); if (!(LOC3)) goto LA4; LOC3 = (((*(*(*e0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym).flags &(1U<<((NU)(((Tsymflag294184) 30))&31U)))!=0); LA4: ; if (!LOC3) goto LA5; gengotovar_546258_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 1)]); } goto LA1; LA5: ; { NIM_BOOL LOC8; Tloc294816 a0; LOC8 = (NIM_BOOL)0; LOC8 = fielddiscriminantcheckneeded_551080_839829468(p0, e0); if (!!(LOC8)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); { Tnode294802* LOC13; Tnode294802* LOC16; LOC13 = (Tnode294802*)0; LOC13 = HEX5BHEX5D_295238_850551059(e0, ((NI) 0)); if (!((*LOC13).kind == ((Tnodekind294020) 47) || (*LOC13).kind == ((Tnodekind294020) 65))) goto LA14; LOC16 = (Tnode294802*)0; LOC16 = HEX5BHEX5D_295238_850551059(e0, ((NI) 0)); genderef_545921_839829468(p0, LOC16, (&a0), NIM_TRUE); } goto LA11; LA14: ; { initlocexpr_541283_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA11: ; { if (!fastasgn0) goto LA20; a0.flags |= ((NU16)1)<<((((Tlocflag294810) 2))%(sizeof(NU16)*8)); } LA20: ; loadinto_545928_839829468(p0, (*e0).kindU.S6.sons->data[((NI) 0)], (*e0).kindU.S6.sons->data[((NI) 1)], (&a0)); } goto LA1; LA9: ; { asgnfielddiscriminant_551209_839829468(p0, e0); } LA1: ; } N_NIMCALL(Ropeobj180006*, genasmoremitstmt_550529_839829468)(Tcproc531021* p0, Tnode294802* t0, NIM_BOOL isasmstmt0) { Ropeobj180006* result0; NimStringDesc* res0; result0 = (Ropeobj180006*)0; res0 = copyString(((NimStringDesc*) &T839829468_490)); { NI i_550547_839829468; NI HEX3Atmp_550644_839829468; NI LOC2; NI res_550647_839829468; i_550547_839829468 = (NI)0; HEX3Atmp_550644_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(t0); HEX3Atmp_550644_839829468 = (NI)(LOC2 - ((NI) 1)); res_550647_839829468 = ((NI) 0); { while (1) { if (!(res_550647_839829468 <= HEX3Atmp_550644_839829468)) goto LA4; i_550547_839829468 = res_550647_839829468; switch ((*(*t0).kindU.S6.sons->data[i_550547_839829468]).kind) { case ((Tnodekind294020) 20) ... ((Tnodekind294020) 22): { res0 = resizeString(res0, (*(*t0).kindU.S6.sons->data[i_550547_839829468]).kindU.S3.strval->Sup.len + 0); appendString(res0, (*(*t0).kindU.S6.sons->data[i_550547_839829468]).kindU.S3.strval); } break; case ((Tnodekind294020) 3): { Tsym294834* sym0; sym0 = (*(*t0).kindU.S6.sons->data[i_550547_839829468]).kindU.S4.sym; { Tloc294816 a0; Ropeobj180006* LOC11; NimStringDesc* LOC12; if (!((28672 &(1U<<((NU)((*sym0).kind)&31U)))!=0)) goto LA9; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[i_550547_839829468], (&a0)); LOC11 = (Ropeobj180006*)0; LOC11 = rdloc_540188_839829468((&a0)); LOC12 = (NimStringDesc*)0; LOC12 = HEX24_180856_2381377266(LOC11); res0 = resizeString(res0, LOC12->Sup.len + 0); appendString(res0, LOC12); } goto LA7; LA9: ; { Ropeobj180006* LOC16; NimStringDesc* LOC17; if (!((*sym0).kind == ((Tsymkind294435) 7))) goto LA14; LOC16 = (Ropeobj180006*)0; LOC16 = gettypedesc_537673_839829468((*p0).module, (*sym0).typ); LOC17 = (NimStringDesc*)0; LOC17 = HEX24_180856_2381377266(LOC16); res0 = resizeString(res0, LOC17->Sup.len + 0); appendString(res0, LOC17); } goto LA7; LA14: ; { Ropeobj180006* r0; NimStringDesc* LOC23; r0 = (*sym0).loc.r; { if (!(r0 == NIM_NIL)) goto LA21; r0 = manglename_535205_839829468(sym0); asgnRefNoCycle((void**) (&(*sym0).loc.r), r0); } LA21: ; LOC23 = (NimStringDesc*)0; LOC23 = HEX24_180856_2381377266(r0); res0 = resizeString(res0, LOC23->Sup.len + 0); appendString(res0, LOC23); } LA7: ; } break; default: { internalerror_198100_155036129((*(*t0).kindU.S6.sons->data[i_550547_839829468]).info, ((NimStringDesc*) &T839829468_612)); } break; } res_550647_839829468 += ((NI) 1); } LA4: ; } } { NIM_BOOL LOC27; LOC27 = (NIM_BOOL)0; LOC27 = isasmstmt0; if (!(LOC27)) goto LA28; LOC27 = ((Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field20 &(1U<<((NU)(((Tinfoccprop275004) 5))&7U)))!=0); LA28: ; if (!LOC27) goto LA29; { NimStringDesc* x_550604_839829468; NI first_550656_839829468; NI last_550658_839829468; x_550604_839829468 = (NimStringDesc*)0; first_550656_839829468 = ((NI) 0); last_550658_839829468 = ((NI) 0); { while (1) { NI j0; { while (1) { if (!!((((NU8)(res0->data[last_550658_839829468])) == ((NU8)(0)) || ((NU8)(res0->data[last_550658_839829468])) == ((NU8)(13)) || ((NU8)(res0->data[last_550658_839829468])) == ((NU8)(10))))) goto LA35; last_550658_839829468 += ((NI) 1); } LA35: ; } x_550604_839829468 = copyStrLast(res0, first_550656_839829468, (NI)(last_550658_839829468 - ((NI) 1))); j0 = ((NI) 0); { while (1) { if (!(((NU8)(x_550604_839829468->data[j0])) == ((NU8)(32)) || ((NU8)(x_550604_839829468->data[j0])) == ((NU8)(9)))) goto LA37; j0 += ((NI) 1); } LA37: ; } { if (!(((NU8)(x_550604_839829468->data[j0])) == ((NU8)(34)) || ((NU8)(x_550604_839829468->data[j0])) == ((NU8)(58)))) goto LA40; add_180487_2381377266(&result0, x_550604_839829468); add_180487_2381377266(&result0, tnl_178644_4151366050); } goto LA38; LA40: ; { if (!!(((NU8)(x_550604_839829468->data[j0]) == (NU8)(0)))) goto LA43; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_613)); add_180487_2381377266(&result0, x_550604_839829468); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_614)); } goto LA38; LA43: ; LA38: ; { if (!((NU8)(res0->data[last_550658_839829468]) == (NU8)(10))) goto LA47; last_550658_839829468 += ((NI) 1); } goto LA45; LA47: ; { if (!((NU8)(res0->data[last_550658_839829468]) == (NU8)(13))) goto LA50; last_550658_839829468 += ((NI) 1); { if (!((NU8)(res0->data[last_550658_839829468]) == (NU8)(10))) goto LA54; last_550658_839829468 += ((NI) 1); } LA54: ; } goto LA45; LA50: ; { goto LA32; } LA45: ; first_550656_839829468 = last_550658_839829468; } } LA32: ; } } goto LA25; LA29: ; { res0 = resizeString(res0, tnl_178644_4151366050->Sup.len + 0); appendString(res0, tnl_178644_4151366050); result0 = rope_180277_2381377266(res0); } LA25: ; return result0; } N_NIMCALL(void, genasmstmt_550659_839829468)(Tcproc531021* p0, Tnode294802* t0) { Ropeobj180006* s0; genlinedir_534823_839829468(p0, t0); s0 = genasmoremitstmt_550529_839829468(p0, t0, NIM_TRUE); { TY180507 LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = s0; addf_181205_2381377266(&(*(*p0).module).s[(((Tcfilesection531005) 7))- 0], Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field17, LOC5, 1); } goto LA1; LA3: ; { TY180507 LOC7; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = s0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field17, LOC7, 1); } LA1: ; } static N_INLINE(void, gensimpleblock_546095_839829468)(Tcproc531021* p0, Tnode294802* stmts0) { TY535289 LOC1; NI LOC2; memset((void*)LOC1, 0, sizeof(LOC1)); LOC2 = (NI)0; LOC2 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC1, 0); genstmts_541244_839829468(p0, stmts0); endblock_546060_839829468(p0); } N_NIMCALL(void, gentrycpp_549866_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { Ropeobj180006* exc0; TY535289 LOC16; NI LOC17; NI length0; TY180507 LOC18; Ropeobj180006* LOC19; NI i0; NIM_BOOL catchallpresent0; TY535289 LOC78; Tnode294802* LOC79; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_299441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind294808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_539032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; genlinedir_534823_839829468(p0, t0); exc0 = gettempname_535598_839829468((*p0).module); { Tsym294834* LOC10; Ropeobj180006* LOC13; LOC10 = (Tsym294834*)0; LOC10 = getcompilerproc_340748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC10 == NIM_NIL))) goto LA11; LOC13 = (Ropeobj180006*)0; LOC13 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA8; LA11: ; { Ropeobj180006* LOC15; LOC15 = (Ropeobj180006*)0; LOC15 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA8: ; (*p0).nestedtrystmts = (Tnodeseq294796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode294802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; memset((void*)LOC16, 0, sizeof(LOC16)); LOC17 = (NI)0; LOC17 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_617), LOC16, 0); expr_541248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); length0 = sonslen_297351_850551059(t0); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = exc0; LOC19 = (Ropeobj180006*)0; LOC19 = ropecg_534407_839829468((*p0).module, ((NimStringDesc*) &T839829468_618), LOC18, 1); endblock_546035_839829468(p0, LOC19); { TY535289 LOC24; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0)) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_619), LOC24, 0); } LA22: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); catchallpresent0 = NIM_FALSE; { while (1) { NIM_BOOL LOC27; NI blen0; LOC27 = (NIM_BOOL)0; LOC27 = (i0 < length0); if (!(LOC27)) goto LA28; LOC27 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind294020) 87)); LA28: ; if (!LOC27) goto LA26; { NIM_BOOL LOC31; LOC31 = (NIM_BOOL)0; LOC31 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC31)) goto LA32; LOC31 = isemptytype_299441_850551059((*t0).typ); LA32: ; if (!LOC31) goto LA33; (*d0).k = ((Tlockind294808) 0); } LA33: ; blen0 = sonslen_297351_850551059((*t0).kindU.S6.sons->data[i0]); { Ropeobj180006** LOC39; TY535289 LOC40; if (!(((NI) 1) < i0)) goto LA37; LOC39 = (Ropeobj180006**)0; LOC39 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); memset((void*)LOC40, 0, sizeof(LOC40)); addf_181205_2381377266(LOC39, ((NimStringDesc*) &T839829468_620), LOC40, 0); } LA37: ; { TY535289 LOC45; NI LOC46; TY535289 LOC47; if (!(blen0 == ((NI) 1))) goto LA43; catchallpresent0 = NIM_TRUE; memset((void*)LOC45, 0, sizeof(LOC45)); LOC46 = (NI)0; LOC46 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC45, 0); expr_541248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_606), LOC47, 0); endblock_546060_839829468(p0); } goto LA41; LA43: ; { Ropeobj180006* orexpr0; TY180507 LOC57; TY535289 LOC58; NI LOC59; TY535289 LOC60; orexpr0 = NIM_NIL; { NI j_549979_839829468; NI HEX3Atmp_550101_839829468; NI res_550104_839829468; j_549979_839829468 = (NI)0; HEX3Atmp_550101_839829468 = (NI)0; HEX3Atmp_550101_839829468 = (NI)(blen0 - ((NI) 2)); res_550104_839829468 = ((NI) 0); { while (1) { TY534811 LOC56; if (!(res_550104_839829468 <= HEX3Atmp_550101_839829468)) goto LA51; j_549979_839829468 = res_550104_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA54; add_180487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA54: ; memset((void*)LOC56, 0, sizeof(LOC56)); LOC56[0] = exc0; LOC56[1] = gentypeinfo_537941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_549979_839829468]).typ); appcg_534632_839829468((*p0).module, &orexpr0, ((NimStringDesc*) &T839829468_621), LOC56, 2); res_550104_839829468 += ((NI) 1); } LA51: ; } } memset((void*)LOC57, 0, sizeof(LOC57)); LOC57[0] = orexpr0; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_622), LOC57, 1); memset((void*)LOC58, 0, sizeof(LOC58)); LOC59 = (NI)0; LOC59 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC58, 0); expr_541248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC60, 0, sizeof(LOC60)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_606), LOC60, 0); endblock_546060_839829468(p0); } LA41: ; i0 += ((NI) 1); } LA26: ; } { TY535289 LOC70; NI LOC71; Tnode294802* finallyblock0; TY535289 LOC76; Ropeobj180006* LOC77; if (!!(catchallpresent0)) goto LA63; { TY535289 LOC69; if (!(((NI) 1) < i0)) goto LA67; memset((void*)LOC69, 0, sizeof(LOC69)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_620), LOC69, 0); } LA67: ; memset((void*)LOC70, 0, sizeof(LOC70)); LOC71 = (NI)0; LOC71 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC70, 0); finallyblock0 = lastson_297364_850551059(t0); { if (!((*finallyblock0).kind == ((Tnodekind294020) 107))) goto LA74; genstmts_541244_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA74: ; memset((void*)LOC76, 0, sizeof(LOC76)); LOC77 = (Ropeobj180006*)0; LOC77 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_623), LOC76, 0); line_534690_839829468(p0, ((Tcprocsection531011) 2), LOC77); endblock_546060_839829468(p0); } LA63: ; memset((void*)LOC78, 0, sizeof(LOC78)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC78, 0); (*p0).inexceptblock -= ((NI) 1); LOC79 = (Tnode294802*)0; LOC79 = pop_320246_1689653243((&(*p0).nestedtrystmts)); { NIM_BOOL LOC82; LOC82 = (NIM_BOOL)0; LOC82 = (i0 < length0); if (!(LOC82)) goto LA83; LOC82 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind294020) 107)); LA83: ; if (!LOC82) goto LA84; gensimpleblock_546095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); } LA84: ; } N_NIMCALL(void, line_534695_839829468)(Tcproc531021* p0, Tcprocsection531011 s0, NimStringDesc* r0) { Ropeobj180006** LOC1; Ropeobj180006* LOC2; Ropeobj180006* LOC3; LOC1 = (Ropeobj180006**)0; LOC1 = s_531179_3723162438(p0, s0); LOC2 = (Ropeobj180006*)0; LOC2 = rope_180277_2381377266(r0); LOC3 = (Ropeobj180006*)0; LOC3 = indentline_534656_839829468(p0, LOC2); add_180482_2381377266(LOC1, LOC3); } static N_INLINE(Ropeobj180006*, pop_180530_1689653243)(TY193350** s0) { Ropeobj180006* result0; NI L0; result0 = (Ropeobj180006*)0; L0 = (NI)(((*s0) ? (*s0)->Sup.len : 0) - ((NI) 1)); result0 = (*s0)->data[L0]; (*s0) = (TY193350*) setLengthSeq(&((*s0))->Sup, sizeof(Ropeobj180006*), ((NI) (L0))); return result0; } N_NIMCALL(void, gentry_550114_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { NIM_BOOL LOC8; Ropeobj180006* safepoint0; TY180507 LOC17; TY180507 LOC18; TY180507 LOC37; NI LOC38; NI length0; TY535289 LOC39; TY535289 LOC40; NI LOC41; TY535289 LOC42; NI i0; Tnode294802* LOC95; TY180507 LOC103; { NIM_BOOL LOC3; NIM_BOOL LOC4; LOC3 = (NIM_BOOL)0; LOC4 = (NIM_BOOL)0; LOC4 = isemptytype_299441_850551059((*t0).typ); LOC3 = !(LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*d0).k == ((Tlockind294808) 0)); LA5: ; if (!LOC3) goto LA6; gettemp_539032_839829468(p0, (*t0).typ, d0, NIM_FALSE); } LA6: ; LOC8 = (NIM_BOOL)0; LOC8 = includestr_148249_3771138726((&(*(*p0).module).headerfiles), ((NimStringDesc*) &T839829468_624)); genlinedir_534823_839829468(p0, t0); safepoint0 = gettempname_535598_839829468((*p0).module); { Tsym294834* LOC11; Ropeobj180006* LOC14; LOC11 = (Tsym294834*)0; LOC11 = getcompilerproc_340748_3937434831(((NimStringDesc*) &T839829468_615)); if (!!((LOC11 == NIM_NIL))) goto LA12; LOC14 = (Ropeobj180006*)0; LOC14 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_615)); } goto LA9; LA12: ; { Ropeobj180006* LOC16; LOC16 = (Ropeobj180006*)0; LOC16 = cgsym_534403_839829468((*p0).module, ((NimStringDesc*) &T839829468_616)); } LA9: ; memset((void*)LOC17, 0, sizeof(LOC17)); LOC17[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 0), ((NimStringDesc*) &T839829468_625), LOC17, 1); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_626), LOC18, 1); { NIM_BOOL LOC21; TY180507 LOC24; LOC21 = (NIM_BOOL)0; LOC21 = isdefined_202011_1967573533(((NimStringDesc*) &T839829468_627)); if (!LOC21) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC24[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_628), LOC24, 1); } goto LA19; LA22: ; { NIM_BOOL LOC26; TY180507 LOC29; LOC26 = (NIM_BOOL)0; LOC26 = isdefined_202011_1967573533(((NimStringDesc*) &T839829468_629)); if (!LOC26) goto LA27; memset((void*)LOC29, 0, sizeof(LOC29)); LOC29[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_630), LOC29, 1); } goto LA19; LA27: ; { NIM_BOOL LOC31; TY180507 LOC34; LOC31 = (NIM_BOOL)0; LOC31 = isdefined_202011_1967573533(((NimStringDesc*) &T839829468_631)); if (!LOC31) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_632), LOC34, 1); } goto LA19; LA32: ; { TY180507 LOC36; memset((void*)LOC36, 0, sizeof(LOC36)); LOC36[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_628), LOC36, 1); } LA19: ; memset((void*)LOC37, 0, sizeof(LOC37)); LOC37[0] = safepoint0; LOC38 = (NI)0; LOC38 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_633), LOC37, 1); length0 = sonslen_297351_850551059(t0); (*p0).nestedtrystmts = (Tnodeseq294796*) incrSeqV2(&((*p0).nestedtrystmts)->Sup, sizeof(Tnode294802*)); asgnRefNoCycle((void**) (&(*p0).nestedtrystmts->data[(*p0).nestedtrystmts->Sup.len]), t0); ++(*p0).nestedtrystmts->Sup.len; expr_541248_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC39, 0, sizeof(LOC39)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_605), LOC39, 0); endblock_546060_839829468(p0); memset((void*)LOC40, 0, sizeof(LOC40)); LOC41 = (NI)0; LOC41 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_634), LOC40, 0); memset((void*)LOC42, 0, sizeof(LOC42)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_605), LOC42, 0); { TY535289 LOC47; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0)) goto LA45; memset((void*)LOC47, 0, sizeof(LOC47)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_619), LOC47, 0); } LA45: ; (*p0).inexceptblock += ((NI) 1); i0 = ((NI) 1); { while (1) { NIM_BOOL LOC50; NI blen0; LOC50 = (NIM_BOOL)0; LOC50 = (i0 < length0); if (!(LOC50)) goto LA51; LOC50 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind294020) 87)); LA51: ; if (!LOC50) goto LA49; { NIM_BOOL LOC54; LOC54 = (NIM_BOOL)0; LOC54 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC54)) goto LA55; LOC54 = isemptytype_299441_850551059((*t0).typ); LA55: ; if (!LOC54) goto LA56; (*d0).k = ((Tlockind294808) 0); } LA56: ; blen0 = sonslen_297351_850551059((*t0).kindU.S6.sons->data[i0]); { TY535289 LOC67; NI LOC68; TY180507 LOC69; TY535289 LOC70; if (!(blen0 == ((NI) 1))) goto LA60; { TY535289 LOC66; if (!(((NI) 1) < i0)) goto LA64; memset((void*)LOC66, 0, sizeof(LOC66)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_635), LOC66, 0); } LA64: ; memset((void*)LOC67, 0, sizeof(LOC67)); LOC68 = (NI)0; LOC68 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC67, 0); memset((void*)LOC69, 0, sizeof(LOC69)); LOC69[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_636), LOC69, 1); expr_541248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)], d0); memset((void*)LOC70, 0, sizeof(LOC70)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_606), LOC70, 0); endblock_546060_839829468(p0); } goto LA58; LA60: ; { Ropeobj180006* orexpr0; TY180507 LOC91; NI LOC92; TY180507 LOC93; TY535289 LOC94; orexpr0 = NIM_NIL; { NI j_550247_839829468; NI HEX3Atmp_550521_839829468; NI res_550524_839829468; j_550247_839829468 = (NI)0; HEX3Atmp_550521_839829468 = (NI)0; HEX3Atmp_550521_839829468 = (NI)(blen0 - ((NI) 2)); res_550524_839829468 = ((NI) 0); { while (1) { NimStringDesc* isobjformat0; TY180507 LOC86; if (!(res_550524_839829468 <= HEX3Atmp_550521_839829468)) goto LA74; j_550247_839829468 = res_550524_839829468; { if (!!((orexpr0 == NIM_NIL))) goto LA77; add_180487_2381377266(&orexpr0, ((NimStringDesc*) &T839829468_229)); } LA77: ; { NIM_BOOL LOC81; LOC81 = (NIM_BOOL)0; LOC81 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC81) goto LA82; LOC81 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA82: ; if (!!(LOC81)) goto LA83; isobjformat0 = copyString(((NimStringDesc*) &T839829468_637)); } goto LA79; LA83: ; { isobjformat0 = copyString(((NimStringDesc*) &T839829468_638)); } LA79: ; memset((void*)LOC86, 0, sizeof(LOC86)); LOC86[0] = gentypeinfo_537941_839829468((*p0).module, (*(*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[j_550247_839829468]).typ); appcg_534632_839829468((*p0).module, &orexpr0, isobjformat0, LOC86, 1); res_550524_839829468 += ((NI) 1); } LA74: ; } } { if (!(((NI) 1) < i0)) goto LA89; line_534695_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_620)); } LA89: ; memset((void*)LOC91, 0, sizeof(LOC91)); LOC91[0] = orexpr0; LOC92 = (NI)0; LOC92 = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_639), LOC91, 1); memset((void*)LOC93, 0, sizeof(LOC93)); LOC93[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_636), LOC93, 1); expr_541248_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[(NI)(blen0 - ((NI) 1))], d0); memset((void*)LOC94, 0, sizeof(LOC94)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_606), LOC94, 0); endblock_546060_839829468(p0); } LA58: ; i0 += ((NI) 1); } LA49: ; } (*p0).inexceptblock -= ((NI) 1); LOC95 = (Tnode294802*)0; LOC95 = pop_320246_1689653243((&(*p0).nestedtrystmts)); endblock_546060_839829468(p0); { NIM_BOOL LOC98; Ropeobj180006* LOC102; LOC98 = (NIM_BOOL)0; LOC98 = (i0 < length0); if (!(LOC98)) goto LA99; LOC98 = ((*(*t0).kindU.S6.sons->data[i0]).kind == ((Tnodekind294020) 107)); LA99: ; if (!LOC98) goto LA100; (*p0).finallysafepoints = (TY193350*) incrSeqV2(&((*p0).finallysafepoints)->Sup, sizeof(Ropeobj180006*)); asgnRefNoCycle((void**) (&(*p0).finallysafepoints->data[(*p0).finallysafepoints->Sup.len]), safepoint0); ++(*p0).finallysafepoints->Sup.len; gensimpleblock_546095_839829468(p0, (*(*t0).kindU.S6.sons->data[i0]).kindU.S6.sons->data[((NI) 0)]); LOC102 = (Ropeobj180006*)0; LOC102 = pop_180530_1689653243((&(*p0).finallysafepoints)); } LA100: ; memset((void*)LOC103, 0, sizeof(LOC103)); LOC103[0] = safepoint0; linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_640), LOC103, 1); } N_NIMCALL(NimStringDesc*, getraisefrmt_548824_839829468)(Tcproc531021* p0) { NimStringDesc* result0; result0 = (NimStringDesc*)0; result0 = copyString(((NimStringDesc*) &T839829468_641)); return result0; } N_NIMCALL(void, genraisestmt_548828_839829468)(Tcproc531021* p0, Tnode294802* t0) { { Tnode294802* finallyblock0; if (!(((NI) 0) < (*p0).inexceptblock)) goto LA3; finallyblock0 = lastson_297364_850551059((*p0).nestedtrystmts->data[(NI)(((*p0).nestedtrystmts ? (*p0).nestedtrystmts->Sup.len : 0) - ((NI) 1))]); { if (!((*finallyblock0).kind == ((Tnodekind294020) 107))) goto LA7; gensimpleblock_546095_839829468(p0, (*finallyblock0).kindU.S6.sons->data[((NI) 0)]); } LA7: ; } LA3: ; { Tloc294816 a0; Ropeobj180006* e0; Ttype294840* typ0; NimStringDesc* LOC13; TY534811 LOC14; if (!!(((*(*t0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)))) goto LA11; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 0)], (&a0)); e0 = rdloc_540188_839829468((&a0)); typ0 = skiptypes_298099_850551059((*(*t0).kindU.S6.sons->data[((NI) 0)]).typ, IL64(211106247256320)); genlinedir_534823_839829468(p0, t0); LOC13 = (NimStringDesc*)0; LOC13 = getraisefrmt_548824_839829468(p0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = e0; LOC14[1] = makecstring_193638_155036129((*(*(*typ0).sym).name).s); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), LOC13, LOC14, 2); } goto LA9; LA11: ; { genlinedir_534823_839829468(p0, t0); { NIM_BOOL LOC18; NIM_BOOL LOC19; TY535289 LOC24; Ropeobj180006* LOC25; LOC18 = (NIM_BOOL)0; LOC19 = (NIM_BOOL)0; LOC19 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC19) goto LA20; LOC19 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA20: ; LOC18 = LOC19; if (!(LOC18)) goto LA21; LOC18 = !(((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 31))&63U)))!=0)); LA21: ; if (!LOC18) goto LA22; memset((void*)LOC24, 0, sizeof(LOC24)); LOC25 = (Ropeobj180006*)0; LOC25 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_623), LOC24, 0); line_534690_839829468(p0, ((Tcprocsection531011) 2), LOC25); } goto LA16; LA22: ; { TY535289 LOC27; memset((void*)LOC27, 0, sizeof(LOC27)); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_642), LOC27, 0); } LA16: ; } LA9: ; } N_NIMCALL(void, gentypesection_540184_839829468)(Tcgen531027* m0, Tnode294802* n0) { } N_NIMCALL(Tcfilesection531005, determinesection_550819_839829468)(Tnode294802* n0) { Tcfilesection531005 result0; result0 = (Tcfilesection531005)0; result0 = ((Tcfilesection531005) 7); { NIM_BOOL LOC3; NI LOC4; NimStringDesc* sec0; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_295081_850551059(n0); LOC3 = (((NI) 1) <= LOC4); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind >= ((Tnodekind294020) 20) && (*(*n0).kindU.S6.sons->data[((NI) 0)]).kind <= ((Tnodekind294020) 22)); LA5: ; if (!LOC3) goto LA6; sec0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S3.strval; { NIM_BOOL LOC10; LOC10 = (NIM_BOOL)0; LOC10 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_643)); if (!LOC10) goto LA11; result0 = ((Tcfilesection531005) 3); } goto LA8; LA11: ; { NIM_BOOL LOC14; LOC14 = (NIM_BOOL)0; LOC14 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_644)); if (!LOC14) goto LA15; result0 = ((Tcfilesection531005) 9); } goto LA8; LA15: ; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = nsuStartsWith(sec0, ((NimStringDesc*) &T839829468_645)); if (!LOC18) goto LA19; result0 = ((Tcfilesection531005) 1); } goto LA8; LA19: ; LA8: ; } LA6: ; return result0; } N_NIMCALL(void, genemit_550839_839829468)(Tcproc531021* p0, Tnode294802* t0) { Ropeobj180006* s0; s0 = genasmoremitstmt_550529_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 1)], NIM_FALSE); { Tcfilesection531005 section0; Tnode294802* LOC5; if (!((*p0).prc == NIM_NIL)) goto LA3; LOC5 = (Tnode294802*)0; LOC5 = HEX5BHEX5D_295238_850551059(t0, ((NI) 1)); section0 = determinesection_550819_839829468(LOC5); genclinedir_534813_839829468(&(*(*p0).module).s[(section0)- 0], (*t0).info); add_180482_2381377266(&(*(*p0).module).s[(section0)- 0], s0); } goto LA1; LA3: ; { genlinedir_534823_839829468(p0, t0); line_534690_839829468(p0, ((Tcprocsection531011) 2), s0); } LA1: ; } N_NIMCALL(void, genbreakpoint_550862_839829468)(Tcproc531021* p0, Tnode294802* t0) { NimStringDesc* name0; name0 = (NimStringDesc*)0; { TY537238 LOC12; NI LOC13; NimStringDesc* LOC14; if (!(((*p0).options &(1U<<((NU)(((Toption171009) 17))&31U)))!=0)) goto LA3; { if (!((*t0).kind == ((Tnodekind294020) 34))) goto LA7; name0 = nsuNormalize((*(*t0).kindU.S6.sons->data[((NI) 1)]).kindU.S3.strval); } goto LA5; LA7: ; { NimStringDesc* LOC10; NimStringDesc* LOC11; breakpointid_550860_839829468 += ((NI) 1); LOC10 = (NimStringDesc*)0; LOC11 = (NimStringDesc*)0; LOC11 = nimIntToStr(breakpointid_550860_839829468); LOC10 = rawNewString(LOC11->Sup.len + 2); appendString(LOC10, ((NimStringDesc*) &T839829468_646)); appendString(LOC10, LOC11); name0 = LOC10; } LA5: ; genlinedir_534823_839829468(p0, t0); memset((void*)LOC12, 0, sizeof(LOC12)); LOC13 = (NI)0; LOC13 = tolinenumber_194415_155036129((*t0).info); LOC12[0] = rope_180401_2381377266(((NI64) (LOC13))); LOC14 = (NimStringDesc*)0; LOC14 = tofilename_194257_155036129((*t0).info.fileindex); LOC12[1] = makecstring_193638_155036129(LOC14); LOC12[2] = makecstring_193638_155036129(name0); appcg_534632_839829468((*p0).module, &gbreakpoints_550861_839829468, ((NimStringDesc*) &T839829468_647), LOC12, 3); } LA3: ; } N_NIMCALL(void, genwatchpoint_551016_839829468)(Tcproc531021* p0, Tnode294802* n0) { Tloc294816 a0; Ttype294840* typ0; TY537238 LOC5; NimStringDesc* LOC6; { { if (!!((((*p0).options &(1U<<((NU)(((Toption171009) 17))&31U)))!=0))) goto LA3; goto BeforeRet; } LA3: ; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 1)], (&a0)); typ0 = skiptypes_298099_850551059((*(*n0).kindU.S6.sons->data[((NI) 1)]).typ, IL64(211106242013440)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = addrloc_540204_839829468((&a0)); LOC6 = (NimStringDesc*)0; LOC6 = rendertree_313044_382274130((*n0).kindU.S6.sons->data[((NI) 1)], 0); LOC5[1] = makecstring_193638_155036129(LOC6); LOC5[2] = gentypeinfo_537941_839829468((*p0).module, typ0); linecg_534707_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_648), LOC5, 3); }BeforeRet: ; } N_NIMCALL(void, genpragma_551039_839829468)(Tcproc531021* p_551041_839829468, Tnode294802* n0) { { NI i_551054_839829468; NI HEX3Atmp_551073_839829468; NI LOC2; NI res_551076_839829468; i_551054_839829468 = (NI)0; HEX3Atmp_551073_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(n0); HEX3Atmp_551073_839829468 = (NI)(LOC2 - ((NI) 1)); res_551076_839829468 = ((NI) 0); { while (1) { Tnode294802* it0; Tspecialword277003 LOC5; if (!(res_551076_839829468 <= HEX3Atmp_551073_839829468)) goto LA4; i_551054_839829468 = res_551076_839829468; it0 = (*n0).kindU.S6.sons->data[i_551054_839829468]; LOC5 = (Tspecialword277003)0; LOC5 = whichpragma_320911_2616423590(it0); switch (LOC5) { case ((Tspecialword277003) 191): { genemit_550839_839829468(p_551041_839829468, it0); } break; case ((Tspecialword277003) 131): { genbreakpoint_550862_839829468(p_551041_839829468, it0); } break; case ((Tspecialword277003) 176): { genwatchpoint_551016_839829468(p_551041_839829468, it0); } break; case ((Tspecialword277003) 183): { Tcproc531021* p0; Ropeobj180006** LOC10; p0 = newproc_531206_3723162438(NIM_NIL, (*p_551041_839829468).module); (*p0).options = ((*p0).options & ~ 98304); genstmts_541244_839829468(p0, (*it0).kindU.S6.sons->data[((NI) 1)]); LOC10 = (Ropeobj180006**)0; LOC10 = s_531179_3723162438(p0, ((Tcprocsection531011) 2)); asgnRefNoCycle((void**) (&(*(*p0).module).injectstmt), (*LOC10)); } break; default: { } break; } res_551076_839829468 += ((NI) 1); } LA4: ; } } } N_NIMCALL(void, genparforstmt_548208_839829468)(Tcproc531021* p0, Tnode294802* t0) { NI oldbreakidx_548411_839829468; Tsym294834* forloopvar0; Tloc294816 rangea0; Tloc294816 rangeb0; Tnode294802* call0; TY537235 LOC1; NimStringDesc* LOC2; TY535289 LOC3; (*p0).withinloop += ((NI) 1); genlinedir_534823_839829468(p0, t0); oldbreakidx_548411_839829468 = (*p0).breakidx; forloopvar0 = (*(*t0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; memset((void*)(&rangea0), 0, sizeof(rangea0)); memset((void*)(&rangeb0), 0, sizeof(rangeb0)); assignlocalvar_540614_839829468(p0, forloopvar0); call0 = (*t0).kindU.S6.sons->data[((NI) 1)]; initlocexpr_541283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 1)], (&rangea0)); initlocexpr_541283_839829468(p0, (*call0).kindU.S6.sons->data[((NI) 2)], (&rangeb0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&(*forloopvar0).loc)); LOC1[1] = rdloc_540188_839829468((&rangea0)); LOC1[2] = rdloc_540188_839829468((&rangeb0)); LOC2 = (NimStringDesc*)0; LOC2 = getstr_299230_850551059((*call0).kindU.S6.sons->data[((NI) 3)]); LOC1[3] = rope_180277_2381377266(LOC2); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_649), LOC1, 4); memset((void*)LOC3, 0, sizeof(LOC3)); (*p0).breakidx = startblock_545978_839829468(p0, ((NimStringDesc*) &T839829468_273), LOC3, 0); (*p0).blocks->data[(*p0).breakidx].isloop = NIM_TRUE; genstmts_541244_839829468(p0, (*t0).kindU.S6.sons->data[((NI) 2)]); endblock_546060_839829468(p0); (*p0).breakidx = oldbreakidx_548411_839829468; (*p0).withinloop -= ((NI) 1); } N_NIMCALL(void, genstate_546117_839829468)(Tcproc531021* p0, Tnode294802* n0) { NI64 idx0; TY180507 LOC9; { NIM_BOOL LOC3; NI LOC4; NimStringDesc* LOC8; LOC3 = (NIM_BOOL)0; LOC4 = (NI)0; LOC4 = len_295081_850551059(n0); LOC3 = (LOC4 == ((NI) 1)); if (!(LOC3)) goto LA5; LOC3 = ((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 6)); LA5: ; if (!!(LOC3)) goto LA6; LOC8 = (NimStringDesc*)0; LOC8 = HEX24_198185_1689653243(T839829468_650); internalerror_198113_155036129(LOC8); } LA6: ; idx0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval; memset((void*)LOC9, 0, sizeof(LOC9)); LOC9[0] = rope_180401_2381377266(idx0); linefmt_534714_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_652), LOC9, 1); } N_NIMCALL(void, gengotostate_546144_839829468)(Tcproc531021* p0, Tnode294802* n0) { Tloc294816 a0; TY180507 LOC1; TY535289 LOC2; TY535289 LOC7; memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = rdloc_540188_839829468((&a0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_603), LOC1, 1); (*p0).beforeretneeded = NIM_TRUE; memset((void*)LOC2, 0, sizeof(LOC2)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_653), LOC2, 0); { NI64 i_546214_839829468; NI64 HEX3Atmp_546223_839829468; NI64 res_546226_839829468; i_546214_839829468 = (NI64)0; HEX3Atmp_546223_839829468 = (NI64)0; HEX3Atmp_546223_839829468 = lastord_322004_3876443242((*(*n0).kindU.S6.sons->data[((NI) 0)]).typ); res_546226_839829468 = IL64(0); { while (1) { TY180507 LOC6; if (!(res_546226_839829468 <= HEX3Atmp_546223_839829468)) goto LA5; i_546214_839829468 = res_546226_839829468; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = rope_180401_2381377266(i_546214_839829468); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_654), LOC6, 1); res_546226_839829468 += ((NI) 1); } LA5: ; } } memset((void*)LOC7, 0, sizeof(LOC7)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_160), LOC7, 0); } N_NIMCALL(void, genbreakstate_546229_839829468)(Tcproc531021* p0, Tnode294802* n0) { Tloc294816 a0; memset((void*)(&a0), 0, sizeof(a0)); { TY180507 LOC5; if (!((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 155))) goto LA3; initlocexpr_541283_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S6.sons->data[((NI) 1)], (&a0)); memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rdloc_540188_839829468((&a0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_655), LOC5, 1); } goto LA1; LA3: ; { TY180507 LOC7; initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rdloc_540188_839829468((&a0)); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_656), LOC7, 1); } LA1: ; } N_NIMCALL(void, expr_541248_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { switch ((*n0).kind) { case ((Tnodekind294020) 3): { Tsym294834* sym0; sym0 = (*n0).kindU.S4.sym; switch ((*sym0).kind) { case ((Tsymkind294435) 13): { { if (!!(((33554448 & (*sym0).flags) == 0))) goto LA5; fillprocloc_541201_839829468(sym0); genprocprototype_541254_839829468((*p0).module, sym0); } goto LA3; LA5: ; { genproc_534951_839829468((*p0).module, sym0); } LA3: ; putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind294435) 12): case ((Tsymkind294435) 15): case ((Tsymkind294435) 14): { { NimStringDesc* LOC13; if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 23))&31U)))!=0)) goto LA11; LOC13 = (NimStringDesc*)0; LOC13 = rawNewString((*(*sym0).name).s->Sup.len + 48); appendString(LOC13, ((NimStringDesc*) &T839829468_270)); appendString(LOC13, (*(*sym0).name).s); localerror_198085_155036129((*n0).info, LOC13); } LA11: ; genproc_534951_839829468((*p0).module, sym0); { NIM_BOOL LOC16; NimStringDesc* LOC20; LOC16 = (NIM_BOOL)0; LOC16 = ((*sym0).loc.r == NIM_NIL); if (LOC16) goto LA17; LOC16 = ((*sym0).loc.t == NIM_NIL); LA17: ; if (!LOC16) goto LA18; LOC20 = (NimStringDesc*)0; LOC20 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC20, ((NimStringDesc*) &T839829468_271)); appendString(LOC20, (*(*sym0).name).s); internalerror_198100_155036129((*n0).info, LOC20); } LA18: ; putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind294435) 10): { { NIM_BOOL LOC24; Ropeobj180006* LOC27; LOC24 = (NIM_BOOL)0; LOC24 = issimpleconst_534311_839829468((*sym0).typ); if (!LOC24) goto LA25; LOC27 = (Ropeobj180006*)0; LOC27 = genliteral_551476_839829468(p0, (*sym0).ast, (*sym0).typ); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC27, ((Tstorageloc294812) 1)); } goto LA22; LA25: ; { gencomplexconst_560249_839829468(p0, sym0, d0); } LA22: ; } break; case ((Tsymkind294435) 19): { Ropeobj180006* LOC30; LOC30 = (Ropeobj180006*)0; LOC30 = rope_180401_2381377266(((NI64) ((*sym0).position))); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC30, ((Tstorageloc294812) 0)); } break; case ((Tsymkind294435) 8): case ((Tsymkind294435) 20): case ((Tsymkind294435) 11): case ((Tsymkind294435) 9): { { if (!!(((4194312 & (*sym0).flags) == 0))) goto LA34; genvarprototype_541236_839829468((*p0).module, sym0); } LA34: ; { NIM_BOOL LOC38; NimStringDesc* LOC42; NimStringDesc* LOC43; LOC38 = (NIM_BOOL)0; LOC38 = ((*sym0).loc.r == NIM_NIL); if (LOC38) goto LA39; LOC38 = ((*sym0).loc.t == NIM_NIL); LA39: ; if (!LOC38) goto LA40; LOC42 = (NimStringDesc*)0; LOC43 = (NimStringDesc*)0; LOC43 = nimIntToStr((*sym0).Sup.id); LOC42 = rawNewString((*(*sym0).name).s->Sup.len + LOC43->Sup.len + 20); appendString(LOC42, ((NimStringDesc*) &T839829468_285)); appendString(LOC42, (*(*sym0).name).s); appendString(LOC42, ((NimStringDesc*) &T839829468_12)); appendString(LOC42, LOC43); internalerror_198100_155036129((*n0).info, LOC42); } LA40: ; { if (!(((*sym0).flags &(1U<<((NU)(((Tsymflag294184) 22))&31U)))!=0)) goto LA46; accessthreadlocalvar_534945_839829468(p0, sym0); { NIM_BOOL LOC50; Ropeobj180006* LOC53; LOC50 = (NIM_BOOL)0; LOC50 = emulatedthreadvars_534949_839829468(); if (!LOC50) goto LA51; LOC53 = (Ropeobj180006*)0; LOC53 = HEX26_180452_2381377266(((NimStringDesc*) &T839829468_288), (*sym0).loc.r); putintodest_552468_839829468(p0, d0, (*sym0).loc.t, LOC53, ((Tstorageloc294812) 0)); } goto LA48; LA51: ; { putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } LA48: ; } goto LA44; LA46: ; { putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } LA44: ; } break; case ((Tsymkind294435) 5): { { NIM_BOOL LOC59; NimStringDesc* LOC63; NimStringDesc* LOC64; LOC59 = (NIM_BOOL)0; LOC59 = ((*sym0).loc.r == NIM_NIL); if (LOC59) goto LA60; LOC59 = ((*sym0).loc.t == NIM_NIL); LA60: ; if (!LOC59) goto LA61; LOC63 = (NimStringDesc*)0; LOC64 = (NimStringDesc*)0; LOC64 = nimIntToStr((*sym0).Sup.id); LOC63 = rawNewString((*(*sym0).name).s->Sup.len + LOC64->Sup.len + 21); appendString(LOC63, ((NimStringDesc*) &T839829468_289)); appendString(LOC63, (*(*sym0).name).s); appendString(LOC63, ((NimStringDesc*) &T839829468_12)); appendString(LOC63, LOC64); internalerror_198100_155036129((*n0).info, LOC63); } LA61: ; putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tsymkind294435) 3): { { NIM_BOOL LOC68; NimStringDesc* LOC72; NimStringDesc* LOC73; LOC68 = (NIM_BOOL)0; LOC68 = ((*sym0).loc.r == NIM_NIL); if (LOC68) goto LA69; LOC68 = ((*sym0).loc.t == NIM_NIL); LA69: ; if (!LOC68) goto LA70; LOC72 = (NimStringDesc*)0; LOC73 = (NimStringDesc*)0; LOC73 = nimIntToStr((*sym0).Sup.id); LOC72 = rawNewString((*(*sym0).name).s->Sup.len + LOC73->Sup.len + 22); appendString(LOC72, ((NimStringDesc*) &T839829468_290)); appendString(LOC72, (*(*sym0).name).s); appendString(LOC72, ((NimStringDesc*) &T839829468_12)); appendString(LOC72, LOC73); internalerror_198100_155036129((*n0).info, LOC72); } LA70: ; putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } break; default: { NimStringDesc* LOC75; LOC75 = (NimStringDesc*)0; LOC75 = rawNewString(reprEnum((NI)(*sym0).kind, (&NTI294435))->Sup.len + 22); appendString(LOC75, ((NimStringDesc*) &T839829468_291)); appendString(LOC75, reprEnum((NI)(*sym0).kind, (&NTI294435))); appendString(LOC75, ((NimStringDesc*) &T839829468_292)); internalerror_198100_155036129((*n0).info, LOC75); } break; } } break; case ((Tnodekind294020) 23): { { NIM_BOOL LOC79; Ropeobj180006* LOC82; LOC79 = (NIM_BOOL)0; LOC79 = isemptytype_299441_850551059((*n0).typ); if (!!(LOC79)) goto LA80; LOC82 = (Ropeobj180006*)0; LOC82 = genliteral_541273_839829468(p0, n0); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC82, ((Tstorageloc294812) 0)); } LA80: ; } break; case ((Tnodekind294020) 20) ... ((Tnodekind294020) 22): { Ropeobj180006* LOC84; LOC84 = (Ropeobj180006*)0; LOC84 = genliteral_541273_839829468(p0, n0); putdataintodest_552436_839829468(p0, d0, (*n0).typ, LOC84); } break; case ((Tnodekind294020) 6) ... ((Tnodekind294020) 15): case ((Tnodekind294020) 16) ... ((Tnodekind294020) 19): case ((Tnodekind294020) 5): { Ropeobj180006* LOC86; LOC86 = (Ropeobj180006*)0; LOC86 = genliteral_541273_839829468(p0, n0); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC86, ((Tstorageloc294812) 0)); } break; case ((Tnodekind294020) 27): case ((Tnodekind294020) 32): case ((Tnodekind294020) 29): case ((Tnodekind294020) 30): case ((Tnodekind294020) 31): case ((Tnodekind294020) 26): case ((Tnodekind294020) 28): { Tnode294802* op0; genlinedir_534823_839829468(p0, n0); op0 = (*n0).kindU.S6.sons->data[((NI) 0)]; { Tloc294816 a0; if (!(*n0).typ == 0) goto LA90; memset((void*)(&a0), 0, sizeof(a0)); { NIM_BOOL LOC94; LOC94 = (NIM_BOOL)0; LOC94 = ((*op0).kind == ((Tnodekind294020) 3)); if (!(LOC94)) goto LA95; LOC94 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic294524) 0))); LA95: ; if (!LOC94) goto LA96; genmagicexpr_559033_839829468(p0, n0, (&a0), (*(*op0).kindU.S4.sym).magic); } goto LA92; LA96: ; { gencall_545632_839829468(p0, n0, (&a0)); } LA92: ; } goto LA88; LA90: ; { { NIM_BOOL LOC102; LOC102 = (NIM_BOOL)0; LOC102 = ((*op0).kind == ((Tnodekind294020) 3)); if (!(LOC102)) goto LA103; LOC102 = !(((*(*op0).kindU.S4.sym).magic == ((Tmagic294524) 0))); LA103: ; if (!LOC102) goto LA104; genmagicexpr_559033_839829468(p0, n0, d0, (*(*op0).kindU.S4.sym).magic); } goto LA100; LA104: ; { gencall_545632_839829468(p0, n0, d0); } LA100: ; } LA88: ; } break; case ((Tnodekind294020) 39): { { NIM_BOOL LOC110; NI LOC112; Ropeobj180006* LOC115; LOC110 = (NIM_BOOL)0; LOC110 = isdeepconstexpr_320566_2616423590(n0); if (!(LOC110)) goto LA111; LOC112 = (NI)0; LOC112 = len_295081_850551059(n0); LOC110 = !((LOC112 == ((NI) 0))); LA111: ; if (!LOC110) goto LA113; LOC115 = (Ropeobj180006*)0; LOC115 = gensetnode_551664_839829468(p0, n0); putintodest_552468_839829468(p0, d0, (*n0).typ, LOC115, ((Tstorageloc294812) 0)); } goto LA108; LA113: ; { gensetconstr_559496_839829468(p0, n0, d0); } LA108: ; } break; case ((Tnodekind294020) 41): { { NIM_BOOL LOC120; NI LOC122; LOC120 = (NIM_BOOL)0; LOC120 = isdeepconstexpr_320566_2616423590(n0); if (!(LOC120)) goto LA121; LOC122 = (NI)0; LOC122 = len_295081_850551059(n0); LOC120 = !((LOC122 == ((NI) 0))); LA121: ; if (!LOC120) goto LA123; exprcomplexconst_560684_839829468(p0, n0, d0); } goto LA118; LA123: ; { Ttype294840* LOC126; LOC126 = (Ttype294840*)0; LOC126 = skiptypes_298099_850551059((*n0).typ, IL64(211106242013440)); if (!((*LOC126).kind == ((Ttypekind294244) 24))) goto LA127; genseqconstr_557004_839829468(p0, n0, d0); } goto LA118; LA127: ; { genarrayconstr_560207_839829468(p0, n0, d0); } LA118: ; } break; case ((Tnodekind294020) 37): { { NIM_BOOL LOC133; NI LOC135; LOC133 = (NIM_BOOL)0; LOC133 = isdeepconstexpr_320566_2616423590(n0); if (!(LOC133)) goto LA134; LOC135 = (NI)0; LOC135 = len_295081_850551059(n0); LOC133 = !((LOC135 == ((NI) 0))); LA134: ; if (!LOC133) goto LA136; exprcomplexconst_560684_839829468(p0, n0, d0); } goto LA131; LA136: ; { gentupleconstr_559618_839829468(p0, n0, d0); } LA131: ; } break; case ((Tnodekind294020) 38): { genobjconstr_556903_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 61): { gencast_558538_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 58): case ((Tnodekind294020) 59): case ((Tnodekind294020) 60): { genconv_558633_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 64): case ((Tnodekind294020) 63): { genaddr_555051_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 42): { genbracketexpr_556277_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 47): case ((Tnodekind294020) 65): { genderef_545921_839829468(p0, n0, d0, NIM_FALSE); } break; case ((Tnodekind294020) 45): { genrecordfield_555448_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 46): { gencheckedrecordfield_556046_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 127): case ((Tnodekind294020) 112): { genblock_548083_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 126): { genstmtlistexpr_560402_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 115): { { NI i_561023_839829468; NI HEX3Atmp_561276_839829468; NI LOC151; NI res_561279_839829468; i_561023_839829468 = (NI)0; HEX3Atmp_561276_839829468 = (NI)0; LOC151 = (NI)0; LOC151 = sonslen_297351_850551059(n0); HEX3Atmp_561276_839829468 = (NI)(LOC151 - ((NI) 1)); res_561279_839829468 = ((NI) 0); { while (1) { if (!(res_561279_839829468 <= HEX3Atmp_561276_839829468)) goto LA153; i_561023_839829468 = res_561279_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[i_561023_839829468]); res_561279_839829468 += ((NI) 1); } LA153: ; } } } break; case ((Tnodekind294020) 48): case ((Tnodekind294020) 92): { genif_546982_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 93): { expr_541248_839829468(p0, (*(*n0).kindU.S6.sons->data[((NI) 1)]).kindU.S6.sons->data[((NI) 0)], d0); } break; case ((Tnodekind294020) 66): { downconv_560581_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 67): { upconv_560431_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 68): { genrangechck_558591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_563)); } break; case ((Tnodekind294020) 69): { genrangechck_558591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_564)); } break; case ((Tnodekind294020) 70): { genrangechck_558591_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_565)); } break; case ((Tnodekind294020) 71): { convstrtocstr_558643_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 72): { convcstrtostr_558655_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 51): case ((Tnodekind294020) 52): { Tsym294834* sym0; sym0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; genproc_534951_839829468((*p0).module, sym0); { NIM_BOOL LOC166; NimStringDesc* LOC170; LOC166 = (NIM_BOOL)0; LOC166 = ((*sym0).loc.r == NIM_NIL); if (LOC166) goto LA167; LOC166 = ((*sym0).loc.t == NIM_NIL); LA167: ; if (!LOC166) goto LA168; LOC170 = (NimStringDesc*)0; LOC170 = rawNewString((*(*sym0).name).s->Sup.len + 20); appendString(LOC170, ((NimStringDesc*) &T839829468_271)); appendString(LOC170, (*(*sym0).name).s); internalerror_198100_155036129((*n0).info, LOC170); } LA168: ; putlocintodest_541258_839829468(p0, d0, (&(*sym0).loc)); } break; case ((Tnodekind294020) 155): { genclosure_559836_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 1): { } break; case ((Tnodekind294020) 96): { genwhilestmt_547985_839829468(p0, n0); } break; case ((Tnodekind294020) 99): case ((Tnodekind294020) 100): { genvarstmt_546854_839829468(p0, n0); } break; case ((Tnodekind294020) 101): { genconststmt_546909_839829468(p0, n0); } break; case ((Tnodekind294020) 94): { internalerror_198100_155036129((*n0).info, ((NimStringDesc*) &T839829468_594)); } break; case ((Tnodekind294020) 97): { gencase_549827_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 109): { genreturnstmt_547617_839829468(p0, n0); } break; case ((Tnodekind294020) 110): { genbreakstmt_548444_839829468(p0, n0); } break; case ((Tnodekind294020) 73): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag294427) 14))&15U)))!=0))) goto LA183; genasgn_551239_839829468(p0, n0, NIM_FALSE); } LA183: ; } break; case ((Tnodekind294020) 74): { { if (!!((((*n0).flags &(1U<<((NU)(((Tnodeflag294427) 14))&15U)))!=0))) goto LA188; genasgn_551239_839829468(p0, n0, !(((*p0).prc == NIM_NIL))); } LA188: ; } break; case ((Tnodekind294020) 114): { { Tloc294816 a0; if (!!(((*(*n0).kindU.S6.sons->data[((NI) 0)]).kind == ((Tnodekind294020) 1)))) goto LA193; genlinedir_534823_839829468(p0, n0); memset((void*)(&a0), 0, sizeof(a0)); initlocexpr_541283_839829468(p0, (*n0).kindU.S6.sons->data[((NI) 0)], (&a0)); } LA193: ; } break; case ((Tnodekind294020) 89): { genasmstmt_550659_839829468(p0, n0); } break; case ((Tnodekind294020) 106): { { NIM_BOOL LOC199; NIM_BOOL LOC200; LOC199 = (NIM_BOOL)0; LOC200 = (NIM_BOOL)0; LOC200 = (gcmd_171132_2607990831 == ((Tcommands171076) 2)); if (LOC200) goto LA201; LOC200 = (((*(*(*p0).module).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA201: ; LOC199 = LOC200; if (!(LOC199)) goto LA202; LOC199 = !(((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 31))&63U)))!=0)); LA202: ; if (!LOC199) goto LA203; gentrycpp_549866_839829468(p0, n0, d0); } goto LA197; LA203: ; { gentry_550114_839829468(p0, n0, d0); } LA197: ; } break; case ((Tnodekind294020) 108): { genraisestmt_548828_839829468(p0, n0); } break; case ((Tnodekind294020) 98): { gentypesection_540184_839829468((*p0).module, n0); } break; case ((Tnodekind294020) 125): case ((Tnodekind294020) 84): case ((Tnodekind294020) 121): case ((Tnodekind294020) 116): case ((Tnodekind294020) 117): case ((Tnodekind294020) 118): case ((Tnodekind294020) 119): case ((Tnodekind294020) 120): case ((Tnodekind294020) 83): case ((Tnodekind294020) 82): { } break; case ((Tnodekind294020) 90): { genpragma_551039_839829468(p0, n0); } break; case ((Tnodekind294020) 91): { Tnode294802* LOC211; LOC211 = (Tnode294802*)0; LOC211 = lastson_297364_850551059(n0); expr_541248_839829468(p0, LOC211, d0); } break; case ((Tnodekind294020) 79): case ((Tnodekind294020) 80): case ((Tnodekind294020) 81): { { Tsym294834* prc0; if (!((*(*n0).kindU.S6.sons->data[((NI) 2)]).kind == ((Tnodekind294020) 1))) goto LA215; prc0 = (*(*n0).kindU.S6.sons->data[((NI) 0)]).kindU.S4.sym; { NIM_BOOL LOC219; Tsym294834* LOC220; LOC219 = (NIM_BOOL)0; LOC220 = (Tsym294834*)0; LOC220 = skipgenericowner_299280_850551059(prc0); LOC219 = ((*LOC220).kind == ((Tsymkind294435) 6)); if (!(LOC219)) goto LA221; LOC219 = !((((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 23))&31U)))!=0)); LA221: ; if (!LOC219) goto LA222; { NIM_BOOL LOC226; NIM_BOOL LOC227; NIM_BOOL LOC228; NIM_BOOL LOC229; Tsym294834* LOC231; NIM_BOOL LOC234; LOC226 = (NIM_BOOL)0; LOC227 = (NIM_BOOL)0; LOC228 = (NIM_BOOL)0; LOC229 = (NIM_BOOL)0; LOC229 = !(((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 2))&63U)))!=0)); if (!(LOC229)) goto LA230; LOC231 = (Tsym294834*)0; LOC231 = getmodule_301123_2984716966(prc0); LOC229 = !((((*LOC231).flags &(1U<<((NU)(((Tsymflag294184) 25))&31U)))!=0)); LA230: ; LOC228 = LOC229; if (LOC228) goto LA232; LOC228 = ((65600 & (*prc0).flags) == 64); LA232: ; LOC227 = LOC228; if (LOC227) goto LA233; LOC234 = (NIM_BOOL)0; LOC234 = (((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 6))&31U)))!=0); if (!(LOC234)) goto LA235; LOC234 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 5))&15U)))!=0); LA235: ; LOC227 = LOC234; LA233: ; LOC226 = LOC227; if (LOC226) goto LA236; LOC226 = ((*prc0).kind == ((Tsymkind294435) 13)); LA236: ; if (!LOC226) goto LA237; { NIM_BOOL LOC241; Tnode294802* LOC242; LOC241 = (NIM_BOOL)0; LOC242 = (Tnode294802*)0; LOC242 = getbody_337226_1724185294(prc0); LOC241 = !(((*LOC242).kind == ((Tnodekind294020) 1))); if (LOC241) goto LA243; LOC241 = (((*prc0).loc.flags &(1U<<((NU)(((Tlocflag294810) 4))&15U)))!=0); LA243: ; if (!LOC241) goto LA244; genproc_534951_839829468((*p0).module, prc0); } LA244: ; } LA237: ; } LA222: ; } LA215: ; } break; case ((Tnodekind294020) 95): { genparforstmt_548208_839829468(p0, n0); } break; case ((Tnodekind294020) 157): { genstate_546117_839829468(p0, n0); } break; case ((Tnodekind294020) 156): { gengotostate_546144_839829468(p0, n0); } break; case ((Tnodekind294020) 158): { genbreakstate_546229_839829468(p0, n0); } break; default: { NimStringDesc* LOC251; LOC251 = (NimStringDesc*)0; LOC251 = rawNewString(reprEnum((NI)(*n0).kind, (&NTI294020))->Sup.len + 25); appendString(LOC251, ((NimStringDesc*) &T839829468_291)); appendString(LOC251, reprEnum((NI)(*n0).kind, (&NTI294020))); appendString(LOC251, ((NimStringDesc*) &T839829468_657)); internalerror_198100_155036129((*n0).info, LOC251); } break; } } N_NIMCALL(void, genstmts_541244_839829468)(Tcproc531021* p0, Tnode294802* t0) { Tloc294816 a0; memset((void*)(&a0), 0, sizeof(a0)); expr_541248_839829468(p0, t0, (&a0)); { NimStringDesc* LOC5; if (!!(((7 &(1U<<((NU)(a0.k)&15U)))!=0))) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = HEX24_198185_1689653243(T839829468_658); internalerror_198113_155036129(LOC5); } LA3: ; } N_NIMCALL(Tnode294802*, myprocess_565402_839829468)(Tpasscontext343002* b0, Tnode294802* n0) { Tnode294802* result0; Tcgen531027* m0; { result0 = (Tnode294802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_343085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen531027*) (b0)); (*(*m0).initproc).options = initprocoptions_564635_839829468(m0); genstmts_541244_839829468((*m0).initproc, n0); }BeforeRet: ; return result0; } N_NIMCALL(Ropeobj180006*, getsomeinitname_563904_839829468)(Tsym294834* m0, NimStringDesc* suffix0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { NimStringDesc* LOC5; if (!((12288 & (*m0).flags) == 0)) goto LA3; LOC5 = (NimStringDesc*)0; LOC5 = mangle_530847_2036603609((*(*(*m0).owner).name).s); result0 = rope_180277_2381377266(LOC5); add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_12)); } LA3: ; add_180487_2381377266(&result0, (*(*m0).name).s); add_180487_2381377266(&result0, suffix0); return result0; } N_NIMCALL(Ropeobj180006*, getinitname_564235_839829468)(Tsym294834* m0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = getsomeinitname_563904_839829468(m0, ((NimStringDesc*) &T839829468_659)); return result0; } N_NIMCALL(Ropeobj180006*, getdatinitname_564239_839829468)(Tsym294834* m0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = getsomeinitname_563904_839829468(m0, ((NimStringDesc*) &T839829468_660)); return result0; } N_NIMCALL(void, registermoduletomain_564243_839829468)(Tsym294834* m0) { Ropeobj180006* init0; Ropeobj180006* datinit0; TY180507 LOC1; TY180507 LOC2; init0 = getinitname_564235_839829468(m0); datinit0 = getdatinitname_564239_839829468(m0); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = init0; addf_181205_2381377266(&mainmodprocs_531148_3723162438, ((NimStringDesc*) &T839829468_661), LOC1, 1); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = datinit0; addf_181205_2381377266(&mainmodprocs_531148_3723162438, ((NimStringDesc*) &T839829468_661), LOC2, 1); { TY180507 LOC7; Ropeobj180006* initcall0; TY180507 LOC8; if (!!((((*m0).flags &(1U<<((NU)(((Tsymflag294184) 13))&31U)))!=0))) goto LA5; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = datinit0; addf_181205_2381377266(&maindatinit_531151_3723162438, ((NimStringDesc*) &T839829468_662), LOC7, 1); memset((void*)LOC8, 0, sizeof(LOC8)); LOC8[0] = init0; initcall0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_662), LOC8, 1); { if (!(((*m0).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)) goto LA11; add_180482_2381377266(&mainmodinit_531149_3723162438, initcall0); } goto LA9; LA11: ; { add_180482_2381377266(&othermodsinit_531150_3723162438, initcall0); } LA9: ; } LA5: ; } N_NIMCALL(Ropeobj180006*, genfilenames_563688_839829468)(Tcgen531027* m0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; LOC1 = (Ropeobj180006*)0; LOC1 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_673)); result0 = NIM_NIL; { NI i_563717_839829468; NI HEX3Atmp_563722_839829468; NI res_563725_839829468; i_563717_839829468 = (NI)0; HEX3Atmp_563722_839829468 = (NI)0; HEX3Atmp_563722_839829468 = ((fileinfos_193629_155036129 ? fileinfos_193629_155036129->Sup.len : 0) - 1); res_563725_839829468 = ((NI) 0); { while (1) { TY180507 LOC5; if (!(res_563725_839829468 <= HEX3Atmp_563722_839829468)) goto LA4; i_563717_839829468 = res_563725_839829468; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = makecstring_193638_155036129(fileinfos_193629_155036129->data[i_563717_839829468].projpath); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_674), LOC5, 1); res_563725_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genmainproc_563729_839829468)(Tcgen531027* m0) { NimStringDesc* nimmain0; NimStringDesc* othermain0; Ropeobj180006* initstackbottomcall0; TY538475 LOC38; TY537238 LOC47; nimmain0 = (NimStringDesc*)0; othermain0 = (NimStringDesc*)0; { NIM_BOOL LOC3; NIM_BOOL LOC12; LOC3 = (NIM_BOOL)0; LOC3 = (targetos_178629_4151366050 == ((Tsystemos178004) 2)); if (!(LOC3)) goto LA4; LOC3 = !(((gglobaloptions_171130_2607990831 & 1280) == 0)); LA4: ; if (!LOC3) goto LA5; { if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 10))&63U)))!=0)) goto LA9; nimmain0 = copyString(((NimStringDesc*) &T839829468_663)); othermain0 = copyString(((NimStringDesc*) &T839829468_664)); } goto LA7; LA9: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_666)); } LA7: ; LOC12 = (NIM_BOOL)0; LOC12 = includestr_148249_3771138726((&(*m0).headerfiles), ((NimStringDesc*) &T839829468_667)); } goto LA1; LA5: ; { if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 8))&63U)))!=0)) goto LA14; nimmain0 = copyString(((NimStringDesc*) &T839829468_665)); othermain0 = copyString(((NimStringDesc*) &T839829468_668)); } goto LA1; LA14: ; { if (!(targetos_178629_4151366050 == ((Tsystemos178004) 24))) goto LA17; nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_670)); } goto LA1; LA17: ; { nimmain0 = copyString(((NimStringDesc*) &T839829468_669)); othermain0 = copyString(((NimStringDesc*) &T839829468_671)); } LA1: ; { Ropeobj180006* LOC24; if (!!((gbreakpoints_550861_839829468 == NIM_NIL))) goto LA22; LOC24 = (Ropeobj180006*)0; LOC24 = cgsym_534403_839829468(m0, ((NimStringDesc*) &T839829468_672)); } LA22: ; { Ropeobj180006* LOC29; if (!((goptions_171128_2607990831 &(1U<<((NU)(((Toption171009) 17))&31U)))!=0)) goto LA27; LOC29 = (Ropeobj180006*)0; LOC29 = genfilenames_563688_839829468(m0); add_180482_2381377266(&gbreakpoints_550861_839829468, LOC29); } LA27: ; { NIM_BOOL LOC32; LOC32 = (NIM_BOOL)0; LOC32 = (targetos_178629_4151366050 == ((Tsystemos178004) 24)); if (LOC32) goto LA33; LOC32 = (gselectedgc_171133_2607990831 == ((Tgcmode171080) 0)); LA33: ; if (!LOC32) goto LA34; initstackbottomcall0 = rope_180277_2381377266(((NimStringDesc*) &T839829468_490)); } goto LA30; LA34: ; { TY535289 LOC37; memset((void*)LOC37, 0, sizeof(LOC37)); initstackbottomcall0 = ropecg_534407_839829468(m0, ((NimStringDesc*) &T839829468_675), LOC37, 0); } LA30: ; (*m0).labels += ((NI) 1); memset((void*)LOC38, 0, sizeof(LOC38)); LOC38[0] = maindatinit_531151_3723162438; LOC38[1] = gbreakpoints_550861_839829468; LOC38[2] = othermodsinit_531150_3723162438; { NIM_BOOL LOC41; TY535289 LOC45; LOC41 = (NIM_BOOL)0; LOC41 = emulatedthreadvars_534949_839829468(); if (!(LOC41)) goto LA42; LOC41 = !((targetos_178629_4151366050 == ((Tsystemos178004) 24))); LA42: ; if (!LOC41) goto LA43; memset((void*)LOC45, 0, sizeof(LOC45)); LOC38[3] = ropecg_534407_839829468(m0, ((NimStringDesc*) &T839829468_677), LOC45, 0); } goto LA39; LA43: ; { LOC38[3] = rope_180277_2381377266(((NimStringDesc*) &T839829468_490)); } LA39: ; LOC38[4] = initstackbottomcall0; appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 10))- 0], ((NimStringDesc*) &T839829468_676), LOC38, 5); memset((void*)LOC47, 0, sizeof(LOC47)); LOC47[0] = mainmodinit_531149_3723162438; LOC47[1] = initstackbottomcall0; LOC47[2] = rope_180401_2381377266(((NI64) ((*m0).labels))); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 10))- 0], nimmain0, LOC47, 3); { TY535289 LOC52; if (!!(((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 20))&63U)))!=0))) goto LA50; memset((void*)LOC52, 0, sizeof(LOC52)); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 10))- 0], othermain0, LOC52, 0); } LA50: ; } N_NIMCALL(Tnode294802*, myclose_565830_839829468)(Tpasscontext343002* b0, Tnode294802* n0) { Tnode294802* result0; Tcgen531027* m0; { result0 = (Tnode294802*)0; result0 = n0; { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = (b0 == NIM_NIL); if (LOC3) goto LA4; LOC3 = skipcodegen_343085_2355241294(n0); LA4: ; if (!LOC3) goto LA5; goto BeforeRet; } LA5: ; m0 = ((Tcgen531027*) (b0)); { if (!!((n0 == NIM_NIL))) goto LA9; (*(*m0).initproc).options = initprocoptions_564635_839829468(m0); genstmts_541244_839829468((*m0).initproc, n0); } LA9: ; registermoduletomain_564243_839829468((*m0).module); { Tnode294802* disp0; if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)) goto LA13; (*m0).flags |= ((NU8)1)<<((((Codegenflag531025) 5))%(sizeof(NU8)*8)); disp0 = generatemethoddispatchers_434151_3853300031(); { NI i_565891_839829468; NI HEX3Atmp_565895_839829468; NI LOC16; NI res_565898_839829468; i_565891_839829468 = (NI)0; HEX3Atmp_565895_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_297351_850551059(disp0); HEX3Atmp_565895_839829468 = (NI)(LOC16 - ((NI) 1)); res_565898_839829468 = ((NI) 0); { while (1) { if (!(res_565898_839829468 <= HEX3Atmp_565895_839829468)) goto LA18; i_565891_839829468 = res_565898_839829468; genprocaux_562284_839829468(m0, (*(*disp0).kindU.S6.sons->data[i_565891_839829468]).kindU.S4.sym); res_565898_839829468 += ((NI) 1); } LA18: ; } } genmainproc_563729_839829468(m0); } LA13: ; }BeforeRet: ; return result0; } N_NIMCALL(void, finishmodule_565420_839829468)(Tcgen531027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Tsym294834* prc0; if (!(i0 <= ((*m0).forwardedprocs ? ((*m0).forwardedprocs->Sup.len-1) : -1))) goto LA2; prc0 = (*m0).forwardedprocs->data[i0]; { NimStringDesc* LOC7; if (!(((*prc0).flags &(1U<<((NU)(((Tsymflag294184) 4))&31U)))!=0)) goto LA5; LOC7 = (NimStringDesc*)0; LOC7 = rawNewString((*(*prc0).name).s->Sup.len + 17); appendString(LOC7, ((NimStringDesc*) &T839829468_678)); appendString(LOC7, (*(*prc0).name).s); internalerror_198100_155036129((*prc0).info, LOC7); } LA5: ; genprocnoforward_562906_839829468(m0, prc0); i0 += ((NI) 1); } LA2: ; } gforwardedprocscounter_531171_3723162438 -= i0; (*m0).forwardedprocs = (Tsymseq294804*) setLengthSeq(&((*m0).forwardedprocs)->Sup, sizeof(Tsym294834*), ((NI) 0)); } N_NIMCALL(void, geninitcode_564286_839829468)(Tcgen531027* m0) { Ropeobj180006* initname0; Ropeobj180006* prc0; TY180507 LOC1; Ropeobj180006* LOC12; Ropeobj180006* LOC13; Ropeobj180006** LOC14; Ropeobj180006** LOC15; Ropeobj180006** LOC16; Ropeobj180006* LOC17; Ropeobj180006* LOC33; Ropeobj180006** LOC34; Ropeobj180006** LOC35; Ropeobj180006** LOC36; Ropeobj180006* LOC37; Ropeobj180006* LOC38; Ropeobj180006** LOC39; Ropeobj180006** LOC40; Ropeobj180006** LOC41; Ropeobj180006* LOC42; Ropeobj180006* LOC50; TY535289 LOC51; TY180507 LOC52; TY535289 LOC58; initname0 = getinitname_564235_839829468((*m0).module); memset((void*)LOC1, 0, sizeof(LOC1)); LOC1[0] = initname0; prc0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_679), LOC1, 1); { TY534811 LOC6; if (!(((NI) 0) < (*m0).typenodes)) goto LA4; memset((void*)LOC6, 0, sizeof(LOC6)); LOC6[0] = (*m0).typenodesname; LOC6[1] = rope_180401_2381377266(((NI64) ((*m0).typenodes))); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_680), LOC6, 2); } LA4: ; { TY534811 LOC11; if (!(((NI) 0) < (*m0).nimtypes)) goto LA9; memset((void*)LOC11, 0, sizeof(LOC11)); LOC11[0] = (*m0).nimtypesname; LOC11[1] = rope_180401_2381377266(((NI64) ((*m0).nimtypes))); appcg_534632_839829468(m0, &(*m0).s[(((Tcfilesection531005) 12))- 0], ((NimStringDesc*) &T839829468_681), LOC11, 2); } LA9: ; LOC12 = (Ropeobj180006*)0; LOC12 = initgcframe_540435_839829468((*m0).initproc); add_180482_2381377266(&prc0, LOC12); LOC13 = (Ropeobj180006*)0; LOC13 = gensectionstart_532081_2760143328(((Tcprocsection531011) 0)); add_180482_2381377266(&prc0, LOC13); LOC14 = (Ropeobj180006**)0; LOC14 = s_531179_3723162438((*m0).preinitproc, ((Tcprocsection531011) 0)); add_180482_2381377266(&prc0, (*LOC14)); LOC15 = (Ropeobj180006**)0; LOC15 = s_531179_3723162438((*m0).initproc, ((Tcprocsection531011) 0)); add_180482_2381377266(&prc0, (*LOC15)); LOC16 = (Ropeobj180006**)0; LOC16 = s_531179_3723162438((*m0).postinitproc, ((Tcprocsection531011) 0)); add_180482_2381377266(&prc0, (*LOC16)); LOC17 = (Ropeobj180006*)0; LOC17 = gensectionend_532116_2760143328(((Tcprocsection531011) 0)); add_180482_2381377266(&prc0, LOC17); { NIM_BOOL LOC20; LOC20 = (NIM_BOOL)0; LOC20 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0); if (!(LOC20)) goto LA21; LOC20 = !((((*m0).flags &(1U<<((NU)(((Codegenflag531025) 2))&7U)))!=0)); LA21: ; if (!LOC20) goto LA22; (*m0).flags |= ((NU8)1)<<((((Codegenflag531025) 2))%(sizeof(NU8)*8)); { Ropeobj180006* procname0; Ropeobj180006* LOC28; Ropeobj180006* LOC29; if (!!((((*m0).flags &(1U<<((NU)(((Codegenflag531025) 0))&7U)))!=0))) goto LA26; procname0 = makecstring_193638_155036129((*(*(*m0).module).name).s); LOC28 = (Ropeobj180006*)0; LOC28 = quotedfilename_198818_155036129((*(*m0).module).info); LOC29 = (Ropeobj180006*)0; LOC29 = initframe_562140_839829468((*m0).initproc, procname0, LOC28); add_180482_2381377266(&prc0, LOC29); } goto LA24; LA26: ; { TY535289 LOC31; Ropeobj180006* LOC32; memset((void*)LOC31, 0, sizeof(LOC31)); LOC32 = (Ropeobj180006*)0; LOC32 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_682), LOC31, 0); add_180482_2381377266(&prc0, LOC32); } LA24: ; } LA22: ; LOC33 = (Ropeobj180006*)0; LOC33 = gensectionstart_532081_2760143328(((Tcprocsection531011) 1)); add_180482_2381377266(&prc0, LOC33); LOC34 = (Ropeobj180006**)0; LOC34 = s_531179_3723162438((*m0).preinitproc, ((Tcprocsection531011) 1)); add_180482_2381377266(&prc0, (*LOC34)); LOC35 = (Ropeobj180006**)0; LOC35 = s_531179_3723162438((*m0).initproc, ((Tcprocsection531011) 1)); add_180482_2381377266(&prc0, (*LOC35)); LOC36 = (Ropeobj180006**)0; LOC36 = s_531179_3723162438((*m0).postinitproc, ((Tcprocsection531011) 1)); add_180482_2381377266(&prc0, (*LOC36)); LOC37 = (Ropeobj180006*)0; LOC37 = gensectionend_532116_2760143328(((Tcprocsection531011) 1)); add_180482_2381377266(&prc0, LOC37); LOC38 = (Ropeobj180006*)0; LOC38 = gensectionstart_532081_2760143328(((Tcprocsection531011) 2)); add_180482_2381377266(&prc0, LOC38); LOC39 = (Ropeobj180006**)0; LOC39 = s_531179_3723162438((*m0).preinitproc, ((Tcprocsection531011) 2)); add_180482_2381377266(&prc0, (*LOC39)); LOC40 = (Ropeobj180006**)0; LOC40 = s_531179_3723162438((*m0).initproc, ((Tcprocsection531011) 2)); add_180482_2381377266(&prc0, (*LOC40)); LOC41 = (Ropeobj180006**)0; LOC41 = s_531179_3723162438((*m0).postinitproc, ((Tcprocsection531011) 2)); add_180482_2381377266(&prc0, (*LOC41)); LOC42 = (Ropeobj180006*)0; LOC42 = gensectionend_532116_2760143328(((Tcprocsection531011) 2)); add_180482_2381377266(&prc0, LOC42); { NIM_BOOL LOC45; Ropeobj180006* LOC49; LOC45 = (NIM_BOOL)0; LOC45 = (((*(*m0).initproc).options &(1U<<((NU)(((Toption171009) 15))&31U)))!=0); if (!(LOC45)) goto LA46; LOC45 = !((((*m0).flags &(1U<<((NU)(((Codegenflag531025) 0))&7U)))!=0)); LA46: ; if (!LOC45) goto LA47; LOC49 = (Ropeobj180006*)0; LOC49 = deinitframe_562150_839829468((*m0).initproc); add_180482_2381377266(&prc0, LOC49); } LA47: ; LOC50 = (Ropeobj180006*)0; LOC50 = deinitgcframe_540441_839829468((*m0).initproc); add_180482_2381377266(&prc0, LOC50); memset((void*)LOC51, 0, sizeof(LOC51)); addf_181205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC51, 0); memset((void*)LOC52, 0, sizeof(LOC52)); LOC52[0] = getdatinitname_564239_839829468((*m0).module); addf_181205_2381377266(&prc0, ((NimStringDesc*) &T839829468_679), LOC52, 1); { Tcfilesection531005 i_564401_839829468; NI res_564482_839829468; i_564401_839829468 = (Tcfilesection531005)0; res_564482_839829468 = ((NI) 12); { while (1) { Ropeobj180006* LOC56; Ropeobj180006* LOC57; if (!(res_564482_839829468 <= ((NI) 16))) goto LA55; i_564401_839829468 = ((Tcfilesection531005) (res_564482_839829468)); LOC56 = (Ropeobj180006*)0; LOC56 = gensectionstart_532015_2760143328(i_564401_839829468); add_180482_2381377266(&prc0, LOC56); add_180482_2381377266(&prc0, (*m0).s[(i_564401_839829468)- 0]); LOC57 = (Ropeobj180006*)0; LOC57 = gensectionend_532050_2760143328(i_564401_839829468); add_180482_2381377266(&prc0, LOC57); res_564482_839829468 += ((NI) 1); } LA55: ; } } memset((void*)LOC58, 0, sizeof(LOC58)); addf_181205_2381377266(&prc0, ((NimStringDesc*) &T839829468_683), LOC58, 0); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 11))- 0], prc0); { NIM_CHAR i_564442_839829468; Ropeobj180006* el_564443_839829468; TY531136 HEX3Atmp_564487_839829468; NIM_CHAR i_564490_839829468; i_564442_839829468 = (NIM_CHAR)0; el_564443_839829468 = (Ropeobj180006*)0; memset((void*)HEX3Atmp_564487_839829468, 0, sizeof(HEX3Atmp_564487_839829468)); memcpy((void*)HEX3Atmp_564487_839829468, (NIM_CONST void*)(*m0).extensionloaders, sizeof(HEX3Atmp_564487_839829468)); i_564490_839829468 = 48; { if (!((NU8)(((NIM_CHAR) (((NU8)(i_564490_839829468))))) <= (NU8)(57))) goto LA62; { while (1) { i_564442_839829468 = i_564490_839829468; el_564443_839829468 = HEX3Atmp_564487_839829468[(((NU8)(i_564490_839829468)))- 48]; { Ropeobj180006* ex0; TY534811 LOC70; if (!!((el_564443_839829468 == NIM_NIL))) goto LA68; memset((void*)LOC70, 0, sizeof(LOC70)); LOC70[0] = rope_180401_2381377266(((NI64) ((NI)(((NI) (((NU8)(i_564442_839829468)))) - ((NI) 48))))); LOC70[1] = el_564443_839829468; ex0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_684), LOC70, 2); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 11))- 0], ex0); } LA68: ; { if (!((NU8)(57) <= (NU8)(((NIM_CHAR) (((NU8)(i_564490_839829468))))))) goto LA73; goto LA64; } LA73: ; i_564490_839829468 += ((NI) 1); } } LA64: ; } LA62: ; } } N_NIMCALL(void, finishtypedescriptions_537842_839829468)(Tcgen531027* m0) { NI i0; i0 = ((NI) 0); { while (1) { Ropeobj180006* LOC3; if (!(i0 < ((*m0).typestack ? (*m0).typestack->Sup.len : 0))) goto LA2; LOC3 = (Ropeobj180006*)0; LOC3 = gettypedesc_537673_839829468(m0, (*m0).typestack->data[i0]); i0 += ((NI) 1); } LA2: ; } } N_NIMCALL(Ropeobj180006*, getcopyright_563665_839829468)(NimStringDesc* cfile0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; { TY180507 LOC5; if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 4))&63U)))!=0)) goto LA3; memset((void*)LOC5, 0, sizeof(LOC5)); LOC5[0] = rope_180277_2381377266(((NimStringDesc*) &T839829468_686)); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_685), LOC5, 1); } goto LA1; LA3: ; { TY538475 LOC7; NimStringDesc* LOC8; memset((void*)LOC7, 0, sizeof(LOC7)); LOC7[0] = rope_180277_2381377266(((NimStringDesc*) &T839829468_686)); LOC7[1] = rope_180277_2381377266(Os_178068_4151366050[(targetos_178629_4151366050)- 1].Field0); LOC7[2] = rope_180277_2381377266(Cpu_178496_4151366050[(targetcpu_178627_4151366050)- 1].Field0); LOC7[3] = rope_180277_2381377266(Cc_275413_2528170400[(ccompiler_275431_2528170400)- 1].Field0); LOC8 = (NimStringDesc*)0; LOC8 = getcompilecfilecmd_276284_2528170400(cfile0, NIM_FALSE); LOC7[4] = rope_180277_2381377266(LOC8); result0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_687), LOC7, 5); } LA1: ; return result0; } static N_INLINE(void, addinttypes_563659_839829468)(Ropeobj180006** result0) { NimStringDesc* LOC1; TY180507 LOC2; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_178644_4151366050->Sup.len + 22); appendString(LOC1, ((NimStringDesc*) &T839829468_688)); appendString(LOC1, tnl_178644_4151366050); memset((void*)LOC2, 0, sizeof(LOC2)); LOC2[0] = rope_180401_2381377266(((NI64) (Cpu_178496_4151366050[(targetcpu_178627_4151366050)- 1].Field1))); addf_181205_2381377266(result0, LOC1, LOC2, 1); } N_NIMCALL(Ropeobj180006*, getfileheader_563683_839829468)(NimStringDesc* cfile0) { Ropeobj180006* result0; result0 = (Ropeobj180006*)0; result0 = getcopyright_563665_839829468(cfile0); addinttypes_563659_839829468(&result0); return result0; } N_NIMCALL(void, generatethreadlocalstorage_540717_839829468)(Tcgen531027* m0) { { NIM_BOOL LOC3; NIM_BOOL LOC5; TY180507 LOC13; LOC3 = (NIM_BOOL)0; LOC3 = !((nimtv_540656_839829468 == NIM_NIL)); if (!(LOC3)) goto LA4; LOC5 = (NIM_BOOL)0; LOC5 = (((*m0).flags &(1U<<((NU)(((Codegenflag531025) 1))&7U)))!=0); if (LOC5) goto LA6; LOC5 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0); LA6: ; LOC3 = LOC5; LA4: ; if (!LOC3) goto LA7; { Ttype294840* t_540761_839829468; NI i_540768_839829468; NI L_540770_839829468; t_540761_839829468 = (Ttype294840*)0; i_540768_839829468 = ((NI) 0); L_540770_839829468 = (nimtvdeps_540674_839829468 ? nimtvdeps_540674_839829468->Sup.len : 0); { while (1) { Ropeobj180006* LOC12; if (!(i_540768_839829468 < L_540770_839829468)) goto LA11; t_540761_839829468 = nimtvdeps_540674_839829468->data[i_540768_839829468]; LOC12 = (Ropeobj180006*)0; LOC12 = gettypedesc_537673_839829468(m0, t_540761_839829468); i_540768_839829468 += ((NI) 1); } LA11: ; } } memset((void*)LOC13, 0, sizeof(LOC13)); LOC13[0] = nimtv_540656_839829468; addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 4))- 0], ((NimStringDesc*) &T839829468_689), LOC13, 1); } LA7: ; } N_NIMCALL(void, generateheaders_562104_839829468)(Tcgen531027* m0) { NimStringDesc* LOC1; Tstrentry148009* it0; LOC1 = (NimStringDesc*)0; LOC1 = rawNewString(tnl_178644_4151366050->Sup.len + tnl_178644_4151366050->Sup.len + 20); appendString(LOC1, tnl_178644_4151366050); appendString(LOC1, ((NimStringDesc*) &T839829468_690)); appendString(LOC1, tnl_178644_4151366050); add_180487_2381377266(&(*m0).s[(((Tcfilesection531005) 1))- 0], LOC1); it0 = ((Tstrentry148009*) ((*m0).headerfiles.head)); { while (1) { if (!!((it0 == NIM_NIL))) goto LA3; { NimStringDesc* LOC8; NimStringDesc* LOC9; Ropeobj180006* LOC10; if (!((NU8)((*it0).data->data[((NI) 0)]) == (NU8)(35))) goto LA6; LOC8 = (NimStringDesc*)0; LOC9 = (NimStringDesc*)0; LOC9 = nsuReplaceChar((*it0).data, 96, 34); LOC8 = rawNewString(LOC9->Sup.len + tnl_178644_4151366050->Sup.len + 0); appendString(LOC8, LOC9); appendString(LOC8, tnl_178644_4151366050); LOC10 = (Ropeobj180006*)0; LOC10 = rope_180277_2381377266(LOC8); add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 1))- 0], LOC10); } goto LA4; LA6: ; { TY180507 LOC14; if (!!((((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(34)) || ((NU8)((*it0).data->data[((NI) 0)])) == ((NU8)(60))))) goto LA12; memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = rope_180277_2381377266((*it0).data); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 1))- 0], ((NimStringDesc*) &T839829468_691), LOC14, 1); } goto LA4; LA12: ; { TY180507 LOC16; memset((void*)LOC16, 0, sizeof(LOC16)); LOC16[0] = rope_180277_2381377266((*it0).data); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 1))- 0], ((NimStringDesc*) &T839829468_692), LOC16, 1); } LA4: ; it0 = ((Tstrentry148009*) ((*it0).Sup.next)); } LA3: ; } } N_NIMCALL(Ropeobj180006*, genmodule_564491_839829468)(Tcgen531027* m0, NimStringDesc* cfile0) { Ropeobj180006* result0; Ropeobj180006* LOC1; result0 = (Ropeobj180006*)0; result0 = getfileheader_563683_839829468(cfile0); LOC1 = (Ropeobj180006*)0; LOC1 = genmergeinfo_532203_2760143328(m0); add_180482_2381377266(&result0, LOC1); generatethreadlocalstorage_540717_839829468(m0); generateheaders_562104_839829468(m0); { Tcfilesection531005 i_564614_839829468; NI res_564622_839829468; i_564614_839829468 = (Tcfilesection531005)0; res_564622_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC5; Ropeobj180006* LOC6; if (!(res_564622_839829468 <= ((NI) 10))) goto LA4; i_564614_839829468 = ((Tcfilesection531005) (res_564622_839829468)); LOC5 = (Ropeobj180006*)0; LOC5 = gensectionstart_532015_2760143328(i_564614_839829468); add_180482_2381377266(&result0, LOC5); add_180482_2381377266(&result0, (*m0).s[(i_564614_839829468)- 0]); LOC6 = (Ropeobj180006*)0; LOC6 = gensectionend_532050_2760143328(i_564614_839829468); add_180482_2381377266(&result0, LOC6); res_564622_839829468 += ((NI) 1); } LA4: ; } } add_180482_2381377266(&result0, (*m0).s[(((Tcfilesection531005) 11))- 0]); return result0; } N_NIMCALL(void, updatecachedmodule_565813_839829468)(Tcgen531027* m0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_565201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj180006* code0; LOC3 = (NIM_BOOL)0; LOC3 = mergerequired_532832_2760143328(m0); if (!(LOC3)) goto LA4; LOC3 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)); LA4: ; if (!LOC3) goto LA5; mergefiles_533241_2760143328(cfile0, m0); geninitcode_564286_839829468(m0); finishtypedescriptions_537842_839829468(m0); code0 = genmodule_564491_839829468(m0, cfile0); writerope_180836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_275863_2528170400(cfile0); } LA5: ; addfiletolink_275872_2528170400(cfilenoext0); } N_NIMCALL(void, generatethreadvarssize_540771_839829468)(Tcgen531027* m0) { { NimStringDesc* externc0; TY180507 LOC12; if (!!((nimtv_540656_839829468 == NIM_NIL))) goto LA3; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = !((gcmd_171132_2607990831 == ((Tcommands171076) 2))); if (!(LOC7)) goto LA8; LOC7 = (((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 27))&31U)))!=0); LA8: ; if (!LOC7) goto LA9; externc0 = copyString(((NimStringDesc*) &T839829468_693)); } goto LA5; LA9: ; { externc0 = copyString(((NimStringDesc*) &T839829468_490)); } LA5: ; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_180277_2381377266(externc0); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 10))- 0], ((NimStringDesc*) &T839829468_694), LOC12, 1); } LA3: ; } N_NIMCALL(NIM_BOOL, shouldrecompile_565621_839829468)(Ropeobj180006* code0, NimStringDesc* cfile0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; result0 = NIM_TRUE; { NimStringDesc* objfile0; if (!!(((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 1))&63U)))!=0))) goto LA3; objfile0 = toobjfile_275859_2528170400(cfile0); { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = writeropeifnotequal_181511_2381377266(code0, cfile0); if (!LOC7) goto LA8; goto BeforeRet; } LA8: ; { NIM_BOOL LOC12; LOC12 = (NIM_BOOL)0; LOC12 = nosexistsFile(objfile0); if (!(LOC12)) goto LA13; LOC12 = nosfileNewer(objfile0, cfile0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; } LA14: ; } goto LA1; LA3: ; { writerope_180836_2381377266(code0, cfile0, NIM_FALSE); } LA1: ; }BeforeRet: ; return result0; } N_NIMCALL(void, writemodule_565637_839829468)(Tcgen531027* m0, NIM_BOOL pending0) { NimStringDesc* cfile0; NimStringDesc* cfilenoext0; cfile0 = getcfile_565201_839829468(m0); cfilenoext0 = noschangeFileExt(cfile0, ((NimStringDesc*) &T839829468_490)); { NIM_BOOL LOC3; Ropeobj180006* code0; LOC3 = (NIM_BOOL)0; LOC3 = !((*m0).Sup.fromcache); if (LOC3) goto LA4; LOC3 = ((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 1))&63U)))!=0); LA4: ; if (!LOC3) goto LA5; geninitcode_564286_839829468(m0); finishtypedescriptions_537842_839829468(m0); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)) goto LA9; add_180482_2381377266(&(*m0).s[(((Tcfilesection531005) 7))- 0], mainmodprocs_531148_3723162438); generatethreadvarssize_540771_839829468(m0); } LA9: ; code0 = genmodule_564491_839829468(m0, cfile0); { NIM_BOOL LOC13; LOC13 = (NIM_BOOL)0; LOC13 = shouldrecompile_565621_839829468(code0, cfile0); if (!LOC13) goto LA14; addfiletocompile_275863_2528170400(cfile0); } LA14: ; } goto LA1; LA5: ; { NIM_BOOL LOC17; NIM_BOOL LOC18; Ropeobj180006* code0; LOC17 = (NIM_BOOL)0; LOC18 = (NIM_BOOL)0; LOC18 = pending0; if (!(LOC18)) goto LA19; LOC18 = mergerequired_532832_2760143328(m0); LA19: ; LOC17 = LOC18; if (!(LOC17)) goto LA20; LOC17 = !((((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 12))&31U)))!=0)); LA20: ; if (!LOC17) goto LA21; mergefiles_533241_2760143328(cfile0, m0); geninitcode_564286_839829468(m0); finishtypedescriptions_537842_839829468(m0); code0 = genmodule_564491_839829468(m0, cfile0); writerope_180836_2381377266(code0, cfile0, NIM_FALSE); addfiletocompile_275863_2528170400(cfile0); } goto LA1; LA21: ; { NimStringDesc* LOC24; NIM_BOOL LOC25; LOC24 = (NimStringDesc*)0; LOC24 = toobjfile_275859_2528170400(cfilenoext0); LOC25 = (NIM_BOOL)0; LOC25 = nosexistsFile(LOC24); if (!!(LOC25)) goto LA26; addfiletocompile_275863_2528170400(cfile0); } goto LA1; LA26: ; LA1: ; addfiletolink_275872_2528170400(cfilenoext0); } N_NIMCALL(void, writeheader_565149_839829468)(Tcgen531027* m0) { Ropeobj180006* result0; Ropeobj180006* guard0; TY180507 LOC1; TY129506 LOC2; TY180507 LOC3; TY535289 LOC13; TY180507 LOC14; result0 = getcopyright_563665_839829468((*m0).filename); memset((void*)LOC1, 0, sizeof(LOC1)); memset((void*)(&LOC2), 0, sizeof(LOC2)); nossplitFile((*m0).filename, (&LOC2)); LOC1[0] = rope_180277_2381377266(LOC2.Field1); guard0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_695), LOC1, 1); memset((void*)LOC3, 0, sizeof(LOC3)); LOC3[0] = guard0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_696), LOC3, 1); addinttypes_563659_839829468(&result0); generateheaders_562104_839829468(m0); generatethreadlocalstorage_540717_839829468(m0); { Tcfilesection531005 i_565171_839829468; NI res_565197_839829468; i_565171_839829468 = (Tcfilesection531005)0; res_565197_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC7; Ropeobj180006* LOC8; if (!(res_565197_839829468 <= ((NI) 10))) goto LA6; i_565171_839829468 = ((Tcfilesection531005) (res_565197_839829468)); LOC7 = (Ropeobj180006*)0; LOC7 = gensectionstart_532015_2760143328(i_565171_839829468); add_180482_2381377266(&result0, LOC7); add_180482_2381377266(&result0, (*m0).s[(i_565171_839829468)- 0]); LOC8 = (Ropeobj180006*)0; LOC8 = gensectionend_532050_2760143328(i_565171_839829468); add_180482_2381377266(&result0, LOC8); res_565197_839829468 += ((NI) 1); } LA6: ; } } add_180482_2381377266(&result0, (*m0).s[(((Tcfilesection531005) 11))- 0]); { if (!((gglobaloptions_171130_2607990831 &((NU64)1<<((NU)(((Tglobaloption171013) 8))&63U)))!=0)) goto LA11; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_22)); } LA11: ; memset((void*)LOC13, 0, sizeof(LOC13)); addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_697), LOC13, 0); memset((void*)LOC14, 0, sizeof(LOC14)); LOC14[0] = guard0; addf_181205_2381377266(&result0, ((NimStringDesc*) &T839829468_698), LOC14, 1); writerope_180836_2381377266(result0, (*m0).filename, NIM_FALSE); } N_NIMCALL(void, cgenwritemodules_565902_839829468)(void) { { if (!!((generatedheader_534201_839829468 == NIM_NIL))) goto LA3; finishmodule_565420_839829468(generatedheader_534201_839829468); } LA3: ; { while (1) { if (!(((NI) 0) < gforwardedprocscounter_531171_3723162438)) goto LA6; { Tcgen531027* m_565916_839829468; m_565916_839829468 = (Tcgen531027*)0; { NI i_565935_839829468; NI HEX3Atmp_565937_839829468; NI res_565939_839829468; i_565935_839829468 = (NI)0; HEX3Atmp_565937_839829468 = (NI)0; HEX3Atmp_565937_839829468 = (gmodules_531170_3723162438 ? (gmodules_531170_3723162438->Sup.len-1) : -1); res_565939_839829468 = ((NI) 0); { while (1) { if (!(res_565939_839829468 <= HEX3Atmp_565937_839829468)) goto LA10; i_565935_839829468 = res_565939_839829468; { if (!!((gmodules_531170_3723162438->data[i_565935_839829468] == NIM_NIL))) goto LA13; m_565916_839829468 = gmodules_531170_3723162438->data[i_565935_839829468]; { if (!!((*m_565916_839829468).Sup.fromcache)) goto LA17; finishmodule_565420_839829468(m_565916_839829468); } LA17: ; } LA13: ; res_565939_839829468 += ((NI) 1); } LA10: ; } } } } LA6: ; } { Tcgen531027* m_565917_839829468; m_565917_839829468 = (Tcgen531027*)0; { NI i_565946_839829468; NI HEX3Atmp_565948_839829468; NI res_565950_839829468; i_565946_839829468 = (NI)0; HEX3Atmp_565948_839829468 = (NI)0; HEX3Atmp_565948_839829468 = (gmodules_531170_3723162438 ? (gmodules_531170_3723162438->Sup.len-1) : -1); res_565950_839829468 = ((NI) 0); { while (1) { if (!(res_565950_839829468 <= HEX3Atmp_565948_839829468)) goto LA22; i_565946_839829468 = res_565950_839829468; { if (!!((gmodules_531170_3723162438->data[i_565946_839829468] == NIM_NIL))) goto LA25; m_565917_839829468 = gmodules_531170_3723162438->data[i_565946_839829468]; { if (!(*m_565917_839829468).Sup.fromcache) goto LA29; updatecachedmodule_565813_839829468(m_565917_839829468); } goto LA27; LA29: ; { writemodule_565637_839829468(m_565917_839829468, NIM_TRUE); } LA27: ; } LA25: ; res_565950_839829468 += ((NI) 1); } LA22: ; } } } writemapping_276789_2528170400(gmapping_531152_3723162438); { if (!!((generatedheader_534201_839829468 == NIM_NIL))) goto LA34; writeheader_565149_839829468(generatedheader_534201_839829468); } LA34: ; } N_NIMCALL(void, nullify_564833_839829468)(Ropeobj180006** arr0) { { Tcfilesection531005 i_564848_839829468; NI res_564853_839829468; i_564848_839829468 = (Tcfilesection531005)0; res_564853_839829468 = ((NI) 0); { while (1) { if (!(res_564853_839829468 <= ((NI) 17))) goto LA3; i_564848_839829468 = ((Tcfilesection531005) (res_564853_839829468)); unsureAsgnRef((void**) (&arr0[(i_564848_839829468)- 0]), NIM_NIL); res_564853_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, nullify_564858_839829468)(Ropeobj180006** arr0) { { NIM_CHAR i_565014_839829468; NI res_565019_839829468; i_565014_839829468 = (NIM_CHAR)0; res_565019_839829468 = ((NI) 48); { while (1) { if (!(res_565019_839829468 <= ((NI) 57))) goto LA3; i_565014_839829468 = ((NIM_CHAR) (res_565019_839829468)); unsureAsgnRef((void**) (&arr0[(((NU8)(i_565014_839829468)))- 48]), NIM_NIL); res_565019_839829468 += ((NI) 1); } LA3: ; } } } N_NIMCALL(void, resetmodule_564763_839829468)(Tcgen531027* m0) { initlinkedlist_148031_3771138726((&(*m0).headerfiles)); initintset_270885_2627731572((&(*m0).declaredprotos)); initidtable_298019_850551059((&(*m0).forwtypecache)); asgnRef((void**) (&(*m0).initproc), newproc_531206_3723162438(NIM_NIL, m0)); (*(*m0).initproc).options = initprocoptions_564635_839829468(m0); asgnRef((void**) (&(*m0).preinitproc), newpreinitproc_564625_839829468(m0)); asgnRef((void**) (&(*m0).postinitproc), newpostinitproc_564630_839829468(m0)); initnodetable_298085_850551059((&(*m0).datacache)); if ((*m0).typestack) nimGCunrefNoCycle((*m0).typestack); (*m0).typestack = (Ttypeseq294836*) newSeqRC1((&NTI294836), 0); if ((*m0).forwardedprocs) nimGCunrefNoCycle((*m0).forwardedprocs); (*m0).forwardedprocs = (Tsymseq294804*) newSeqRC1((&NTI294804), 0); asgnRefNoCycle((void**) (&(*m0).typenodesname), gettempname_535598_839829468(m0)); asgnRefNoCycle((void**) (&(*m0).nimtypesname), gettempname_535598_839829468(m0)); { if (!(((*(*m0).module).flags &(1U<<((NU)(((Tsymflag294184) 13))&31U)))!=0)) goto LA3; (*m0).flags |= ((NU8)1)<<((((Codegenflag531025) 0))%(sizeof(NU8)*8)); } goto LA1; LA3: ; { (*m0).flags &= ~(((NU8)1) << ((((Codegenflag531025) 0)) % (sizeof(NU8)*8))); } LA1: ; nullify_564833_839829468((*m0).s); (*m0).typenodes = ((NI) 0); (*m0).nimtypes = ((NI) 0); nullify_564858_839829468((*m0).extensionloaders); (*m0).Sup.fromcache = NIM_TRUE; } N_NIMCALL(void, resetcgenmodules_565024_839829468)(void) { { Tcgen531027* m_565026_839829468; m_565026_839829468 = (Tcgen531027*)0; { NI i_565031_839829468; NI HEX3Atmp_565033_839829468; NI res_565035_839829468; i_565031_839829468 = (NI)0; HEX3Atmp_565033_839829468 = (NI)0; HEX3Atmp_565033_839829468 = (gmodules_531170_3723162438 ? (gmodules_531170_3723162438->Sup.len-1) : -1); res_565035_839829468 = ((NI) 0); { while (1) { if (!(res_565035_839829468 <= HEX3Atmp_565033_839829468)) goto LA4; i_565031_839829468 = res_565035_839829468; { if (!!((gmodules_531170_3723162438->data[i_565031_839829468] == NIM_NIL))) goto LA7; m_565026_839829468 = gmodules_531170_3723162438->data[i_565031_839829468]; resetmodule_564763_839829468(m_565026_839829468); } LA7: ; res_565035_839829468 += ((NI) 1); } LA4: ; } } } } NIM_EXTERNC N_NOINLINE(void, compiler_cgenInit000)(void) { nimRegisterGlobalMarker(T839829468_2); nimRegisterGlobalMarker(T839829468_3); nimRegisterGlobalMarker(T839829468_5); nimRegisterGlobalMarker(T839829468_6); nimRegisterGlobalMarker(T839829468_7); nimRegisterGlobalMarker(T839829468_8); asgnRefNoCycle((void**) (&indent_534655_839829468), rope_180277_2381377266(((NimStringDesc*) &T839829468_4))); if (nimtvdeps_540674_839829468) nimGCunrefNoCycle(nimtvdeps_540674_839829468); nimtvdeps_540674_839829468 = (Ttypeseq294836*) newSeqRC1((&NTI294836), 0); chckNil((void*)(&nimtvdeclared_540675_839829468)); genericReset((void*)(&nimtvdeclared_540675_839829468), (&NTI270030)); initintset_270885_2627731572((&nimtvdeclared_540675_839829468)); breakpointid_550860_839829468 = ((NI) 0); } NIM_EXTERNC N_NOINLINE(void, compiler_cgenDatInit000)(void) { }
GB_binop__bset_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bset_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__bset_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bset_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__bset_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bset_uint64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bset_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bset_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bset_uint64) // C=scalar+B GB (_bind1st__bset_uint64) // C=scalar+B' GB (_bind1st_tran__bset_uint64) // C=A+scalar GB (_bind2nd__bset_uint64) // C=A'+scalar GB (_bind2nd_tran__bset_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = GB_BITSET (aij, bij, uint64_t, 64) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITSET (x, y, uint64_t, 64) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BSET || GxB_NO_UINT64 || GxB_NO_BSET_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bset_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bset_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bset_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bset_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bset_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bset_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bset_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bset_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bset_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITSET (x, bij, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bset_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITSET (aij, y, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITSET (x, aij, uint64_t, 64) ; \ } GrB_Info GB (_bind1st_tran__bset_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITSET (aij, y, uint64_t, 64) ; \ } GrB_Info GB (_bind2nd_tran__bset_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
rmat_generator.h
// Adapted from the stinger project <https://github.com/stingergraph/stinger> rmat.c #include <cassert> #include <cinttypes> #include <random> #include "prng_engine.hpp" /* * RMAT edge generator * Implements discard() to skip ahead in the random stream in constant time */ class rmat_edge_generator { private: /* * RANDOM NUMBER GENERATION */ // Generates uniformly distributed uint32_t's // Implements discard() in constant time typedef sitmo::prng_engine prng_engine; //typedef NotRandomEngine prng_engine; prng_engine rng_engine; // Converts values from the rng_engine into double type std::uniform_real_distribution<double> rng_distribution; // Helper function to get a number from the distribution double rng() { return rng_distribution(rng_engine); } /* Stores the number of times std::uniform_real_distribution<double> will * call the generator for each number generated */ size_t k; size_t getk() const { /* * From http://en.cppreference.com/w/cpp/numeric/random/generate_canonical * To generate enough entropy, generate_canonical() will call the generator g() exactly k times, * where k = max(1, ceil(b / log2(R))) * and b = std::min<std::size_t>(bits, std::numeric_limits<RealType>::digits) * and R = g.max() - g.min() + 1. * * In our case, * bits = std::numeric_limits<prng_engine::result_type>::digits * and RealType = double * and __urng = prng_engine */ typedef double _RealType; size_t __bits = std::numeric_limits<_RealType>::digits; const prng_engine& __urng = rng_engine; /* * Remaining code copied from std::generate_canonical(), defined in bits/random.tcc * Even if that implementation changes, the equation should still be the same */ const size_t __b = std::min(static_cast<size_t>(std::numeric_limits<_RealType>::digits), __bits); const long double __r = static_cast<long double>(__urng.max()) - static_cast<long double>(__urng.min()) + 1.0L; const size_t __log2r = std::log(__r) / std::log(2.0L); size_t __k = std::max<size_t>(1UL, (__b + __log2r - 1UL) / __log2r); return __k; } /* * RMAT PARAMETERS */ // log2(num_vertices) int64_t SCALE; // RMAT parameters double a, b, c, d; public: rmat_edge_generator(int64_t nv, double a, double b, double c, double d, uint32_t seed=0) : rng_engine(seed) , rng_distribution(0, 1) , k(getk()) , SCALE(0), a(a), b(b), c(c), d(d) { while (nv >>= 1) { ++SCALE; } } // Skips past the next n randomly generated edges void discard(uint64_t n) { // The loop in next_edge iterates SCALE-1 times, using 5 random numbers in each iteration // The final iteration before the break uses one more random number n *= 5 * (SCALE-1) + 1; // std::uniform_real_distribution<double> calls the generator multiple times to get enough entropy n *= k; rng_engine.discard(n); } void next_edge(int64_t *src, int64_t *dst) { double A = a; double B = b; double C = c; double D = d; int64_t i = 0, j = 0; int64_t bit = ((int64_t) 1) << (SCALE - 1); while (1) { const double r = rng(); if (r > A) { /* outside quadrant 1 */ if (r <= A + B) /* in quadrant 2 */ j |= bit; else if (r <= A + B + C) /* in quadrant 3 */ i |= bit; else { /* in quadrant 4 */ j |= bit; i |= bit; } } if (1 == bit) break; /* Assuming R is in (0, 1), 0.95 + 0.1 * R is in (0.95, 1.05). So the new probabilities are *not* the old +/- 10% but instead the old +/- 5%. */ A *= (9.5 + rng()) / 10; B *= (9.5 + rng()) / 10; C *= (9.5 + rng()) / 10; D *= (9.5 + rng()) / 10; /* Used 5 random numbers. */ { const double norm = 1.0 / (A + B + C + D); A *= norm; B *= norm; C *= norm; } /* So long as +/- are monotonic, ensure a+b+c+d <= 1.0 */ D = 1.0 - (A + B + C); bit >>= 1; } /* Iterates SCALE times. */ *src = i; *dst = j; } }; // Fill up an array with randomly generated edges template<class Iterator> void rmat_fill(rmat_edge_generator& generator, Iterator edges_begin, Iterator edges_end) { using Edge = typename std::iterator_traits<Iterator>::value_type; // Make a local copy of the edge generator rmat_edge_generator local_rng = generator; // Keeps track of this thread's position in the random number stream relative to the loop index int64_t pos = 0; const int64_t num_edges = std::distance(edges_begin, edges_end); // Generate edges in parallel, while maintaining RNG state as if we did it serially // Mark the RNG with firstprivate so each thread gets a copy of the inital state // Also mark the RNG with lastprivate so the master thread gets the state after the last iteration #pragma omp parallel for \ firstprivate(local_rng) lastprivate(local_rng) \ firstprivate(pos) \ schedule(static) for (int64_t i = 0; i < num_edges; ++i) { // Assuming we will always execute loop iterations in order (we can't jump backwards) assert(pos <= i); // Advance RNG whenever we skip ahead in the iteration space if (pos < i) { uint64_t skip_distance = static_cast<uint64_t>(i - pos); local_rng.discard(skip_distance); } // Generate the next random edge Edge& e = edges_begin[i]; local_rng.next_edge(&e.src, &e.dst); // Remember position, in case OpenMP jumps through the iteration space pos = i+1; } // Go back through the list and regenerate self-edges // This step is serial, since we don't know how many times each edge has to be // re-rolled before we get a non-self-edge for (int64_t i = 0; i < num_edges; ++i) { Edge& e = edges_begin[i]; while (e.src == e.dst) { local_rng.next_edge(&e.src, &e.dst); } } // Copy final RNG state back to caller generator = local_rng; }
5-1.c
#include <omp.h> #include <stdio.h> int main() { int w = 10; #pragma omp parallel num_threads(2) #pragma omp for private(w) for (int i = 0; i < 100; i++) { int id = omp_get_thread_num(); printf("T%d:ai%d w=%d\n", id, i, w++); } printf("W=%d\n", w); }
loops_test.c
#include <stdio.h> #include <math.h> #include <malloc.h> #include <string.h> #define N 729 #define reps 1000 #include <omp.h> double a[N][N], b[N][N], c[N]; int jmax[N]; void init1(void); void init2(void); void runloop(int); void loop1chunk(int, int); void loop2chunk(int, int); void valid1(void); void valid2(void); int main(int argc, char *argv[]) { double start1,start2,end1,end2; int r; init1(); start1 = omp_get_wtime(); for (r=0; r<reps; r++){ runloop(1); } end1 = omp_get_wtime(); valid1(); printf("Total time for %d reps of loop 1 = %f\n",reps, (float)(end1-start1)); init2(); start2 = omp_get_wtime(); for (r=0; r<reps; r++){ runloop(2); } end2 = omp_get_wtime(); valid2(); printf("Total time for %d reps of loop 2 = %f\n",reps, (float)(end2-start2)); } void init1(void){ int i,j; for (i=0; i<N; i++){ for (j=0; j<N; j++){ a[i][j] = 0.0; b[i][j] = 3.142*(i+j); } } } void init2(void){ int i,j, expr; for (i=0; i<N; i++){ expr = i%( 3*(i/30) + 1); if ( expr == 0) { jmax[i] = N; } else { jmax[i] = 1; } c[i] = 0.0; } for (i=0; i<N; i++){ for (j=0; j<N; j++){ b[i][j] = (double) (i*j+1) / (double) (N*N); } } } ////////////////////////////////////////////////////////////////////// ///////////// New structure's defination ///////////////////////////// typedef struct _TopList { int thread_num; int avail_size; } TopList ; ////////////////////////////////////////////////////////////////////// ///////////// New functions's defination ///////////////////////////// //Update the available size of the thread in Top List, while reordering the whole list void updatetoplist(TopList *plist , int list_len , int t_num , int avail_size); //Get a piece of work from a specific thread's local trunk int gettrunk(int (*pavail)[2] , TopList *plist , int t_num , int t_size , int *plow , int *phigh); //Assign a new trunk to a specific thread int dispatchwork(int (*pavail)[2] , omp_lock_t *plock , TopList *plist , \ int t_num , int t_size , int *plow , int *phigh); ////////////////////////////////////////////////////////////////////// ///////////// New version of runloop function //////////////////////// void runloop(int loopid) { //Shared values among threads int (*pavail)[2]; //The boundary value of each thread's local trunk TopList *plist; //The ordered list of threads number by their available trunk size omp_lock_t top_lock; //Lock for serialize the work assignment actions // printf("***********LOOP BEGIN*********************\n"); #pragma omp parallel default(none) shared(loopid,pavail,plist,top_lock) { int myid = omp_get_thread_num(); int nthreads = omp_get_num_threads(); // printf("INIT:T_ID-%d TOTAL-%d\n",myid,nthreads); // int ipt = (int) ceil((double)N/(double)nthreads); // int lo = myid*ipt; // int hi = (myid+1)*ipt; // if (hi > N) hi = N; #pragma omp single { //Apply the space to store the trunk's boundary for available loops pavail = (int(*)[2])malloc( sizeof(int)*2*nthreads ); int block_size = N /nthreads ; //Set the initial trunk bundary for each thread and init the locks. for (int i = 0; i < nthreads; i++) { pavail[i][0] = i * block_size; pavail[i][1] = (i+1) * block_size; if ( N - (i+1) * block_size < block_size ) pavail[i][1] = N; } //Initialize the top list and lock omp_init_lock(&top_lock) ; plist = (TopList *)malloc(sizeof(TopList)*nthreads); memset(plist,-1,sizeof(TopList)*nthreads); } int result = 1; int lo, hi; while ( dispatchwork(pavail,&top_lock,plist,myid,nthreads,&lo,&hi) ) { printf("CALC%d:T_ID-%d LOW:%d HIGH:%d \n",loopid,myid,lo,hi-1); switch (loopid) { case 1: loop1chunk(lo,hi); break; case 2: loop2chunk(lo,hi); break; } } } } void loop1chunk(int lo, int hi) { int i,j; for (i=lo; i<hi; i++){ for (j=N-1; j>i; j--){ a[i][j] += cos(b[i][j]); } } } void loop2chunk(int lo, int hi) { int i,j,k; double rN2; rN2 = 1.0 / (double) (N*N); for (i=lo; i<hi; i++){ for (j=0; j < jmax[i]; j++){ for (k=0; k<j; k++){ c[i] += (k+1) * log (b[i][j]) * rN2; } } } } void valid1(void) { int i,j; double suma; suma= 0.0; for (i=0; i<N; i++){ for (j=0; j<N; j++){ suma += a[i][j]; } } printf("Loop 1 check: Sum of a is %lf\n", suma); } void valid2(void) { int i; double sumc; sumc= 0.0; for (i=0; i<N; i++){ sumc += c[i]; } printf("Loop 2 check: Sum of c is %f\n", sumc); } ///////////////////////////////////////////////////////////////////// /////////////New functions developed in this coursework////////////// //Update the available size of the thread in Top List, while reordering the whole list void updatetoplist(TopList *plist , int list_len , int t_num , int avail_size) { int origin_num = t_num; TopList tp_swap,tp_cur; tp_cur.thread_num = t_num; tp_cur.avail_size = avail_size; int iter_mode = 0; for (int i=0; i<list_len; i++) { if (iter_mode == 0) { if (plist[i].thread_num == -1) { plist[i] = tp_cur; break; } else if (plist[i].thread_num == origin_num) { plist[i] = tp_cur; iter_mode = 1; } else if (plist[i].avail_size < tp_cur.avail_size ) { tp_swap = plist[i] ; plist[i] = tp_cur ; tp_cur = tp_swap ; } } else if (iter_mode == 1) { if (plist[i].thread_num == -1) break; else if (plist[i].avail_size > plist[i-1].avail_size) { tp_swap = plist[i] ; plist[i] = plist[i-1]; plist[i-1] = tp_swap; } else break; } } } //Get a piece of work from a specific thread's local trunk int gettrunk(int (*pavail)[2] , TopList *plist , int t_num , int t_size , int *plow , int *phigh) { int get_size = 0; int avail_size = pavail[t_num][1] - pavail[t_num][0]; if ( avail_size > 0 ) { *plow = pavail[t_num][0]; get_size = avail_size / t_size; if (get_size == 0 ) get_size = 1; *phigh = *plow + get_size; pavail[t_num][0] += get_size; avail_size = pavail[t_num][1] - pavail[t_num][0]; updatetoplist(plist,t_size,t_num,avail_size); return 1; } else return 0; } //Assign a new trunk to a specific thread int dispatchwork(int (*pavail)[2] , omp_lock_t *plock , TopList *plist , \ int t_num , int t_size , int *plow , int *phigh) { // printf("DISPA:T_ID-%d LOW-%d HIGH-%d LOW-%d HIGH-%d LIST-%d AVAIL-%d\n",t_num,pavail[t_num][0],pavail[t_num][1],pavail[t_size-1][0],pavail[t_size-1][1],plist[0].thread_num,plist[0].avail_size); int result = 1; omp_set_lock(plock); if (gettrunk(pavail,plist,t_num,t_size,plow,phigh) == 0) { if (plist[0].avail_size > 0) { if (gettrunk(pavail,plist,plist[0].thread_num,t_size,plow,phigh) == 0) result = 0; } else result = 0; } omp_unset_lock(plock); return result ; }
jacobi.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <math.h> // just for debugging void printMatrix(double **matrix, int dim){ int i, j; for (i = 0; i < dim; i++){ for (j = 0; j < dim; j++){ printf("%.8lf ", matrix[i][j]); // print each row } printf("\n"); // linebreak for new row } printf("\n"); return; } // just for debugging void printVector(double *vector, int dim){ int i; printf("\n"); for (i = 0; i < dim; i++){ printf("%.8lf \n", vector[i]); } printf("\n"); } int main(void){ omp_set_dynamic(0); omp_set_num_threads(4); int dim = 17000; int i, j, k, exp; double norm, temp; double **A, **DLU; double *b, *Dinv_b, *u, *u_new, *result, *DLU_times_u, *residual; double start_time, end_time, time_matrices, time_iterations; // start timer start_time = omp_get_wtime(); printf("Setting up matrices and vectors..."); fflush(stdout); // otherwise printf to buffer, since there is no \n // creating matrices A = (double **)malloc(dim * sizeof(double*)); DLU = (double **)malloc(dim * sizeof(double*)); // -Dinv*(L+U) for (i = 0; i < dim; i++){ A[i] = (double *)malloc(dim * sizeof(double)); DLU[i] = (double *)malloc(dim * sizeof(double)); } // coefficient matrix A #pragma omp parallel for collapse(2) // collapsing results in speedup for (i = 0; i < dim; i++){ for (j = 0; j < dim; j++){ if (i == j){ A[i][j] = 1; } else { exp = - 2 * fabs(i - j); A[i][j] = -pow(2, exp); } } } // -Dinv*(L+U) #pragma omp parallel for collapse(2) // collapsing results in speedup for (i = 0; i < dim; i++){ for (j = 0; j < dim; j++){ if (i == j){ DLU[i][j] = 0; } else { exp = - 2 * fabs(i - j); DLU[i][j] = pow(2, exp); } } } // just for debugging //printf("\nA \n"); //printMatrix(A, dim); //printf("DLU \n"); //printMatrix(DLU, dim); // create vectors b = malloc(dim * sizeof(double)); // RHS Dinv_b = malloc(dim * sizeof(double)); // Dinv*b u = malloc(dim * sizeof(double)); // u(n) ; initial guess DLU_times_u = malloc(dim * sizeof(double)); residual = malloc(dim * sizeof(double)); // define vectors #pragma omp parallel for // small speedup for (i = 0; i < dim; i++){ u[i] = 0; // initial guess b[i] = 1; // rhs residual[i] = 0; // zeros, needed for addition on convergence check Dinv_b[i] = 1; // Dinv*b -> constant } time_matrices = omp_get_wtime(); printf("done (%.2lfs)\n", time_matrices - start_time); printf("Starting Jacobi iterations..."); fflush(stdout); // iterations for (i = 0; i < 200000; i++){ // execution of formula for (j = 0; j < dim; j++){ #pragma omp parallel for reduction(+:DLU_times_u[j]) for (k = 0; k < dim; k++){ DLU_times_u[j] += DLU[j][k] * u[k]; // Dinv*(L+U)*u } u[j] = DLU_times_u[j] + Dinv_b[j]; // Dinv*(L+U)*u + Dinv*b } // checking for convergence with norm of residual vector r = b - A*u for (j = 0; j < dim; j++){ residual[j] += b[j]; #pragma omp parallel for reduction(+:residual[j]) for (k = 0; k < dim; k++){ residual[j] -= A[j][k] * u[k]; } } norm = 0.0; #pragma omp parallel for reduction(+:norm) for (j = 0; j < dim; j++){ temp = residual[j]; // small speedup norm += temp*temp; } norm = sqrt(norm); if (norm < 0.001){ time_iterations = omp_get_wtime(); printf("done (%.2lfs)\n\n", time_iterations - time_matrices); printf("Finished after %d iterations.\n(Residual norm: %f)\n\n", i, norm); break; } else { // exit if program takes too long if (i > 100){ printf("\n\nHighest number of iterations is reached. Aborting...\n"); exit(0); } // resetting vector, parallel->no speedup for (j = 0; j < dim; j++){ DLU_times_u[j] = 0; residual[j] = 0; } } } // print result //printf("result:"); //printVector(u, dim); //memory deallocation for (2D) arrays for (i = 0; i < dim; i++){ free(A[i]); free(DLU[i]); } free(A); free(DLU); free(Dinv_b); free(residual); free(b); free(u); // end timer end_time = omp_get_wtime(); printf("Total execution time: %.2lfs\n", end_time - start_time); return 0; } /* compiled with: gcc jacobi.c -fopenmp -o jacobi.exe -lm -O3 example output: Setting up matrices and vectors...done (12.79s) Starting Jacobi iterations...done (6.47s) Finished after 16 iterations. (Residual norm: 0.000994) Total execution time: 19.46 notes: - with dim = 20000, memory became the limiting factor on my machine - therefore: dim = 17000 ------------------------------------------------------------------------------- some old functions... void matMult(double **matrix1, double **matrix2, double **result, int dim){ int i, j, k; for (i = 0; i < dim; i++){ // iterate over rows of first matrix for (j = 0; j < dim; j++){ // iterate over columns of second matrix result[i][j] = 0; // create zero matrix for (k = 0; k < dim; k++){ // iterate over columns of matrix1 and rows of matrix2, respectively result[i][j] += matrix1[i][k] * matrix2[k][j]; } } } return; } void matAdd(double **matrix1, double **matrix2, double **result, int dim){ int i, j; for (i = 0; i < dim; i++){ // iterate over rows of matrix for (j = 0; j < dim; j++){ // iterate over columns of matrix result[i][j] = matrix1[i][j] + matrix2[i][j]; } } return; } void matVecMult(double **matrix, double *vector, double *result, int dim){ int i, j; for (i = 0; i < dim; i++){ // iterate over rows of matrix for (j = 0; j < dim; j++){ // iterate over columns of matrix result[i] += matrix[i][j] * vector[j]; } } return; } */
yescrypt-opt.c
/*- * Copyright 2009 Colin Percival * Copyright 2013,2014 Alexander Peslyak * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file was originally written by Colin Percival as part of the Tarsnap * online backup system. */ #ifdef __i386__ #warning "This implementation does not use SIMD, and thus it runs a lot slower than the SIMD-enabled implementation. Enable at least SSE2 in the C compiler and use yescrypt-best.c instead unless you're building this SIMD-less implementation on purpose (portability to older CPUs or testing)." #elif defined(__x86_64__) #warning "This implementation does not use SIMD, and thus it runs a lot slower than the SIMD-enabled implementation. Use yescrypt-best.c instead unless you're building this SIMD-less implementation on purpose (for testing only)." #endif #include <errno.h> #include <stdint.h> #include <stdlib.h> #include "../sha256.h" #include "yescrypt-platform.c" static inline void blkcpy(uint64_t * dest, const uint64_t * src, size_t count) { do { *dest++ = *src++; *dest++ = *src++; *dest++ = *src++; *dest++ = *src++; } while (count -= 4); } static inline void blkxor(uint64_t * dest, const uint64_t * src, size_t count) { do { *dest++ ^= *src++; *dest++ ^= *src++; *dest++ ^= *src++; *dest++ ^= *src++; } while (count -= 4); } typedef union { uint32_t w[16]; uint64_t d[8]; } salsa20_blk_t; static inline void salsa20_simd_shuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout) { #define COMBINE(out, in1, in2) \ Bout->d[out] = Bin->w[in1 * 2] | ((uint64_t)Bin->w[in2 * 2 + 1] << 32); COMBINE(0, 0, 2) COMBINE(1, 5, 7) COMBINE(2, 2, 4) COMBINE(3, 7, 1) COMBINE(4, 4, 6) COMBINE(5, 1, 3) COMBINE(6, 6, 0) COMBINE(7, 3, 5) #undef COMBINE } static inline void salsa20_simd_unshuffle(const salsa20_blk_t * Bin, salsa20_blk_t * Bout) { #define COMBINE(out, in1, in2) \ Bout->w[out * 2] = Bin->d[in1]; \ Bout->w[out * 2 + 1] = Bin->d[in2] >> 32; COMBINE(0, 0, 6) COMBINE(1, 5, 3) COMBINE(2, 2, 0) COMBINE(3, 7, 5) COMBINE(4, 4, 2) COMBINE(5, 1, 7) COMBINE(6, 6, 4) COMBINE(7, 3, 1) #undef COMBINE } /** * salsa20_8(B): * Apply the salsa20/8 core to the provided block. */ static void salsa20_8(uint64_t B[8]) { size_t i; salsa20_blk_t X; #define x X.w salsa20_simd_unshuffle((const salsa20_blk_t *)B, &X); for (i = 0; i < 8; i += 2) { #define R(a,b) (((a) << (b)) | ((a) >> (32 - (b)))) /* Operate on columns */ x[ 4] ^= R(x[ 0]+x[12], 7); x[ 8] ^= R(x[ 4]+x[ 0], 9); x[12] ^= R(x[ 8]+x[ 4],13); x[ 0] ^= R(x[12]+x[ 8],18); x[ 9] ^= R(x[ 5]+x[ 1], 7); x[13] ^= R(x[ 9]+x[ 5], 9); x[ 1] ^= R(x[13]+x[ 9],13); x[ 5] ^= R(x[ 1]+x[13],18); x[14] ^= R(x[10]+x[ 6], 7); x[ 2] ^= R(x[14]+x[10], 9); x[ 6] ^= R(x[ 2]+x[14],13); x[10] ^= R(x[ 6]+x[ 2],18); x[ 3] ^= R(x[15]+x[11], 7); x[ 7] ^= R(x[ 3]+x[15], 9); x[11] ^= R(x[ 7]+x[ 3],13); x[15] ^= R(x[11]+x[ 7],18); /* Operate on rows */ x[ 1] ^= R(x[ 0]+x[ 3], 7); x[ 2] ^= R(x[ 1]+x[ 0], 9); x[ 3] ^= R(x[ 2]+x[ 1],13); x[ 0] ^= R(x[ 3]+x[ 2],18); x[ 6] ^= R(x[ 5]+x[ 4], 7); x[ 7] ^= R(x[ 6]+x[ 5], 9); x[ 4] ^= R(x[ 7]+x[ 6],13); x[ 5] ^= R(x[ 4]+x[ 7],18); x[11] ^= R(x[10]+x[ 9], 7); x[ 8] ^= R(x[11]+x[10], 9); x[ 9] ^= R(x[ 8]+x[11],13); x[10] ^= R(x[ 9]+x[ 8],18); x[12] ^= R(x[15]+x[14], 7); x[13] ^= R(x[12]+x[15], 9); x[14] ^= R(x[13]+x[12],13); x[15] ^= R(x[14]+x[13],18); #undef R } #undef x { salsa20_blk_t Y; salsa20_simd_shuffle(&X, &Y); for (i = 0; i < 16; i += 4) { ((salsa20_blk_t *)B)->w[i] += Y.w[i]; ((salsa20_blk_t *)B)->w[i + 1] += Y.w[i + 1]; ((salsa20_blk_t *)B)->w[i + 2] += Y.w[i + 2]; ((salsa20_blk_t *)B)->w[i + 3] += Y.w[i + 3]; } } } /** * blockmix_salsa8(Bin, Bout, X, r): * Compute Bout = BlockMix_{salsa20/8, r}(Bin). The input Bin must be 128r * bytes in length; the output Bout must also be the same size. The * temporary space X must be 64 bytes. */ static void blockmix_salsa8(const uint64_t * Bin, uint64_t * Bout, uint64_t * X, size_t r) { size_t i; /* 1: X <-- B_{2r - 1} */ blkcpy(X, &Bin[(2 * r - 1) * 8], 8); /* 2: for i = 0 to 2r - 1 do */ for (i = 0; i < 2 * r; i += 2) { /* 3: X <-- H(X \xor B_i) */ blkxor(X, &Bin[i * 8], 8); salsa20_8(X); /* 4: Y_i <-- X */ /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ blkcpy(&Bout[i * 4], X, 8); /* 3: X <-- H(X \xor B_i) */ blkxor(X, &Bin[i * 8 + 8], 8); salsa20_8(X); /* 4: Y_i <-- X */ /* 6: B' <-- (Y_0, Y_2 ... Y_{2r-2}, Y_1, Y_3 ... Y_{2r-1}) */ blkcpy(&Bout[i * 4 + r * 8], X, 8); } } /* These are tunable */ #define S_BITS 8 #define S_SIMD 2 #define S_P 4 #define S_ROUNDS 6 /* Number of S-boxes. Not tunable, hard-coded in a few places. */ #define S_N 2 /* Derived values. Not tunable on their own. */ #define S_SIZE1 (1 << S_BITS) #define S_MASK ((S_SIZE1 - 1) * S_SIMD * 8) #define S_MASK2 (((uint64_t)S_MASK << 32) | S_MASK) #define S_SIZE_ALL (S_N * S_SIZE1 * S_SIMD) #define S_P_SIZE (S_P * S_SIMD) #define S_MIN_R ((S_P * S_SIMD + 15) / 16) /** * pwxform(B): * Transform the provided block using the provided S-boxes. */ static void block_pwxform(uint64_t * B, const uint64_t * S) { uint64_t (*X)[S_SIMD] = (uint64_t (*)[S_SIMD])B; const uint8_t *S0 = (const uint8_t *)S; const uint8_t *S1 = (const uint8_t *)(S + S_SIZE1 * S_SIMD); size_t i, j; #if S_SIMD > 2 size_t k; #endif for (j = 0; j < S_P; j++) { uint64_t *Xj = X[j]; uint64_t x0 = Xj[0]; #if S_SIMD > 1 uint64_t x1 = Xj[1]; #endif for (i = 0; i < S_ROUNDS; i++) { uint64_t x = x0 & S_MASK2; const uint64_t *p0, *p1; p0 = (const uint64_t *)(S0 + (uint32_t)x); p1 = (const uint64_t *)(S1 + (x >> 32)); x0 = (uint64_t)(x0 >> 32) * (uint32_t)x0; x0 += p0[0]; x0 ^= p1[0]; #if S_SIMD > 1 x1 = (uint64_t)(x1 >> 32) * (uint32_t)x1; x1 += p0[1]; x1 ^= p1[1]; #endif #if S_SIMD > 2 for (k = 2; k < S_SIMD; k++) { x = Xj[k]; x = (uint64_t)(x >> 32) * (uint32_t)x; x += p0[k]; x ^= p1[k]; Xj[k] = x; } #endif } Xj[0] = x0; #if S_SIMD > 1 Xj[1] = x1; #endif } } /** * blockmix_pwxform(Bin, Bout, S, r): * Compute Bout = BlockMix_pwxform{salsa20/8, S, r}(Bin). The input Bin must * be 128r bytes in length; the output Bout must also be the same size. * * S lacks const qualifier to match blockmix_salsa8()'s prototype, which we * need to refer to both functions via the same function pointers. */ static void blockmix_pwxform(const uint64_t * Bin, uint64_t * Bout, uint64_t * S, size_t r) { size_t r1, r2, i; /* Convert 128-byte blocks to (S_P_SIZE * 64-bit) blocks */ r1 = r * 128 / (S_P_SIZE * 8); /* X <-- B_{r1 - 1} */ blkcpy(Bout, &Bin[(r1 - 1) * S_P_SIZE], S_P_SIZE); /* X <-- X \xor B_i */ blkxor(Bout, Bin, S_P_SIZE); /* X <-- H'(X) */ /* B'_i <-- X */ block_pwxform(Bout, S); /* for i = 0 to r1 - 1 do */ for (i = 1; i < r1; i++) { /* X <-- X \xor B_i */ blkcpy(&Bout[i * S_P_SIZE], &Bout[(i - 1) * S_P_SIZE], S_P_SIZE); blkxor(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE], S_P_SIZE); /* X <-- H'(X) */ /* B'_i <-- X */ block_pwxform(&Bout[i * S_P_SIZE], S); } /* Handle partial blocks */ if (i * S_P_SIZE < r * 16) blkcpy(&Bout[i * S_P_SIZE], &Bin[i * S_P_SIZE], r * 16 - i * S_P_SIZE); i = (r1 - 1) * S_P_SIZE / 8; /* Convert 128-byte blocks to 64-byte blocks */ r2 = r * 2; /* B'_i <-- H(B'_i) */ salsa20_8(&Bout[i * 8]); i++; for (; i < r2; i++) { /* B'_i <-- H(B'_i \xor B'_{i-1}) */ blkxor(&Bout[i * 8], &Bout[(i - 1) * 8], 8); salsa20_8(&Bout[i * 8]); } } /** * integerify(B, r): * Return the result of parsing B_{2r-1} as a little-endian integer. */ static inline uint64_t integerify(const uint64_t * B, size_t r) { /* * Our 64-bit words are in host byte order, and word 6 holds the second 32-bit * word of B_{2r-1} due to SIMD shuffling. The 64-bit value we return is also * in host byte order, as it should be. */ const uint64_t * X = &B[(2 * r - 1) * 8]; uint32_t lo = X[0]; uint32_t hi = X[6] >> 32; return ((uint64_t)hi << 32) + lo; } /** * smix1(B, r, N, flags, V, NROM, shared, XY, S): * Compute first loop of B = SMix_r(B, N). The input B must be 128r bytes in * length; the temporary storage V must be 128rN bytes in length; the temporary * storage XY must be 256r + 64 bytes in length. The value N must be even and * no smaller than 2. */ static void smix1(uint64_t * B, size_t r, uint64_t N, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) = (S ? blockmix_pwxform : blockmix_salsa8); const uint64_t * VROM = shared->shared1.aligned; uint32_t VROM_mask = shared->mask1; size_t s = 16 * r; uint64_t * X = V; uint64_t * Y = &XY[s]; uint64_t * Z = S ? S : &XY[2 * s]; uint64_t n, i, j; size_t k; /* 1: X <-- B */ /* 3: V_i <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8]; for (k = 0; k < 16; k++) tmp->w[k] = le32dec(&src->w[k]); salsa20_simd_shuffle(tmp, dst); } /* 4: X <-- H(X) */ /* 3: V_i <-- X */ blockmix(X, Y, Z, r); blkcpy(&V[s], Y, s); X = XY; if (NROM && (VROM_mask & 1)) { if ((1 & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j = integerify(Y, r) & (NROM - 1); /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } blockmix(Y, X, Z, r); /* 2: for i = 0 to N - 1 do */ for (n = 1, i = 2; i < N; i += 2) { /* 3: V_i <-- X */ blkcpy(&V[i * s], X, s); if ((i & (i - 1)) == 0) n <<= 1; /* j <-- Wrap(Integerify(X), i) */ j = integerify(X, r) & (n - 1); j += i - n; /* X <-- X \xor V_j */ blkxor(X, &V[j * s], s); /* 4: X <-- H(X) */ blockmix(X, Y, Z, r); /* 3: V_i <-- X */ blkcpy(&V[(i + 1) * s], Y, s); j = integerify(Y, r); if (((i + 1) & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j &= NROM - 1; /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } else { /* j <-- Wrap(Integerify(X), i) */ j &= n - 1; j += i + 1 - n; /* X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); } blockmix(Y, X, Z, r); } } else { yescrypt_flags_t rw = flags & YESCRYPT_RW; /* 4: X <-- H(X) */ blockmix(Y, X, Z, r); /* 2: for i = 0 to N - 1 do */ for (n = 1, i = 2; i < N; i += 2) { /* 3: V_i <-- X */ blkcpy(&V[i * s], X, s); if (rw) { if ((i & (i - 1)) == 0) n <<= 1; /* j <-- Wrap(Integerify(X), i) */ j = integerify(X, r) & (n - 1); j += i - n; /* X <-- X \xor V_j */ blkxor(X, &V[j * s], s); } /* 4: X <-- H(X) */ blockmix(X, Y, Z, r); /* 3: V_i <-- X */ blkcpy(&V[(i + 1) * s], Y, s); if (rw) { /* j <-- Wrap(Integerify(X), i) */ j = integerify(Y, r) & (n - 1); j += (i + 1) - n; /* X <-- X \xor V_j */ blkxor(Y, &V[j * s], s); } /* 4: X <-- H(X) */ blockmix(Y, X, Z, r); } } /* B' <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8]; for (k = 0; k < 16; k++) le32enc(&tmp->w[k], src->w[k]); salsa20_simd_unshuffle(tmp, dst); } } /** * smix2(B, r, N, Nloop, flags, V, NROM, shared, XY, S): * Compute second loop of B = SMix_r(B, N). The input B must be 128r bytes in * length; the temporary storage V must be 128rN bytes in length; the temporary * storage XY must be 256r + 64 bytes in length. The value N must be a * power of 2 greater than 1. The value Nloop must be even. */ static void smix2(uint64_t * B, size_t r, uint64_t N, uint64_t Nloop, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { void (*blockmix)(const uint64_t *, uint64_t *, uint64_t *, size_t) = (S ? blockmix_pwxform : blockmix_salsa8); const uint64_t * VROM = shared->shared1.aligned; uint32_t VROM_mask = shared->mask1 | 1; size_t s = 16 * r; yescrypt_flags_t rw = flags & YESCRYPT_RW; uint64_t * X = XY; uint64_t * Y = &XY[s]; uint64_t * Z = S ? S : &XY[2 * s]; uint64_t i, j; size_t k; if (Nloop == 0) return; /* X <-- B' */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&B[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&X[i * 8]; for (k = 0; k < 16; k++) tmp->w[k] = le32dec(&src->w[k]); salsa20_simd_shuffle(tmp, dst); } if (NROM) { /* 6: for i = 0 to N - 1 do */ for (i = 0; i < Nloop; i += 2) { /* 7: j <-- Integerify(X) mod N */ j = integerify(X, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(X, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], X, s); blockmix(X, Y, Z, r); j = integerify(Y, r); if (((i + 1) & VROM_mask) == 1) { /* j <-- Integerify(X) mod NROM */ j &= NROM - 1; /* X <-- H(X \xor VROM_j) */ blkxor(Y, &VROM[j * s], s); } else { /* 7: j <-- Integerify(X) mod N */ j &= N - 1; /* 8: X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], Y, s); } blockmix(Y, X, Z, r); } } else { /* 6: for i = 0 to N - 1 do */ i = Nloop / 2; do { /* 7: j <-- Integerify(X) mod N */ j = integerify(X, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(X, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], X, s); blockmix(X, Y, Z, r); /* 7: j <-- Integerify(X) mod N */ j = integerify(Y, r) & (N - 1); /* 8: X <-- H(X \xor V_j) */ blkxor(Y, &V[j * s], s); /* V_j <-- Xprev \xor V_j */ if (rw) blkcpy(&V[j * s], Y, s); blockmix(Y, X, Z, r); } while (--i); } /* 10: B' <-- X */ for (i = 0; i < 2 * r; i++) { const salsa20_blk_t *src = (const salsa20_blk_t *)&X[i * 8]; salsa20_blk_t *tmp = (salsa20_blk_t *)Y; salsa20_blk_t *dst = (salsa20_blk_t *)&B[i * 8]; for (k = 0; k < 16; k++) le32enc(&tmp->w[k], src->w[k]); salsa20_simd_unshuffle(tmp, dst); } } /** * p2floor(x): * Largest power of 2 not greater than argument. */ static uint64_t p2floor(uint64_t x) { uint64_t y; while ((y = x & (x - 1))) x = y; return x; } /** * smix(B, r, N, p, t, flags, V, NROM, shared, XY, S): * Compute B = SMix_r(B, N). The input B must be 128rp bytes in length; the * temporary storage V must be 128rN bytes in length; the temporary storage * XY must be 256r+64 or (256r+64)*p bytes in length (the larger size is * required with OpenMP-enabled builds). The value N must be a power of 2 * greater than 1. */ static void smix(uint64_t * B, size_t r, uint64_t N, uint32_t p, uint32_t t, yescrypt_flags_t flags, uint64_t * V, uint64_t NROM, const yescrypt_shared_t * shared, uint64_t * XY, uint64_t * S) { size_t s = 16 * r; uint64_t Nchunk = N / p, Nloop_all, Nloop_rw; uint32_t i; Nloop_all = Nchunk; if (flags & YESCRYPT_RW) { if (t <= 1) { if (t) Nloop_all *= 2; /* 2/3 */ Nloop_all = (Nloop_all + 2) / 3; /* 1/3, round up */ } else { Nloop_all *= t - 1; } } else if (t) { if (t == 1) Nloop_all += (Nloop_all + 1) / 2; /* 1.5, round up */ Nloop_all *= t; } Nloop_rw = 0; if (flags & __YESCRYPT_INIT_SHARED) Nloop_rw = Nloop_all; else if (flags & YESCRYPT_RW) Nloop_rw = Nloop_all / p; Nchunk &= ~(uint64_t)1; /* round down to even */ Nloop_all++; Nloop_all &= ~(uint64_t)1; /* round up to even */ Nloop_rw &= ~(uint64_t)1; /* round down to even */ #ifdef _OPENMP #pragma omp parallel if (p > 1) default(none) private(i) shared(B, r, N, p, flags, V, NROM, shared, XY, S, s, Nchunk, Nloop_all, Nloop_rw) { #pragma omp for #endif for (i = 0; i < p; i++) { uint64_t Vchunk = i * Nchunk; uint64_t * Bp = &B[i * s]; uint64_t * Vp = &V[Vchunk * s]; #ifdef _OPENMP uint64_t * XYp = &XY[i * (2 * s + 8)]; #else uint64_t * XYp = XY; #endif uint64_t Np = (i < p - 1) ? Nchunk : (N - Vchunk); uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S; if (Sp) smix1(Bp, 1, S_SIZE_ALL / 16, flags & ~YESCRYPT_PWXFORM, Sp, NROM, shared, XYp, NULL); if (!(flags & __YESCRYPT_INIT_SHARED_2)) smix1(Bp, r, Np, flags, Vp, NROM, shared, XYp, Sp); smix2(Bp, r, p2floor(Np), Nloop_rw, flags, Vp, NROM, shared, XYp, Sp); } if (Nloop_all > Nloop_rw) { #ifdef _OPENMP #pragma omp for #endif for (i = 0; i < p; i++) { uint64_t * Bp = &B[i * s]; #ifdef _OPENMP uint64_t * XYp = &XY[i * (2 * s + 8)]; #else uint64_t * XYp = XY; #endif uint64_t * Sp = S ? &S[i * S_SIZE_ALL] : S; smix2(Bp, r, N, Nloop_all - Nloop_rw, flags & ~YESCRYPT_RW, V, NROM, shared, XYp, Sp); } } #ifdef _OPENMP } #endif } /** * yescrypt_kdf(shared, local, passwd, passwdlen, salt, saltlen, * N, r, p, t, flags, buf, buflen): * Compute scrypt(passwd[0 .. passwdlen - 1], salt[0 .. saltlen - 1], N, r, * p, buflen), or a revision of scrypt as requested by flags and shared, and * write the result into buf. The parameters r, p, and buflen must satisfy * r * p < 2^30 and buflen <= (2^32 - 1) * 32. The parameter N must be a power * of 2 greater than 1. * * t controls computation time while not affecting peak memory usage. shared * and flags may request special modes as described in yescrypt.h. local is * the thread-local data structure, allowing to preserve and reuse a memory * allocation across calls, thereby reducing its overhead. * * Return 0 on success; or -1 on error. */ int yescrypt_kdf(const yescrypt_shared_t * shared, yescrypt_local_t * local, const uint8_t * passwd, size_t passwdlen, const uint8_t * salt, size_t saltlen, uint64_t N, uint32_t r, uint32_t p, uint32_t t, yescrypt_flags_t flags, uint8_t * buf, size_t buflen) { yescrypt_region_t tmp; uint64_t NROM; size_t B_size, V_size, XY_size, need; uint64_t * B, * V, * XY, * S; uint64_t sha256[4]; /* * YESCRYPT_PARALLEL_SMIX is a no-op at p = 1 for its intended purpose, * so don't let it have side-effects. Without this adjustment, it'd * enable the SHA-256 password pre-hashing and output post-hashing, * because any deviation from classic scrypt implies those. */ if (p == 1) flags &= ~YESCRYPT_PARALLEL_SMIX; /* Sanity-check parameters */ if (flags & ~YESCRYPT_KNOWN_FLAGS) { errno = EINVAL; return -1; } #if SIZE_MAX > UINT32_MAX if (buflen > (((uint64_t)(1) << 32) - 1) * 32) { errno = EFBIG; return -1; } #endif if ((uint64_t)(r) * (uint64_t)(p) >= (1 << 30)) { errno = EFBIG; return -1; } if (((N & (N - 1)) != 0) || (N <= 1) || (r < 1) || (p < 1)) { errno = EINVAL; return -1; } if ((flags & YESCRYPT_PARALLEL_SMIX) && (N / p <= 1)) { errno = EINVAL; return -1; } #if S_MIN_R > 1 if ((flags & YESCRYPT_PWXFORM) && (r < S_MIN_R)) { errno = EINVAL; return -1; } #endif if ((p > SIZE_MAX / ((size_t)256 * r + 64)) || #if SIZE_MAX / 256 <= UINT32_MAX (r > SIZE_MAX / 256) || #endif (N > SIZE_MAX / 128 / r)) { errno = ENOMEM; return -1; } if (N > UINT64_MAX / ((uint64_t)t + 1)) { errno = EFBIG; return -1; } #ifdef _OPENMP if (!(flags & YESCRYPT_PARALLEL_SMIX) && (N > SIZE_MAX / 128 / (r * p))) { errno = ENOMEM; return -1; } #endif if ((flags & YESCRYPT_PWXFORM) && #ifndef _OPENMP (flags & YESCRYPT_PARALLEL_SMIX) && #endif p > SIZE_MAX / (S_SIZE_ALL * sizeof(*S))) { errno = ENOMEM; return -1; } NROM = 0; if (shared->shared1.aligned) { NROM = shared->shared1.aligned_size / ((size_t)128 * r); if (((NROM & (NROM - 1)) != 0) || (NROM <= 1) || !(flags & YESCRYPT_RW)) { errno = EINVAL; return -1; } } /* Allocate memory */ V = NULL; V_size = (size_t)128 * r * N; #ifdef _OPENMP if (!(flags & YESCRYPT_PARALLEL_SMIX)) V_size *= p; #endif need = V_size; if (flags & __YESCRYPT_INIT_SHARED) { if (local->aligned_size < need) { if (local->base || local->aligned || local->base_size || local->aligned_size) { errno = EINVAL; return -1; } if (!alloc_region(local, need)) return -1; } V = (uint64_t *)local->aligned; need = 0; } B_size = (size_t)128 * r * p; need += B_size; if (need < B_size) { errno = ENOMEM; return -1; } XY_size = (size_t)256 * r + 64; #ifdef _OPENMP XY_size *= p; #endif need += XY_size; if (need < XY_size) { errno = ENOMEM; return -1; } if (flags & YESCRYPT_PWXFORM) { size_t S_size = S_SIZE_ALL * sizeof(*S); #ifdef _OPENMP S_size *= p; #else if (flags & YESCRYPT_PARALLEL_SMIX) S_size *= p; #endif need += S_size; if (need < S_size) { errno = ENOMEM; return -1; } } if (flags & __YESCRYPT_INIT_SHARED) { if (!alloc_region(&tmp, need)) return -1; B = (uint64_t *)tmp.aligned; XY = (uint64_t *)((uint8_t *)B + B_size); } else { init_region(&tmp); if (local->aligned_size < need) { if (free_region(local)) return -1; if (!alloc_region(local, need)) return -1; } B = (uint64_t *)local->aligned; V = (uint64_t *)((uint8_t *)B + B_size); XY = (uint64_t *)((uint8_t *)V + V_size); } S = NULL; if (flags & YESCRYPT_PWXFORM) S = (uint64_t *)((uint8_t *)XY + XY_size); if (t || flags) { sha256_ctx ctx; sha256_init(&ctx); sha256_update(&ctx, passwd, passwdlen); sha256_final((uint8_t *)sha256, &ctx); passwd = (uint8_t *)sha256; passwdlen = sizeof(sha256); } /* 1: (B_0 ... B_{p-1}) <-- PBKDF2(P, S, 1, p * MFLen) */ PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, 1, (uint8_t *)B, B_size); if (t || flags) blkcpy(sha256, B, sizeof(sha256) / sizeof(sha256[0])); if (p == 1 || (flags & YESCRYPT_PARALLEL_SMIX)) { smix(B, r, N, p, t, flags, V, NROM, shared, XY, S); } else { uint32_t i; /* 2: for i = 0 to p - 1 do */ #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(B, r, N, p, t, flags, V, NROM, shared, XY, S) #endif for (i = 0; i < p; i++) { /* 3: B_i <-- MF(B_i, N) */ #ifdef _OPENMP smix(&B[(size_t)16 * r * i], r, N, 1, t, flags, &V[(size_t)16 * r * i * N], NROM, shared, &XY[((size_t)32 * r + 8) * i], S ? &S[S_SIZE_ALL * i] : S); #else smix(&B[(size_t)16 * r * i], r, N, 1, t, flags, V, NROM, shared, XY, S); #endif } } /* 5: DK <-- PBKDF2(P, B, 1, dkLen) */ PBKDF2_SHA256(passwd, passwdlen, (uint8_t *)B, B_size, 1, buf, buflen); /* * Except when computing classic scrypt, allow all computation so far * to be performed on the client. The final steps below match those of * SCRAM (RFC 5802), so that an extension of SCRAM (with the steps so * far in place of SCRAM's use of PBKDF2 and with SHA-256 in place of * SCRAM's use of SHA-1) would be usable with yescrypt hashes. */ if ((t || flags) && buflen == sizeof(sha256)) { /* Compute ClientKey */ { hmac_sha256_ctx ctx; hmac_sha256_init(&ctx, buf, buflen); hmac_sha256_update(&ctx, salt, saltlen); hmac_sha256_final((uint8_t *)sha256, &ctx); } /* Compute StoredKey */ { sha256_ctx ctx; sha256_init(&ctx); sha256_update(&ctx, (uint8_t *)sha256, sizeof(sha256)); sha256_final(buf, &ctx); } } if (free_region(&tmp)) return -1; /* Success! */ return 0; }
FiniteElementMesh.h
#pragma once #include <omp.h> #include "AnimatedMesh.h" #include "CGVectorWrapper.h" #include "CGSystemWrapper.h" #include "ConjugateGradient.h" #include <Eigen/Dense> template<class T> struct FiniteElementMesh : public AnimatedMesh<T, 3> { using Base = AnimatedMesh<T, 3>; using Base::m_meshElements; using Base::m_particleX; using Vector2 = typename Base::Vector2; using Matrix22 = Eigen::Matrix< T , 2 , 2>; int m_nFrames; int m_subSteps; T m_frameDt; T m_stepDt; T m_stepEndTime; const T m_density; const T m_mu; const T m_lambda; const T m_rayleighCoefficient; std::vector<T> m_particleMass; std::vector<Vector2> m_particleV; std::vector<Matrix22> m_DmInverse; std::vector<T> m_restVolume; FiniteElementMesh(const T density, const T mu, const T lambda, const T rayleighCoefficient) :m_density(density), m_mu(mu), m_lambda(lambda), m_rayleighCoefficient(rayleighCoefficient) {} void initializeUndeformedConfiguration() { // Initialize rest shape and particle mass (based on constant density) m_particleMass.resize(m_particleX.size(), T()); // Initialize all particle masses to zero for(const auto& element: m_meshElements) { Matrix22 Dm; for(int j = 0; j < 2; j++) Dm.col(j) = m_particleX[element[j+1]]-m_particleX[element[0]]; T restVolume = .5 * Dm.determinant(); if(restVolume < 0) throw std::logic_error("Inverted element"); m_DmInverse.emplace_back(Dm.inverse()); m_restVolume.push_back(restVolume); T elementMass = m_density * restVolume; for(const int v: element) m_particleMass[v] += (1./3.) * elementMass; } } void addElasticForce(std::vector<Vector2>& f) const { #pragma omp parallel for for(int e = 0; e < m_meshElements.size(); e++) { const auto& element = m_meshElements[e]; // Linear Elasticity Matrix22 Ds; for(int j = 0; j < 2; j++) Ds.col(j) = m_particleX[element[j+1]]-m_particleX[element[0]]; Matrix22 F = Ds * m_DmInverse[e]; Matrix22 strain = .5 * (F + F.transpose()) - Matrix22::Identity(); Matrix22 P = 2. * m_mu * strain + m_lambda * strain.trace() * Matrix22::Identity(); Matrix22 H = -m_restVolume[e] * P * m_DmInverse[e].transpose(); #pragma omp critical { for (int j = 0; j < 2; j++) { f[element[j + 1]] += H.col(j); f[element[0]] -= H.col(j); } } } } void addProductWithStiffnessMatrix(std::vector<Vector2>& w, std::vector<Vector2>& f, const T scale) const { #pragma omp parallel for for(int e = 0; e < m_meshElements.size(); e++) { const auto& element = m_meshElements[e]; // Linear Damping Matrix22 Ds_dot; for(int j = 0; j < 2; j++) Ds_dot.col(j) = w[element[j+1]]-w[element[0]]; Matrix22 F_dot = Ds_dot * m_DmInverse[e]; Matrix22 strain_rate = .5 * (F_dot + F_dot.transpose()); Matrix22 P_damping = scale * (2. * m_mu * strain_rate + m_lambda * strain_rate.trace() * Matrix22::Identity()); Matrix22 H_damping = m_restVolume[e] * P_damping * m_DmInverse[e].transpose(); for(int j = 0; j < 2; j++){ f[element[j+1]] += H_damping.col(j); f[element[0]] -= H_damping.col(j); } } } void simulateSubstep() { using FEMType = FiniteElementMesh<T>; const int nParticles = m_particleX.size(); // Save last time step velocities std::vector<Vector2> lastV = m_particleV; // Construct initial guess for next-timestep // Velocities -> Same as last timestep // Positions -> Using Forward Euler for(int p = 0; p < nParticles; p++) m_particleX[p] += m_stepDt * m_particleV[p]; // Overwrite boundary conditions with desired values setBoundaryConditions(); // Solve for everything else using Conjugate Gradients std::vector<Vector2> dx(nParticles, Vector2::Zero()); std::vector<Vector2> rhs(nParticles, Vector2::Zero()); std::vector<Vector2> q(nParticles, Vector2::Zero()); std::vector<Vector2> s(nParticles, Vector2::Zero()); std::vector<Vector2> r(nParticles, Vector2::Zero()); CGVectorWrapper<Vector2> dxWrapper(dx); CGVectorWrapper<Vector2> rhsWrapper(rhs); CGVectorWrapper<Vector2> qWrapper(q); CGVectorWrapper<Vector2> sWrapper(s); CGVectorWrapper<Vector2> rWrapper(r); CGSystemWrapper<Vector2, FEMType> systemWrapper(*this); addElasticForce(rhs); for(int p = 0; p < nParticles; p++) rhs[p] += (m_particleMass[p] / m_stepDt) * (lastV[p] - m_particleV[p]); addProductWithStiffnessMatrix(m_particleV, rhs, -m_rayleighCoefficient); clearConstrainedParticles(rhs); ConjugateGradient<T>::Solve(systemWrapper, dxWrapper, rhsWrapper, qWrapper, sWrapper, rWrapper, 1e-4, 50); // Apply corrections to positions and velocities const T oneOverDt = T(1.) / m_stepDt; for(int p = 0; p < nParticles; p++){ m_particleX[p] += dx[p]; m_particleV[p] += oneOverDt * dx[p]; } } void simulateFrame(const int frame) { m_stepDt = m_frameDt / (T) m_subSteps; for(int step = 1; step <= m_subSteps; step++){ m_stepEndTime = m_frameDt * (T) (frame-1) + m_stepDt * (T) step; simulateSubstep(); } } virtual void clearConstrainedParticles(std::vector<Vector2>& x) {} virtual void setBoundaryConditions() {} };
GB_AxB_dot4_template.c
//------------------------------------------------------------------------------ // GB_AxB_dot4: C+=A'*B via dot products, where C is dense //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // C+=A'*B where C is a dense matrix and computed in-place. The monoid of the // semiring matches the accum operator, and the type of C matches the ztype of // accum. That is, no typecasting can be done with C. // The PAIR operator as the multiplier provides important special cases. // See Template/GB_AxB_dot_cij.c for details. // cij += A(k,i) * B(k,j) #undef GB_DOT_MERGE #define GB_DOT_MERGE \ { \ if (!cij_updated) \ { \ cij_updated = true ; \ GB_GETC (cij, pC) ; \ } \ GB_GETA (aki, Ax, pA) ; /* aki = A(k,i) */ \ GB_GETB (bkj, Bx, pB) ; /* bkj = B(k,j) */ \ GB_MULTADD (cij, aki, bkj) ; /* cij += aki * bkj */ \ GB_DOT_TERMINAL (cij) ; /* break if cij == terminal */ \ pA++ ; \ pB++ ; \ } { //-------------------------------------------------------------------------- // get A, B, and C //-------------------------------------------------------------------------- GB_CTYPE *GB_RESTRICT Cx = (GB_CTYPE *) C->x ; const int64_t cvlen = C->vlen ; const int64_t *GB_RESTRICT Bp = B->p ; const int64_t *GB_RESTRICT Bh = B->h ; const int64_t *GB_RESTRICT Bi = B->i ; const GB_BTYPE *GB_RESTRICT Bx = (GB_BTYPE *) (B_is_pattern ? NULL : B->x) ; const int64_t bvlen = B->vlen ; const int64_t *GB_RESTRICT Ap = A->p ; const int64_t *GB_RESTRICT Ah = A->h ; const int64_t *GB_RESTRICT Ai = A->i ; const GB_ATYPE *GB_RESTRICT Ax = (GB_ATYPE *) (A_is_pattern ? NULL : A->x) ; ASSERT (A->vlen == B->vlen) ; int ntasks = naslice * nbslice ; bool cij_is_terminal ; //-------------------------------------------------------------------------- // C += A'*B //-------------------------------------------------------------------------- int taskid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) for (taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the entries in A and B to compute //---------------------------------------------------------------------- int a_taskid = taskid / nbslice ; int b_taskid = taskid % nbslice ; int64_t akfirst = A_slice [a_taskid] ; int64_t aklast = A_slice [a_taskid+1] ; if (akfirst >= aklast) continue ; int64_t bkfirst = B_slice [b_taskid] ; int64_t bklast = B_slice [b_taskid+1] ; if (bkfirst >= bklast) continue ; //---------------------------------------------------------------------- // C+=A'*B via dot products //---------------------------------------------------------------------- for (int64_t bk = bkfirst ; bk < bklast ; bk++) { //------------------------------------------------------------------ // get B(:,j) //------------------------------------------------------------------ int64_t j = (Bh == NULL) ? bk : Bh [bk] ; int64_t pB_start = Bp [bk] ; int64_t pB_end = Bp [bk+1] ; int64_t pC_start = j * cvlen ; int64_t bjnz = pB_end - pB_start ; if (bjnz == 0) continue ; if (bjnz == bvlen) { //-------------------------------------------------------------- // B(:,j) is dense //-------------------------------------------------------------- for (int64_t ak = akfirst ; ak < aklast ; ak++) { //---------------------------------------------------------- // get A(:,i) //---------------------------------------------------------- int64_t i = (Ah == NULL) ? ak : Ah [ak] ; int64_t pA = Ap [ak] ; int64_t pA_end = Ap [ak+1] ; int64_t ainz = pA_end - pA ; if (ainz == 0) continue ; GB_CIJ_DECLARE (cij) ; // declare the cij scalar int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] int64_t pB = pB_start ; GB_GETC (cij, pC) ; // cij = Cx [pC] //---------------------------------------------------------- // special cases for the PAIR multiplier //---------------------------------------------------------- // Since B(:,j) is dense, C(i,j) += A(:,i)'*B(:,j) is // trivial to compute with the PAIR multiplier. #if GB_IS_PAIR_MULTIPLIER #if GB_IS_ANY_MONOID // ANY monoid: take the first entry found // cij = 1, or CMPLX(1,0) for complex ANY GB_MULT (cij, ignore, ignore) ; #elif GB_IS_EQ_MONOID // A(:,i)'*B(:j) is one, so this result must be // accumulated into cij, as cij += 1, where the // accumulator is the EQ operator. cij = (cij == 1) ; #elif (GB_CTYPE_BITS > 0) // PLUS, XOR monoids: A(:,i)'*B(:,j) is nnz(A(:,i)), // for bool, 8-bit, 16-bit, or 32-bit integer uint64_t t = ((uint64_t) cij) + ainz ; cij = (GB_CTYPE) (t & GB_CTYPE_BITS) ; #elif GB_IS_PLUS_FC32_MONOID // PLUS monoid for float complex cij = GxB_CMPLXF (crealf (cij) + (float) ainz, 0) ; #elif GB_IS_PLUS_FC64_MONOID // PLUS monoid for double complex cij = GxB_CMPLX (creal (cij) + (double) ainz, 0) ; #else // PLUS monoid for float, double, or 64-bit integers cij += (GB_CTYPE) ainz ; #endif #else //---------------------------------------------------------- // general case //---------------------------------------------------------- if (ainz == bvlen) { //------------------------------------------------------ // both A(:,i) and B(:,j) are dense //------------------------------------------------------ GB_PRAGMA_SIMD_DOT (cij) for (int64_t k = 0 ; k < bvlen ; k++) { GB_DOT_TERMINAL (cij) ; // break if terminal // cij += A(k,i) * B(k,j) GB_GETA (aki, Ax, pA+k) ; // aki = A(k,i) GB_GETB (bkj, Bx, pB+k) ; // bkj = B(k,j) GB_MULTADD (cij, aki, bkj) ; // cij += aki * bkj } } else { //------------------------------------------------------ // A(:,i) is sparse and B(:,j) is dense //------------------------------------------------------ GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pA ; p < pA_end ; p++) { GB_DOT_TERMINAL (cij) ; // break if terminal int64_t k = Ai [p] ; // cij += A(k,i) * B(k,j) GB_GETA (aki, Ax, p ) ; // aki = A(k,i) GB_GETB (bkj, Bx, pB+k) ; // bkj = B(k,j) GB_MULTADD (cij, aki, bkj) ; // cij += aki * bkj } } #endif GB_PUTC (cij, pC) ; // Cx [pC] = cij } } else { //-------------------------------------------------------------- // B(:,j) is sparse //-------------------------------------------------------------- // get the first and last index in B(:,j) int64_t ib_first = Bi [pB_start] ; int64_t ib_last = Bi [pB_end-1] ; for (int64_t ak = akfirst ; ak < aklast ; ak++) { //---------------------------------------------------------- // get A(:,i) //---------------------------------------------------------- int64_t i = (Ah == NULL) ? ak : Ah [ak] ; int64_t pA = Ap [ak] ; int64_t pA_end = Ap [ak+1] ; int64_t ainz = pA_end - pA ; if (ainz == 0) continue ; // get the first and last index in A(:,i) if (Ai [pA_end-1] < ib_first || ib_last < Ai [pA]) continue; //---------------------------------------------------------- // C(i,j) += A(:,i)'*B(:,j) //---------------------------------------------------------- GB_CIJ_DECLARE (cij) ; // declare the cij scalar int64_t pC = i + pC_start ; // C(i,j) is at Cx [pC] int64_t pB = pB_start ; if (ainz == bvlen) { //------------------------------------------------------ // A(:,i) is dense and B(:,j) is sparse //------------------------------------------------------ GB_GETC (cij, pC) ; // cij = Cx [pC] #if GB_IS_PAIR_MULTIPLIER #if GB_IS_ANY_MONOID // ANY monoid: take the first entry found // cij = 1, or CMPLX(1,0) for complex ANY GB_MULT (cij, ignore, ignore) ; #elif GB_IS_EQ_MONOID // A(:,i)'*B(:j) is one, so this result must be // accumulated into cij, as cij += 1, where the // accumulator is the EQ operator. cij = (cij == 1) ; #elif (GB_CTYPE_BITS > 0) // PLUS, XOR monoids: A(:,i)'*B(:,j) is nnz(A(:,i)), // for bool, 8-bit, 16-bit, or 32-bit integer uint64_t t = ((uint64_t) cij) + bjnz ; cij = (GB_CTYPE) (t & GB_CTYPE_BITS) ; #elif GB_IS_PLUS_FC32_MONOID // PLUS monoid for float complex cij = GxB_CMPLXF (crealf (cij) + (float) bjnz, 0) ; #elif GB_IS_PLUS_FC64_MONOID // PLUS monoid for double complex cij = GxB_CMPLX (creal (cij) + (double) bjnz, 0) ; #else // PLUS monoid for float, double, or 64-bit integers cij += (GB_CTYPE) bjnz ; #endif #else GB_PRAGMA_SIMD_DOT (cij) for (int64_t p = pB ; p < pB_end ; p++) { GB_DOT_TERMINAL (cij) ; // break if terminal int64_t k = Bi [p] ; // cij += A(k,i) * B(k,j) GB_GETA (aki, Ax, pA+k) ; // aki = A(k,i) GB_GETB (bkj, Bx, p ) ; // bkj = B(k,j) GB_MULTADD (cij, aki, bkj) ; // cij += aki*bkj } #endif GB_PUTC (cij, pC) ; // Cx [pC] = cij } else if (ainz > 8 * bjnz) { //------------------------------------------------------ // B(:,j) is very sparse compared to A(:,i) //------------------------------------------------------ bool cij_updated = false ; while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) // discard all entries A(ia:ib-1,i) int64_t pleft = pA + 1 ; int64_t pright = pA_end - 1 ; GB_TRIM_BINARY_SEARCH (ib, Ai, pleft, pright) ; ASSERT (pleft > pA) ; pA = pleft ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) pB++ ; } else // ia == ib == k { // A(k,i) and B(k,j) are next entries to merge GB_DOT_MERGE ; } } if (cij_updated) GB_PUTC (cij, pC) ; } else if (bjnz > 8 * ainz) { //------------------------------------------------------ // A(:,i) is very sparse compared to B(:,j) //------------------------------------------------------ bool cij_updated = false ; while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) pA++ ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) // discard all entries B(ib:ia-1,j) int64_t pleft = pB + 1 ; int64_t pright = pB_end - 1 ; GB_TRIM_BINARY_SEARCH (ia, Bi, pleft, pright) ; ASSERT (pleft > pB) ; pB = pleft ; } else // ia == ib == k { // A(k,i) and B(k,j) are next entries to merge GB_DOT_MERGE ; } } if (cij_updated) GB_PUTC (cij, pC) ; } else { //------------------------------------------------------ // A(:,i) and B(:,j) have about the same sparsity //------------------------------------------------------ bool cij_updated = false ; while (pA < pA_end && pB < pB_end) { int64_t ia = Ai [pA] ; int64_t ib = Bi [pB] ; if (ia < ib) { // A(ia,i) appears before B(ib,j) pA++ ; } else if (ib < ia) { // B(ib,j) appears before A(ia,i) pB++ ; } else // ia == ib == k { // A(k,i) and B(k,j) are the entries to merge GB_DOT_MERGE ; } } if (cij_updated) GB_PUTC (cij, pC) ; } } } } } }
threading-funneled.c
#include "mpi.h" #include <stdio.h> void compute_row(int row_index, float input[6][8], float output[6][8]) { for (int j = 0; j < 8; j = j + 1) { /* Here is the 5-point stencil */ const int right_column_index = (j + 1) % 8; const int left_column_index = (j + 8 - 1) % 8; const int top_row_index = row_index-1; const int bottom_row_index = row_index+1; output[row_index][j] = (input[row_index][j] + input[row_index][left_column_index] + input[row_index][right_column_index] + input[top_row_index][j] + input[bottom_row_index][j]); } } int main(int argc, char **argv) { /* ==== CHALLENGE ==== * * Uncomment the line and fix the MPI call to make this code work! * We want to use fork-join parallelism, so pick a more suitable * threading mode */ /* Initialize the MPI environment and check */ int provided, required; /* = FIXME; */ MPI_Init(&argc, &argv); /* FIXME */ MPI_Comm comm = MPI_COMM_WORLD; /* If the program can't run, stop running */ if (required != provided) { printf("Sorry, the MPI library does not provide " "this threading level! Aborting!\n"); MPI_Abort(comm, 1); } int rank, size; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); if (size != 2) { if (rank == 0) { printf("Only two ranks is supported for this exercise, " "please re-run with two ranks\n"); } MPI_Finalize(); return 0; } /* Prepare the initial values for this process */ float local_data_set[4][8]; printf("Local data set on rank %d was:\n", rank); for (int i = 0; i < 4; i = i + 1) { printf(" [ "); for (int j = 0; j < 8; j = j + 1) { /* Make sure the local data on each rank is different, so * that we see the communication works properly. */ local_data_set[i][j] = 1*(rank + 1); if (j != 0) { printf(", "); } printf("%g", local_data_set[i][j]); } printf(" ]\n"); } float working_data_set[6][8]; for (int i = 0; i < 4; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { /* Initialize the local part of the working data set */ working_data_set[i+1][j] = local_data_set[i][j]; } } /* Prepare to report whether the code is correct */ int success = 1; /* Do the loop over heat-propagation steps */ float next_working_data_set[6][8]; float total, local_total, temporary_total; const int total_root_rank = 0; MPI_Request total_request = MPI_REQUEST_NULL; const int max_step = 10; for (int step = 0; step < max_step; step = step + 1) { int send_up_tag = 0, send_down_tag = 1; /* Prepare to receive the halo data */ int source_rank = size-rank-1; MPI_Request sent_from_source[2]; MPI_Irecv(working_data_set[5], 8, MPI_FLOAT, source_rank, send_up_tag, comm, &sent_from_source[0]); MPI_Irecv(working_data_set[0], 8, MPI_FLOAT, source_rank, send_down_tag, comm, &sent_from_source[1]); /* Prepare to send the border data */ int destination_rank = size-rank-1; MPI_Request sent_to_destination[2]; MPI_Isend(working_data_set[1], 8, MPI_FLOAT, destination_rank, send_up_tag, comm, &sent_to_destination[0]); MPI_Isend(working_data_set[4], 8, MPI_FLOAT, destination_rank, send_down_tag, comm, &sent_to_destination[1]); /* ==== CHALLENGE ==== * * Uncomment and fix the arguments to the MPI call to make * this code work! * * Pass parameters to compute_row() in a way that each * iteration of the for loop does an equal part of the * local_work, ie rows 2 and 3 of the working_data_set. You * may need to consult the parameter names of compute_row(). */ /* Do the local computation. OpenMP will distribute each * iteration to a different thread. */ /* int local_work[] = FIXME; */ #pragma omp parallel for for (int k = 0; k != 2; k = k + 1) { /* compute_row(FIXME, working_data_set, next_working_data_set); */ } /* Implied thread barrier here */ /* Wait for the halo-exchange receives to complete */ MPI_Wait(&sent_from_source[0], MPI_STATUS_IGNORE); MPI_Wait(&sent_from_source[1], MPI_STATUS_IGNORE); /* ==== CHALLENGE ==== * * Uncomment and fix the arguments to the MPI call to make * this code work! * * Pass parameters to compute_row() in a way that each * iteration of the for loop does an equal part of the * local_work, ie rows 1 and 4 of the working_data_set. You * may need to consult the parameter names of compute_row(). */ /* Do the non-local computation. OpenMP will distribute each * iteration to a different thread. */ /* int non_local_work[] = FIXME; */ #pragma omp parallel for for (int k = 0; k != 2; k = k + 1) { /* compute_row(FIXME, working_data_set, next_working_data_set); */ } /* Implied thread barrier here */ /* Compute the total heat via non-blocking reduction */ if (step % 5 == 4) { local_total = 0; for (int i = 1; i < 5; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { local_total += next_working_data_set[i][j]; } } fprintf(stderr, "Doing an non-blocking reduction on step %d\n", step); MPI_Ireduce(&local_total, &temporary_total, 1, MPI_FLOAT, MPI_SUM, total_root_rank, comm, &total_request); } /* Wait for the most recent total heat reduction, 4 steps after it was started */ if (step % 5 == 3 && total_request != MPI_REQUEST_NULL) { MPI_Wait(&total_request, MPI_STATUS_IGNORE); total = temporary_total; if (rank == total_root_rank) { fprintf(stderr, "Total after waiting at step %d was %g\n", step, total); } } if (rank == total_root_rank) { const float expected_total_value = (step < 8) ? 0 : 300000; if (total != expected_total_value) { success = 0; printf("Failed on step %d with total %g not matching expected %g\n", step, total, expected_total_value); } } /* Wait for the halo-exchange sends to complete */ MPI_Wait(&sent_to_destination[0], MPI_STATUS_IGNORE); MPI_Wait(&sent_to_destination[1], MPI_STATUS_IGNORE); /* Prepare to iterate */ for (int i = 1; i < 5; i = i + 1) { for (int j = 0; j < 8; j = j + 1) { /* copy the output back to the input array */ working_data_set[i][j] = next_working_data_set[i][j]; } } } /* Now that we have left the main loop, we should wait for * the most recent total heat reduction to complete. */ if (total_request != MPI_REQUEST_NULL) { MPI_Wait(&total_request, MPI_STATUS_IGNORE); total = temporary_total; if (rank == total_root_rank) { fprintf(stderr, "Total after waiting at step %d was %g\n", max_step - 1, total); } } if (rank == total_root_rank) { const float expected_total_value = 9.375e+08; if (total != expected_total_value) { success = 0; printf("Failed on step %d with total %g not matching expected %g\n", max_step - 1, total, expected_total_value); } } /* Report whether the code is correct */ if (rank == total_root_rank) { if (success) { printf("SUCCESS on rank %d!\n", rank); } else { printf("Improvement needed before rank %d can report success!\n", rank); } } /* Clean up and exit */ MPI_Finalize(); return 0; }
Random-Search.c
/* Author: Makarios Christakis Description: Parallel implementation of the random search algorithm for the travelling salesman problem. For the parameters below the algorithm converged to: Final total distance: 489587.66 Timed using time() on a 7th gen i7, Ubuntu 18.04 machine we get: real 1m34,568s user 1m34,540s sys 0m0,021s Not a noticable improvement over the serial implementation, which is due to the fact that this algorithm is not really parallelizable and also the problem is NP-hard. NOTE: The moveCity function is loop dependant and thus can't be parallelized. */ #include <math.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> // ********************************************************** // DEFINITIONS #define N_POINTS 10000 // Number of cities to generate #define ITERATIONS 1e9 // Number of iterations to execute // ********************************************************** // GLOBAL VARS float cities[N_POINTS][2] = {0}; int route[N_POINTS + 1] = {0}; float totDist = 0; // ********************************************************** // Initialises the city coordinate vectors and the chosen route // between them. void initVec() { for (int i = 0; i < N_POINTS; i++) { route[i] = i; cities[i][0] = (float)rand() / RAND_MAX * 1e3; cities[i][1] = (float)rand() / RAND_MAX * 1e3; } route[N_POINTS] = 0; } // ********************************************************** // Euclidean distance calculation between 2 points in the grid. float dist(int p1, int p2) { float register dx = cities[p1][0] - cities[p2][0]; float register dy = cities[p1][1] - cities[p2][1]; return (float)sqrt(dx * dx + dy * dy); } // ********************************************************** // Swaps 2 cities and checks if the total distance is shorter. // If it is, it updates the route taken. void moveCity() { int register index1, index2; float tempDist = totDist; do { index1 = 1 + rand() % (N_POINTS - 1); index2 = 1 + rand() % (N_POINTS - 1); } while (index1 == index2); int register point1 = route[index1]; int register point2 = route[index2]; if (abs(index1 - index2) == 1) //when neighboring points are to be swapped, 2 distances change { //Assure that index1 = min(index1,index2) if (index1 > index2) { int tmp = index1; index1 = index2; index2 = tmp; } // subtract tempDist -= dist(route[index1], route[index1 - 1]); tempDist -= dist(route[index2], route[index2 + 1]); // add tempDist += dist(route[index1], route[index2 + 1]); tempDist += dist(route[index2], route[index1 - 1]); } else //In all other cases 4 distances change. { // subtract tempDist -= dist(route[index1], route[index1 - 1]); tempDist -= dist(route[index1], route[index1 + 1]); tempDist -= dist(route[index2], route[index2 - 1]); tempDist -= dist(route[index2], route[index2 + 1]); // add tempDist += dist(route[index1], route[index2 - 1]); tempDist += dist(route[index1], route[index2 + 1]); tempDist += dist(route[index2], route[index1 - 1]); tempDist += dist(route[index2], route[index1 + 1]); } if (tempDist < totDist) { route[index1] = point2; route[index2] = point1; totDist = tempDist; } } int main() { initVec(); // initial total distance calculation #pragma omp parallel for reduction(+:totDist) for (int i = 0; i < N_POINTS; i++) { totDist += dist(route[i], route[i + 1]); } printf("Starting total distance: %.2f\n", totDist); float startDist = totDist; for (int i = 0; i < ITERATIONS; i++) { moveCity(); } printf("Final total distance: %.2f\n", totDist); printf("Delta: %.2f\n\n", totDist - startDist); return 0; }
OVPC.h
// // Created by gonciarz on 10/17/18. // // CPU implementation of GPU pulling scheme algorithm #ifndef LIBAPR_OVPC_H #define LIBAPR_OVPC_H #include <vector> #include "data_structures/Mesh/PixelData.hpp" #include "data_structures/APR/APRAccess.hpp" #include "algorithm/PullingScheme.hpp" class OVPC { // Element big enouth to keep all the levels + 2 highest bits for type // for uint8_t we have [ 2 bit - type(empty, seed, boundary, filler) | 6 bit - level(0-63) ] using ElementType = uint8_t; static constexpr int BIT_SHIFT = 6; static constexpr ElementType OVPC_SEED = SEED_TYPE; static constexpr ElementType OVPC_BOUNDARY = BOUNDARY_TYPE; static constexpr ElementType OVPC_FILLER = FILLER_TYPE; static constexpr ElementType SEED = OVPC_SEED << BIT_SHIFT; static constexpr ElementType BOUNDARY = OVPC_BOUNDARY << BIT_SHIFT; static constexpr ElementType FILLER = OVPC_FILLER << BIT_SHIFT; static constexpr ElementType MASK = 0x03 << BIT_SHIFT; int iLevelMax; int iLevelMin; std::vector<PixelData<ElementType>> iParticleCellTree; public: template <typename T> OVPC(const APRAccess &aAprAccess, const PixelData<T> &aInputLevels) { // Level Max is one less since we are working on downsampled version iLevelMax = aAprAccess.l_max - 1; iLevelMin = aAprAccess.l_min; // Initialize particle cell tree on maximum level with input level data iParticleCellTree.resize(iLevelMax + 1); iParticleCellTree[iLevelMax].init(aInputLevels.y_num, aInputLevels.x_num, aInputLevels.z_num); fillLevel(iLevelMax, aInputLevels); // Downsample with max reduction to levelMin to fill the rest of the tree for(int level = iLevelMax - 1; level >= iLevelMin; --level) { downsample(iParticleCellTree[level + 1], iParticleCellTree[level], [](const float &x, const float &y) -> float { return std::max(x, y); }, [](const float &x) -> float { return x; }, true); } } std::vector<PixelData<ElementType>>& getParticleCellTree() { return iParticleCellTree; } void generateTree() { for (int level = iLevelMin; level <= iLevelMax; ++level) { firstStep(level); } for (int level = iLevelMax - 1; level >= iLevelMin; --level) { secondStep(level); } } private: /** * Sets SEED, BOUNDARY or FILER type to each element of the tree. * @param aCurrentLevel */ void firstStep(ElementType aCurrentLevel) { auto &currData = iParticleCellTree[aCurrentLevel]; const size_t xLen = currData.x_num; const size_t yLen = currData.y_num; const size_t zLen = currData.z_num; short boundaries[3][2] = {{0,2},{0,2},{0,2}}; #ifdef HAVE_OPENMP #pragma omp parallel for default(shared) firstprivate(boundaries) if (zLen * xLen * yLen > 100000) #endif for (size_t j = 0; j < zLen; ++j) { CHECKBOUNDARIES(0, j, zLen - 1, boundaries); for (size_t i = 0; i < xLen; ++i) { CHECKBOUNDARIES(1, i, xLen - 1, boundaries); size_t index = j * xLen * yLen + i * yLen; for (size_t k = 0; k < yLen; ++k) { ElementType level = currData.mesh[index + k]; if (level <= aCurrentLevel) { bool hasNeighHigherLevel = false; bool hasNeighSameLevel = false; CHECKBOUNDARIES(2, k, yLen - 1, boundaries); int64_t jn, in, kn; NEIGHBOURLOOP(jn, in, kn, boundaries) { size_t neighbourIndex = index + k + jn * xLen * yLen + in * yLen + kn ; ElementType neighbourLevel = ~MASK & currData.mesh[neighbourIndex]; if (neighbourLevel > aCurrentLevel) { hasNeighHigherLevel = true; break; } else if (neighbourLevel == aCurrentLevel) hasNeighSameLevel = true; } if (!hasNeighHigherLevel) { if (level == aCurrentLevel) currData.mesh[index + k] |= SEED; else if (hasNeighSameLevel) currData.mesh[index + k] |= BOUNDARY; else currData.mesh[index + k] |= FILLER; } } } } } } /* * Zeros all level values in children when parent has a level set. * Shifts all values to keep only type value (input level are not needed anymore). */ void secondStep(int level) { short children_boundaries[3] = {2, 2, 2}; const int64_t x_num = iParticleCellTree[level].x_num; const int64_t y_num = iParticleCellTree[level].y_num; const int64_t z_num = iParticleCellTree[level].z_num; int64_t prev_x_num = iParticleCellTree[level + 1].x_num; int64_t prev_y_num = iParticleCellTree[level + 1].y_num; int64_t prev_z_num = iParticleCellTree[level + 1].z_num; #ifdef HAVE_OPENMP #pragma omp parallel for default(shared) if (z_num * x_num * y_num > 10000) firstprivate(level, children_boundaries) #endif for (int64_t j = 0; j < z_num; ++j) { children_boundaries[0] = (j == z_num - 1 && prev_z_num % 2 == 1) ? 1 : 2; for (int64_t i = 0; i < x_num; ++i) { children_boundaries[1] = (i == x_num - 1 && prev_x_num % 2 == 1) ? 1 : 2; size_t index = j * x_num * y_num + i * y_num; for (int64_t k = 0; k < y_num; ++k) { children_boundaries[2] = (k == y_num - 1 && prev_y_num % 2 == 1) ? 1 : 2; const ElementType status = iParticleCellTree[level].mesh[index + k]; int64_t jn, in, kn; CHILDRENLOOP(jn, in, kn, children_boundaries) { size_t children_index = jn * prev_x_num * prev_y_num + in * prev_y_num + kn; // If there is any of SEED, FILLER or BOUNDARY type set children to 0 // otherwise just shift to keep type value only iParticleCellTree[level + 1].mesh[children_index] = (status >= SEED) ? 0 : (iParticleCellTree[level + 1].mesh[children_index] >> BIT_SHIFT); } // shift values in min level since they are not handled by childrenloop if (level == iLevelMin) iParticleCellTree[level].mesh[index + k] = status >> BIT_SHIFT; } } } } /* * Fills level with provided data, clamps values to allowed one [minLevel; maxLevel] */ template<typename T> void fillLevel(int level, const PixelData<T> &input) { auto &inMesh = input.mesh; auto &outMesh = iParticleCellTree[level].mesh; #ifdef HAVE_OPENMP #pragma omp parallel for #endif for (size_t i = 0; i < inMesh.size(); ++i) { T v = inMesh[i]; if (v > iLevelMax) v = iLevelMax; else if (v < iLevelMin) v = iLevelMin; outMesh[i] = v; } } }; #endif //LIBAPR_OVPC_H
pre_utilities.h
#ifndef PRE_UTILITES_H #define PRE_UTILITES_H /* System includes */ #include <limits> #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <stdlib.h> #include <time.h> #include <string> /* External includes */ #ifdef _OPENMP #include <omp.h> #endif /* Project includes */ #include "includes/define.h" #include "utilities/timer.h" #include "includes/variables.h" #include "utilities/openmp_utils.h" #include "cluster_information.h" #include "custom_elements/spheric_continuum_particle.h" namespace Kratos { class PreUtilities { public: typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::NodesContainerType::ContainerType NodesContainerType; typedef GlobalPointersVector<Element> ParticleWeakVectorType; typedef GlobalPointersVector<Element>::iterator ParticleWeakIteratorType; KRATOS_CLASS_POINTER_DEFINITION(PreUtilities); /// Default constructor PreUtilities() {} PreUtilities(ModelPart& rModelPart) { //mInitialCenterOfMassAndMass = CalculateCenterOfMass(rModelPart); //mInitialMass = CalculateTotalMass(rModelPart); } /// Destructor virtual ~PreUtilities() {} void SetClusterInformationInProperties(std::string const& name, pybind11::list& list_of_coordinates, pybind11::list& list_of_radii, double size, double volume, pybind11::list& inertias, Properties::Pointer& p_properties) { ClusterInformation cl_info; cl_info.mName = name; array_1d<double,3> coords(3,0.0); for (int i = 0; i < (int)pybind11::len(list_of_coordinates); i++) { pybind11::list list(list_of_coordinates[i]); coords[0] = pybind11::cast<double>(list[0]); coords[1] = pybind11::cast<double>(list[1]); coords[2] = pybind11::cast<double>(list[2]); cl_info.mListOfCoordinates.push_back(coords); } for (int i = 0; i < (int)pybind11::len(list_of_radii); i++) { cl_info.mListOfRadii.push_back(pybind11::cast<double>(list_of_radii[i])); } //TODO: check the sizes (should be the same) cl_info.mSize = size; cl_info.mVolume = volume; cl_info.mInertias[0] = pybind11::cast<double>(inertias[0]); cl_info.mInertias[1] = pybind11::cast<double>(inertias[1]); cl_info.mInertias[2] = pybind11::cast<double>(inertias[2]); p_properties->SetValue(CLUSTER_INFORMATION, cl_info); } void PrintNumberOfNeighboursHistogram(const ModelPart& rSpheresModelPart, std::string const& filename) { std::vector<int> number_of_spheres_with_i_neighbours; number_of_spheres_with_i_neighbours.resize(20); for(int i=0; i<(int)number_of_spheres_with_i_neighbours.size(); i++) {number_of_spheres_with_i_neighbours[i] = 0;} const ElementsArrayType& pElements = rSpheresModelPart.GetCommunicator().LocalMesh().Elements(); ElementsArrayType::ptr_const_iterator begin = pElements.ptr_begin(); for(int i=0; i<(int)pElements.size(); i++) { ElementsArrayType::ptr_const_iterator it = begin + i; const Element& el = **it; const SphericContinuumParticle* p_cont_sphere = dynamic_cast<const SphericContinuumParticle*>(&el); if(p_cont_sphere) { unsigned int size = p_cont_sphere->mContinuumInitialNeighborsSize; if(size > number_of_spheres_with_i_neighbours.size() - 1) size = number_of_spheres_with_i_neighbours.size() - 1; number_of_spheres_with_i_neighbours[size] += 1; } else { const SphericParticle* p_sphere = dynamic_cast<const SphericParticle*>(&el); unsigned int size = p_sphere->mNeighbourElements.size(); if(size > number_of_spheres_with_i_neighbours.size() - 1) size = number_of_spheres_with_i_neighbours.size() - 1; number_of_spheres_with_i_neighbours[size] += 1; } } std::ofstream outputfile(filename, std::ios_base::out | std::ios_base::app); outputfile << "number_of_neighbours percentage_of_spheres_with_that_number_of_neighbours number_of_spheres_with_that_number_of_neighbours\n"; for(int i=0; i<(int)number_of_spheres_with_i_neighbours.size(); i++) { const double percentage = (double)(number_of_spheres_with_i_neighbours[i]) / (double)(rSpheresModelPart.NumberOfElements(0)) * 100.0; outputfile <<i<<" "<<percentage<<" "<<number_of_spheres_with_i_neighbours[i]<<"\n"; } } void FillAnalyticSubModelPartUtility(ModelPart& rSpheresModelPart, ModelPart& rAnalyticSpheresModelPart){ ElementsArrayType& pElements = rSpheresModelPart.GetCommunicator().LocalMesh().Elements(); std::vector<std::vector<std::size_t> > thread_vectors_of_ids; int mNumberOfThreads = OpenMPUtils::GetNumThreads(); thread_vectors_of_ids.resize(mNumberOfThreads); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; int analytic_particle_id = it->Id(); thread_vectors_of_ids[OpenMPUtils::ThisThread()].push_back(analytic_particle_id); } std::vector<std::size_t> vector_of_ids; for (int i = 0; i < mNumberOfThreads; i++) { vector_of_ids.insert(vector_of_ids.end(), thread_vectors_of_ids[i].begin(), thread_vectors_of_ids[i].end()); } rAnalyticSpheresModelPart.AddElements(vector_of_ids); } // non-OMP version // void FillAnalyticSubModelPartUtility(ModelPart& rSpheresModelPart, ModelPart& rAnalyticSpheresModelPart){ // ElementsArrayType& pElements = rSpheresModelPart.GetCommunicator().LocalMesh().Elements(); // std::vector<long unsigned int> vector_of_ids; // for (int k = 0; k < (int)pElements.size(); k++) { // ElementsArrayType::iterator it = pElements.ptr_begin() + k; // int analytic_particle_id = it->Id(); // vector_of_ids.push_back(analytic_particle_id); // } // rAnalyticSpheresModelPart.AddElements(vector_of_ids); // } void ResetSkinParticles(ModelPart& r_model_part) { auto& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { auto it = pNodes.begin() + k; it->FastGetSolutionStepValue(SKIN_SPHERE) = 0.0; } } void SetSkinParticlesInnerCircularBoundary(ModelPart& r_model_part, const double inner_radius, const double detection_radius) { auto& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { auto it = pNodes.begin() + k; const array_1d<double, 3>& coords = it->Coordinates(); array_1d<double, 3> vector_distance_to_center; noalias(vector_distance_to_center) = coords; const double distance_to_center = MathUtils<double>::Norm3(vector_distance_to_center); if(distance_to_center < inner_radius + detection_radius) { it->FastGetSolutionStepValue(SKIN_SPHERE) = 1.0; } } } void SetSkinParticlesOuterCircularBoundary(ModelPart& r_model_part, const double outer_radius, const double detection_radius) { auto& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { auto it = pNodes.begin() + k; const array_1d<double, 3>& coords = it->Coordinates(); array_1d<double, 3> vector_distance_to_center; noalias(vector_distance_to_center) = coords; const double distance_to_center = MathUtils<double>::Norm3(vector_distance_to_center); const double radius = it->FastGetSolutionStepValue(RADIUS); if (distance_to_center + radius > outer_radius - detection_radius) { it->FastGetSolutionStepValue(SKIN_SPHERE) = 1.0; } } } void SetSkinParticlesOuterSquaredBoundary(ModelPart& r_model_part, const double outer_radius, const array_1d<double, 3>& center, const double detection_radius) { auto& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { auto it = pNodes.begin() + k; const array_1d<double, 3>& coords = it->Coordinates(); array_1d<double, 3> vector_distance_to_center; noalias(vector_distance_to_center) = coords - center; const double total_x_distance = fabs(vector_distance_to_center[0]); const double total_y_distance = fabs(vector_distance_to_center[1]); const double radius = it->FastGetSolutionStepValue(RADIUS); if ((total_x_distance + radius > outer_radius - detection_radius) || (total_y_distance + radius > outer_radius - detection_radius)) { it->FastGetSolutionStepValue(SKIN_SPHERE) = 1.0; } } } void BreakBondUtility(ModelPart& rSpheresModelPart){ ElementsArrayType& pElements = rSpheresModelPart.GetCommunicator().LocalMesh().Elements(); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; Element* p_element = &(*it); SphericContinuumParticle* p_sphere = dynamic_cast<SphericContinuumParticle*>(p_element); if (p_sphere->mNeighbourElements[k] == NULL) continue; double x_node = p_sphere->GetGeometry()[0].Coordinates()[0]; double y_node = p_sphere->GetGeometry()[0].Coordinates()[1]; double z_node = p_sphere->GetGeometry()[0].Coordinates()[2]; double radius = 0.0225; // radi if ((x_node*x_node + z_node*z_node >= radius*radius && y_node < 0.01) || (x_node*x_node + z_node*z_node >= radius*radius && y_node > 0.07)){ // 1- geometry condition unsigned int number_of_neighbors = p_sphere->mContinuumInitialNeighborsSize; for (unsigned int i = 0; i < number_of_neighbors; i++) { SphericContinuumParticle* neighbour_iterator = dynamic_cast<SphericContinuumParticle*>(p_sphere->mNeighbourElements[i]); double x_node_it = neighbour_iterator->GetGeometry()[0].Coordinates()[0]; double z_node_it = neighbour_iterator->GetGeometry()[0].Coordinates()[2]; double radius_it = 0.0225; // radi de la entalla en el shear test. if (x_node_it*x_node_it + z_node_it*z_node_it < radius_it*radius_it){ // 2- geometry condition //int& failure_type = p_sphere->mIniNeighbourFailureId[i]; //failure_type = 1; p_sphere->Set(TO_ERASE, true); neighbour_iterator->Set(TO_ERASE, true); //noalias(other_to_me_vector) = p_sphere->GetGeometry()[0].Coordinates() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].Coordinates(); //noalias(initial_other_to_me_vector) = p_sphere->GetGeometry()[0].GetInitialPosition() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].GetInitialPosition(); } } } else if ((x_node*x_node + z_node*z_node < radius*radius && y_node < 0.01) || (x_node*x_node + z_node*z_node < radius*radius && y_node > 0.07)) { unsigned int number_of_neighbors = p_sphere->mContinuumInitialNeighborsSize; for (unsigned int i = 0; i < number_of_neighbors; i++) { SphericContinuumParticle* neighbour_iterator = dynamic_cast<SphericContinuumParticle*>(p_sphere->mNeighbourElements[i]); double x_node_it = neighbour_iterator->GetGeometry()[0].Coordinates()[0]; double z_node_it = neighbour_iterator->GetGeometry()[0].Coordinates()[2]; double radius_it = 0.0225; // radi de la entalla en el shear test. if (x_node_it*x_node_it + z_node_it*z_node_it > radius_it*radius_it){ // 2- geometry condition //int& failure_type = p_sphere->mIniNeighbourFailureId[i]; //failure_type = 1; p_sphere->Set(TO_ERASE, true); neighbour_iterator->Set(TO_ERASE, true); } } } } } void CreateCartesianSpecimenMdpa(std::string filename) { // We have a prismatic specimen of dimensions 1m x 1m x 2m const double side = 0.15; int divisions; KRATOS_WARNING("DEM") << "\nEnter the number of divisions: "; std::cin >> divisions; if (!divisions) { KRATOS_WARNING("DEM") << "\nCannot divide by zero. Program stopped.\n\n"; exit(EXIT_FAILURE); } const double radius = 0.5 * side / divisions; int node_counter = 0; std::vector<int> skin_nodes; std::vector<int> top_nodes; std::vector<int> bottom_nodes; filename += "DEM.mdpa"; // std::ifstream infile(filename); if(infile.good()) { while(1){ KRATOS_WARNING("DEM") << "\nThe file already exists. Do you want to overwrite it? (y/n) "; char yn; std::cin >> yn; if(yn == 'n') { KRATOS_WARNING("DEM") << "\nStopped.\n\n"; exit(EXIT_FAILURE); } if(yn=='y') break; } } KRATOS_INFO("DEM") << "\nGenerating mesh...\n\n"; clock_t initial_time, end_time; initial_time = clock(); std::ofstream outputfile(filename, std::ios_base::out); outputfile << "Begin ModelPartData\nEnd ModelPartData\n\n"; outputfile << "Begin Properties 1\n"; outputfile << "PARTICLE_DENSITY 2550.0\n"; outputfile << "YOUNG_MODULUS 35e9\n"; outputfile << "POISSON_RATIO 0.20\n"; outputfile << "STATIC_FRICTION 0.5773502691896257\n"; outputfile << "DYNAMIC_FRICTION 0.5773502691896257\n"; outputfile << "PARTICLE_COHESION 0.0\n"; outputfile << "COEFFICIENT_OF_RESTITUTION 0.2\n"; outputfile << "PARTICLE_MATERIAL 1\n"; outputfile << "ROLLING_FRICTION 0.01\n"; outputfile << "ROLLING_FRICTION_WITH_WALLS 0.01\n"; outputfile << "DEM_CONTINUUM_CONSTITUTIVE_LAW_NAME DEM_Dempack\n"; outputfile << "DEM_DISCONTINUUM_CONSTITUTIVE_LAW_NAME DEM_D_Linear_viscous_Coulomb\n"; outputfile << "SLOPE_LIMIT_COEFF_C1 24\n"; outputfile << "SLOPE_LIMIT_COEFF_C2 28\n"; outputfile << "SLOPE_LIMIT_COEFF_C3 1\n"; outputfile << "SLOPE_FRACTION_N1 1\n"; outputfile << "SLOPE_FRACTION_N2 1\n"; outputfile << "SLOPE_FRACTION_N3 35e9\n"; outputfile << "YOUNG_MODULUS_PLASTIC 1000\n"; outputfile << "PLASTIC_YIELD_STRESS 0.2\n"; outputfile << "DAMAGE_FACTOR 1\n"; outputfile << "SHEAR_ENERGY_COEF 1\n"; outputfile << "CONTACT_TAU_ZERO 5\n"; outputfile << "CONTACT_SIGMA_MIN 1\n"; outputfile << "CONTACT_INTERNAL_FRICC 20\n"; outputfile << "End Properties\n"; outputfile << "\nBegin Nodes\n"; // Relative sizes according to axes: int ai=1; int aj=2; int ak=1; //Generation of the samble for (int k = 0; k < ai*divisions; k++) { for (int j = 0; j < aj* divisions; j++) { for (int i = 0; i < ak*divisions; i++) { outputfile << ++node_counter << " " << (1 + 2 * i) * radius - 0.5*side << " " << (1 + 2 * j) * radius << " " << (1 + 2 * k) * radius - 0.5*side << '\n'; if ((i == 0) || (j == 0) || (k == 0) || (i == ai* divisions - 1) || (j == aj*divisions - 1) || (k == ak*divisions - 1)) skin_nodes.push_back(node_counter); if (k == 0) bottom_nodes.push_back(node_counter); if (k == 2 * divisions - 1) top_nodes.push_back(node_counter); } } } // outputfile << "End Nodes\n"; outputfile << "\nBegin Elements SphericContinuumParticle3D\n"; for (int i = 1; i <= node_counter; i++) outputfile << i << " 1 " << i << '\n'; outputfile << "End Elements\n"; outputfile << "\nBegin NodalData RADIUS\n"; for (int i = 1; i <= node_counter; i++) outputfile << i << " 0 " << radius << '\n'; outputfile << "End NodalData\n"; outputfile << "\nBegin NodalData COHESIVE_GROUP // whole specimen\n"; for (int i = 1; i <= node_counter; i++) outputfile << i << " 0 1\n"; outputfile << "End NodalData\n"; //outputfile << "\nBegin NodalData COHESIVE_GROUP // bottom nodes\n"; //for (std::vector<int>::iterator it_bottom = bottom_nodes.begin(); it_bottom != bottom_nodes.end(); it_bottom++) outputfile << *it_bottom << " 0 1\n"; //outputfile << "End NodalData\n\nBegin NodalData COHESIVE_GROUP // top nodes\n"; //for (std::vector<int>::iterator it_top = top_nodes.begin(); it_top != top_nodes.end(); it_top++) outputfile << *it_top << " 0 1\n"; //outputfile << "End NodalData\n"; outputfile << "\nBegin NodalData SKIN_SPHERE\n"; for (std::vector<int>::iterator it_skin = skin_nodes.begin(); it_skin != skin_nodes.end(); it_skin++) outputfile << *it_skin << " 0 1\n"; outputfile << "End NodalData\n\n"; /*outputfile << "Begin Mesh 1 // bottom nodes\n Begin MeshData\n VELOCITY_START_TIME 0.0\n"; outputfile << " FORCE_INTEGRATION_GROUP 0\n VELOCITY_STOP_TIME 100.0\n TOP 0\n"; outputfile << " IMPOSED_VELOCITY_Z_VALUE 0.0005\n BOTTOM 0\n End MeshData\n Begin MeshNodes\n"; for (std::vector<int>::iterator it_bottom = bottom_nodes.begin(); it_bottom != bottom_nodes.end(); it_bottom++) outputfile << " " << *it_bottom << '\n'; outputfile << " End MeshNodes\nEnd Mesh\n\n"; outputfile << "Begin Mesh 2 // top nodes\n Begin MeshData\n VELOCITY_START_TIME 0.0\n"; outputfile << " FORCE_INTEGRATION_GROUP 0\n VELOCITY_STOP_TIME 100.0\n TOP 0\n"; outputfile << " IMPOSED_VELOCITY_Z_VALUE -0.0005\n BOTTOM 0\n End MeshData\n Begin MeshNodes\n"; for (std::vector<int>::iterator it_top = top_nodes.begin(); it_top != top_nodes.end(); it_top++) outputfile << " " << *it_top << '\n'; outputfile << " End MeshNodes\nEnd Mesh\n";*/ outputfile.close(); end_time = clock(); double elapsed_time = (double(end_time) - double(initial_time)) / CLOCKS_PER_SEC; KRATOS_INFO("DEM") << "\nfinished!\n\n"; KRATOS_INFO("DEM") << "\nTotal number of elements: " << node_counter << '\n'; KRATOS_INFO("DEM") << "\nTime required to create the mdpa file: " << elapsed_time << " seconds\n\n"; } void MeasureTopHeight(ModelPart& rModelPart, double& subtotal, double& weight) { /* ElementsArrayType& pElements = rModelPart.Elements(); for (ElementsArrayType::iterator it= pElements.begin(); it!=pElements.end(); ++it) { if( it->GetGeometry()[0].FastGetSolutionStepValue(GROUP_ID) == 1 ) { ParticleWeakVectorType& mrNeighbours = it->GetValue(NEIGHBOUR_ELEMENTS); for(ParticleWeakIteratorType ineighbour = mrNeighbours.begin(); ineighbour != mrNeighbours.end(); ineighbour++) { if( ineighbour->GetGeometry()[0].FastGetSolutionStepValue(GROUP_ID) != 1 ) { subtotal += it->GetGeometry()[0].Coordinates()[1]*it->GetGeometry()[0].FastGetSolutionStepValue(RADIUS); weight += it->GetGeometry()[0].FastGetSolutionStepValue(RADIUS); break; } } } } */ } void MeasureBotHeight(ModelPart& rModelPart, double& subtotal, double& weight) { /* ElementsArrayType& pElements = rModelPart.Elements(); for (ElementsArrayType::iterator it= pElements.begin(); it!=pElements.end(); ++it) { if( it->GetGeometry()[0].FastGetSolutionStepValue(GROUP_ID) == 2 ) { ParticleWeakVectorType& mrNeighbours = it->GetValue(NEIGHBOUR_ELEMENTS); for(ParticleWeakIteratorType ineighbour = mrNeighbours.begin(); ineighbour != mrNeighbours.end(); ineighbour++) { if( ineighbour->GetGeometry()[0].FastGetSolutionStepValue(GROUP_ID) != 2 ) { subtotal += it->GetGeometry()[0].Coordinates()[1]*it->GetGeometry()[0].FastGetSolutionStepValue(RADIUS); weight += it->GetGeometry()[0].FastGetSolutionStepValue(RADIUS); break; } } } } */ } void MarkToEraseParticlesOutsideRadius(ModelPart& r_model_part, const double max_radius, const array_1d<double, 3>& center, const double tolerance_for_erasing) { auto& pNodes = r_model_part.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int)pNodes.size(); k++) { auto it = pNodes.begin() + k; const array_1d<double, 3>& coords = it->Coordinates(); array_1d<double, 3> vector_distance_to_center; noalias(vector_distance_to_center) = coords - center; const double distance_to_center = MathUtils<double>::Norm3(vector_distance_to_center); const double radius = it->FastGetSolutionStepValue(RADIUS); if(distance_to_center + radius > max_radius + tolerance_for_erasing) { it->Set(TO_ERASE, true); } } } void ApplyConcentricForceOnParticles(ModelPart& r_model_part, const array_1d<double, 3>& center, const double density_for_artificial_gravity) { auto& pElements = r_model_part.GetCommunicator().LocalMesh().Elements(); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++) { auto it = pElements.begin() + k; auto& node = it->GetGeometry()[0]; const array_1d<double, 3>& coords = node.Coordinates(); array_1d<double, 3> vector_particle_to_center; noalias(vector_particle_to_center) = center - coords; const double distance_to_center = MathUtils<double>::Norm3(vector_particle_to_center); const double inv_dist = 1.0 / distance_to_center; array_1d<double, 3> force; SphericParticle* spheric_p_particle = dynamic_cast<SphericParticle*> (&*it); const double volume = spheric_p_particle->CalculateVolume(); noalias(force) = inv_dist * vector_particle_to_center * volume * density_for_artificial_gravity; node.FastGetSolutionStepValue(EXTERNAL_APPLIED_FORCE) = force; } } array_1d<double, 3> GetInitialCenterOfMass() { return mInitialCenterOfMassAndMass; } /// Turn back information as a stemplate<class T, std::size_t dim> tring. virtual std::string Info() const { return ""; } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const { } std::vector<unsigned int>& GetElementPartition() {return (mElementPartition);}; protected: std::vector<unsigned int> mElementPartition; private: array_1d<double, 3> mInitialCenterOfMassAndMass; double mInitialMass; /// Assignment operator PreUtilities & operator=(PreUtilities const& rOther); }; // Class PreUtilities /// output stream function // template<std::size_t TDim> // inline std::ostream& operator << (std::ostream& rOStream) // { // rThis.PrintInfo(rOStream); // rOStream << std::endl; // rThis.PrintData(rOStream); // // return rOStream; // } } // namespace Kratos #endif // PRE_UTILITES_H
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CheckedCAnalysesPrepass.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; /// A key method to reduce duplicate debug info from Sema. virtual void anchor(); ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 29; static const unsigned MaximumAlignment = 1u << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// True if the current expression is a member bounds expression /// for a structure. Member bounds expressions can only reference /// members and cannot reference variables. bool IsMemberBoundsExpr; std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. SmallVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, CheckedPointerKind kind, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, CheckedArrayKind Kind, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildExtIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); ExprResult ConvertParamDefaultArgument(const ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, SourceLocation EqualLoc = SourceLocation()); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); bool ValidateNTCheckedType(ASTContext &C, QualType VDeclType, Expr *Init); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr, RecordDecl::Genericity GenericKind = RecordDecl::NonGeneric, ArrayRef<TypedefDecl *> TypeParams = ArrayRef<TypedefDecl *> {nullptr, 0} ); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); FieldDecl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); /// Push the parameters listed in Params into scope. void ActOnSetupParametersAgain(Scope* S, ArrayRef<ParmVarDecl *> Params); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // Checked C specific methods for merging function declarations. bool CheckedCFunctionDeclCompatibility(FunctionDecl *New, FunctionDecl *Old); bool CheckedCMergeFunctionDecls(FunctionDecl *New, FunctionDecl *Old); bool DiagnoseCheckedCFunctionCompatibility(FunctionDecl *New, FunctionDecl *Old); // used for %select in diagnostics for errors involving checked types. enum class CheckedTypeClassification { CCT_Any, CCT_Struct, CCT_Union }; // used for %select in diagnostics for errors involving redeclarations // with bounds enum class CheckedCBoundsError { CCBE_Parameter, CCBE_Return, CCBE_Variable }; // used for %select in diagnostics for errors involving redeclarations // with bounds annotations. enum class BoundsAnnotationKind { Bounds, IType }; CheckedTypeClassification classifyForCheckedTypeDiagnostic(QualType qt); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ConstexprIf, ///< Condition in a constexpr if statement. CCEK_ExplicitBool ///< Condition in an explicit(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr, CheckedScopeSpecifier WrittenCSS = CSS_None, SourceLocation CSSLoc = SourceLocation(), SourceLocation CSMLoc = SourceLocation(), SourceLocation BNDLoc = SourceLocation()); private: CheckedScopeSpecifier CheckingKind; // Keep a stack of saved checked scope information. class SavedCheckedScope { public: SavedCheckedScope(CheckedScopeSpecifier S, SourceLocation L) : Loc(L), Saved(S) {} SourceLocation Loc; CheckedScopeSpecifier Saved; }; SmallVector<SavedCheckedScope, 8> CheckingKindStack; // can be empty public: CheckedScopeSpecifier GetCheckedScopeInfo() { return CheckingKind; } void SetCheckedScopeInfo(CheckedScopeSpecifier CSS) { CheckingKind = CSS; } void PushCheckedScopeInfo(SourceLocation Loc) { CheckingKindStack.push_back(SavedCheckedScope(CheckingKind, Loc)); } bool PopCheckedScopeInfo() { if (CheckingKindStack.size() > 0) { CheckingKind = CheckingKindStack.back().Saved; CheckingKindStack.pop_back(); return false; } else return true; } void DiagnoseUnterminatedCheckedScope(); bool IsCheckedScope() { return CheckingKind != CSS_Unchecked; } class CheckedScopeRAII { Sema &SemaRef; CheckedScopeSpecifier PrevCheckingKind; public: CheckedScopeRAII(Sema &SemaRef, CheckedScopeSpecifier CSS) : SemaRef(SemaRef), PrevCheckingKind(SemaRef.CheckingKind) { if (CSS != CSS_None) SemaRef.CheckingKind = CSS; } CheckedScopeRAII(Sema &S, DeclSpec &DS) : CheckedScopeRAII(S, DS.getCheckedScopeSpecifier()) { } ~CheckedScopeRAII() { SemaRef.CheckingKind = PrevCheckingKind; } }; /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false, CheckedScopeSpecifier CSS = CSS_None): S(S), CheckedProperties(S, CSS) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; CheckedScopeRAII CheckedProperties; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; // Checked C: Perform semantic analysis on a where clause. WhereClause *ActOnWhereClause(SourceLocation WhereLoc); // Checked C: Perform semantic analysis on a where clause bounds decl fact. BoundsDeclFact *ActOnBoundsDeclFact(IdentifierInfo *Id, Expr *E, Scope *CurScope, SourceLocation IdLoc, SourceLocation BoundsLoc); // Checked C: Perform semantic analysis on a where clause equality-op fact. EqualityOpFact *ActOnEqualityOpFact(Expr *E, SourceLocation ExprLoc); StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); enum CheckedScopeTypeLocation { CSTL_TopLevel, CSTL_Nested, CSTL_BoundsSafeInterface }; /// Returns true if Ty is allowed in a checked scope: /// - If Ty is a pointer or array type, it must be a checked pointer or /// array type or an unchecked pointer or array type with a bounds-safe /// interface. /// - This rule applies recursively to any types nested within Ty. /// - All other types are allowed in checked scopes. /// Return false if Ty is not allowed. bool AllowedInCheckedScope(QualType Ty, const InteropTypeExpr *InteropType, bool IsParam, CheckedScopeTypeLocation Loc, CheckedScopeTypeLocation &ProblemLoc, QualType &ProblemTy); // Enum for diagnostic message that describes the type of declaration // being checked. enum CheckedDeclKind { CDK_Parameter, CDK_FunctionReturn, CDK_LocalVariable, CDK_GlobalVariable, CDK_Member }; /// \param D - target declaration /// \param UseLoc - default invalid location at declaration /// it is valid only if it is regarded as use of variable /// \returns true if target declaration is valid checked decl bool DiagnoseCheckedDecl(const ValueDecl *D, SourceLocation UseLoc = SourceLocation()); bool DiagnoseTypeInCheckedScope(QualType Ty, SourceLocation Start, SourceLocation End); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op, bool isCheckedScope = false); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Checked C Extension ----------------------===// private: QualType ValidateBoundsExprArgument(Expr *Arg); public: ExprResult ActOnNullaryBoundsExpr(SourceLocation BoundKWLoc, BoundsExpr::Kind Kind, SourceLocation RParenLoc); ExprResult ActOnCountBoundsExpr(SourceLocation BoundsKWLoc, BoundsExpr::Kind Kind, Expr *CountExpr, SourceLocation RParenLoc); ExprResult ActOnRangeBoundsExpr(SourceLocation BoundsKWLoc, Expr *LowerBound, Expr *UpperBound, SourceLocation RParenLoc); ExprResult CreateRangeBoundsExpr(SourceLocation BoundsKWLoc, Expr *LowerBound, Expr *UpperBound, RelativeBoundsClause *Relative, SourceLocation RParenLoc); ExprResult ActOnBoundsInteropType(SourceLocation TypeKWLoc, ParsedType Ty, SourceLocation RParenLoc); ExprResult CreateBoundsInteropTypeExpr(SourceLocation TypeKWLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc); ExprResult CreatePositionalParameterExpr(unsigned Index, QualType QT); RelativeBoundsClause* ActOnRelativeTypeBoundsClause(SourceLocation BoundsKWLoc, ParsedType Ty, SourceLocation RParenLoc); RelativeBoundsClause * CreateRelativeTypeBoundsClause(SourceLocation BoundsKWLoc, TypeSourceInfo *TyInfo, SourceLocation RParenLoc); RelativeBoundsClause* ActOnRelativeConstExprClause(Expr *ConstExpr, SourceLocation BoundsKWLoc, SourceLocation RParenLoc); bool CheckBoundsCastBaseType(Expr *E1); ExprResult ActOnBoundsCastExprBounds(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAnagleBracketLoc, ParsedType D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E1, BoundsExpr *ParsedBounds); ExprResult ActOnBoundsCastExprSingle( Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAnagleBracketLoc, ParsedType D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E1); ExprResult BuildBoundsCastExpr(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *CastTypeInfo, SourceRange AngleBrackets, SourceRange Paren, Expr *E1, BoundsExpr *bounds); bool DiagnoseBoundsDeclType(QualType Ty, DeclaratorDecl *D, BoundsAnnotations &BA, bool IsReturnAnnots); /// \\brief Update information in ASTContext tracking for a member what /// bounds declarations depend upon it. FD is the member whose /// bounds are given by Bounds. void TrackMemberBoundsDependences(FieldDecl *FD, BoundsExpr *Bounds); void ActOnBoundsDecl(DeclaratorDecl *D, BoundsAnnotations Annots, bool MergeDeferredBounds = false); void ActOnEmptyBoundsDecl(DeclaratorDecl *D); void ActOnInvalidBoundsDecl(DeclaratorDecl *D); /// \brief Add default bounds/interop type expressions to Annots, if appropriate. void InferBoundsAnnots(QualType Ty, BoundsAnnotations &Annots, bool IsParam); // \#pragma CHECKED_SCOPE. enum PragmaCheckedScopeKind { PCSK_On, PCSK_Off, PCSK_BoundsOnly, PCSK_Push, PCSK_Pop }; void ActOnPragmaCheckedScope(PragmaCheckedScopeKind Kind, SourceLocation Loc); void DiagnoseUnterminatedPragmaCheckedScopePush(); BoundsExpr *CreateInvalidBoundsExpr(); /// /brief Synthesize the interop type expression implied by the presence /// of a bounds expression. Ty is the original unchecked type. Returns null /// if none exists. InteropTypeExpr *SynthesizeInteropTypeExpr(QualType Ty, bool IsParam); // _Return_value in Checked C bounds expressions. ExprResult ActOnReturnValueExpr(SourceLocation Loc); /// \brief When non-NULL, the type of the '_Return_value' expression. QualType BoundsExprReturnValue; /// \brief RAII object used to temporarily set the the type of _Return_value class CheckedCReturnValueRAII { Sema &S; QualType OldReturnValue; public: CheckedCReturnValueRAII(Sema &S, QualType ReturnVal) : S(S) { OldReturnValue = S.BoundsExprReturnValue; S.BoundsExprReturnValue = ReturnVal; } ~CheckedCReturnValueRAII() { S.BoundsExprReturnValue = OldReturnValue; } }; typedef bool (*ParseDeferredBoundsCallBackFn)(void *P, std::unique_ptr<CachedTokens> Toks, ArrayRef<ParmVarDecl *> Params, BoundsAnnotations &Result, const Declarator &D); void SetDeferredBoundsCallBack(void *OpaqueData, ParseDeferredBoundsCallBackFn p); ParseDeferredBoundsCallBackFn DeferredBoundsParser; void *DeferredBoundsParserData; // Represents the context where an expression must be non-modifying. enum NonModifyingContext { NMC_Unknown, NMC_Dynamic_Check, NMC_Count, // Bounds count expression. NMC_Byte_Count, // Bounds byte count expression. NMC_Range, // Bounds range expression. NMC_Function_Return, // Argument for parameter used in function // return bounds. NMC_Function_Parameter // Argument for parameter used in function // parameter bounds. }; /// /brief Checks whether an expression is non-modifying /// (see Checked C Spec, 3.6.1). Returns true if the expression is non-modifying, /// false otherwise. enum NonModifyingMessage { NMM_None, NMM_Error, NMM_Note }; /// \brief Checks whether an expression is non-modifying /// (see Checked C Spec, 3.6.1). Returns true if the expression is non-modifying, /// false otherwise. bool CheckIsNonModifying(Expr *E, NonModifyingContext Req = NonModifyingContext::NMC_Unknown, NonModifyingMessage = NMM_Error); BoundsExpr *CheckNonModifyingBounds(BoundsExpr *Bounds, Expr *E); ExprResult ActOnFunctionTypeApplication(ExprResult TypeFunc, SourceLocation Loc, ArrayRef<TypeArgument> Args); RecordDecl *ActOnRecordTypeApplication(RecordDecl *Base, ArrayRef<TypeArgument> TypeArgs); const ExistentialType *ActOnExistentialType(ASTContext &Context, const Type *TypeVar, QualType InnerType); /// Complete a delayed type application by populating the record's fields with the right types. /// Should only be called once per delayed 'RecordDecl'. void CompleteTypeAppFields(RecordDecl *Incomplete); // Determine whether the given 'RecordDecl' is part of an 'expanding cycle'. // Generic records that form part of an expanding cycle can't be instantiated because they // produce an infinite number of type applications (because we construct the transitive closure // of type applications eagerly). // // Consider the graph of type parameter dependencies as defined below. An expanding cycle // is a cycle in the graph that contains at least one expanding edge. // // We show how the graph is built via an example. Suppose we have three generic structs A<T>, B<U>, C<V>: // // struct A _For_any(T) { struct A<T>* a; struct B<T> *b; } // struct B _For_any(U) { struct C<struct C<U> > *c; } // struct C _For_any(V) { struct A<V>* a; } // // The vertices of the graph are T, U, and V (the type parameter, alpha re-named if needed). // There is an edge between nodes N1 and N2 if N2 is used in a field anywhere in the position of N1. // If N2 appears at the "top-level" replacing N1, then the resulting edge is "non-expanding". // Otheriwse, if N2 appears nested within the argument that replaces N1, then the edge is "expanding". // // In our example the edges are: // // non-expanding: T -> T, T -> U, V -> T, U -> V // expanding: U => V // // T -> U, U => V, V -> T is an expanding cycle because it contains the expanding edge U => V // // The cycle will be detected when C is processed (because C is defined last). If we tried to instantiate C, we would // end up performing the following type applications: // A<V>, B<V>, C<C<V>>, A<C<V>>, B<C<V>>, C<C<C<V>>>, ... // // The definition of expanding cycle is adapted from the 'ECMA 335 Common Language Infrastructure (CLI) Partitions I to VI' standard. // Specifically, Partition II, section II.9.2 'Generics and recursive inheritance graphs'. bool DiagnoseExpandingCycles(RecordDecl *Base, SourceLocation Loc); QualType SubstituteTypeArgs(QualType QT, ArrayRef<TypeArgument> TypeArgs); std::vector<const TypedefNameDecl *> FindFreeVariableDecls(QualType T); bool AbstractForFunctionType(BoundsAnnotations &BA, ArrayRef<DeclaratorChunk::ParamInfo> Params); /// \brief Take a bounds expression with positional parameters from a function /// type and substitute DeclRefs to the corresonding parameters in Params. BoundsExpr *ConcretizeFromFunctionType(BoundsExpr *Expr, ArrayRef<ParmVarDecl *> Params); /// \brief Take a member bounds expression with member references and /// replace the member references with member access expressions using /// MemberBase as the base. Returns a nullptr if there is an error. BoundsExpr *MakeMemberBoundsConcrete(Expr *MemberBase, bool IsArrow, BoundsExpr *Bounds); BoundsExpr *ConcretizeFromFunctionTypeWithArgs(BoundsExpr *Bounds, ArrayRef<Expr *> Args, NonModifyingContext ErrorKind, NonModifyingMessage Message); /// ConvertToFullyCheckedType: convert an expression E to a fully checked type. This /// is used to retype declrefs and member exprs in checked scopes with bounds-safe /// interfaces. The Checked C spec that says that such uses in checked scopes shall be /// treated as having "checked type". ExprResult ConvertToFullyCheckedType(Expr *E, InteropTypeExpr *BA, bool IsParamUse, ExprValueKind VK); /// GetArrayPtrDereference - determine if an lvalue expression is a /// dereference of an _Array_ptr or _Nt_array_ptr (via '*" or an array /// subscript operator). If it is, return the actual dereference expression /// and set Result to the pointer type being dereferenced. Otherwise, return /// null. Expr *GetArrayPtrDereference(Expr *E, QualType &Result); /// ReplaceAssignmentImplicitCast: E has had assignment conversion rules /// applied to it. If an implicit cast has been introduced because of the /// assignment conversion rules, replace it with an explicit cast. /// This allows us to substitute E into other operator expressions without worrying /// about the different implicit conversion rules between assignments and //// other operators. Sema tree rewriting assumes that semantic /// analysis will recreate implicit casts. That doesn't happen properly if /// E is taken from an assignment expression and used in another operator expression. Expr *MakeAssignmentImplicitCastExplicit(Expr *E); enum BoundsDeclarationCheck { BDC_Assignment, BDC_Decrement, BDC_Increment, BDC_Initialization, BDC_Statement, }; /// \brief Check that address=of operation is not taking the /// address of members used in bounds. void CheckAddressTakenMembers(UnaryOperator *AddrOf); /// \brief Check whether E contains a return value expression. bool ContainsReturnValueExpr(Expr *E); /// \brief Wrap a call expression in a Checked C temporay binding /// expression, if a temporary is needed to describe the bounds /// of the result of the call expression. ExprResult CreateTemporaryForCallIfNeeded(ExprResult R); /// CheckFunctionBodyBoundsDecls - check bounds declarations within a function /// body. void CheckFunctionBodyBoundsDecls(FunctionDecl *FD, Stmt *Body); /// CheckTopLevelBoundsDecls - check bounds declarations for variable declarations /// not within a function body. void CheckTopLevelBoundsDecls(VarDecl *VD); // WarnDynamicCheckAlwaysFails - Adds a warning if an explicit dynamic check // will always fail. void WarnDynamicCheckAlwaysFails(const Expr *Condition); // If the VarDecl D has a byte_count or count bounds expression, // NormalizeBounds expands it to a range bounds expression. The expanded // range bounds are attached to the VarDecl D to avoid recomputing the // normalized bounds for D. BoundsExpr *NormalizeBounds(const VarDecl *D); // If the BoundsDeclFact F has a byte_count or count bounds expression, // NormalizeBounds expands it to a range bounds expression. The expanded // range bounds are attached to the BoundsDeclFact F to avoid recomputing // the normalized bounds for F. BoundsExpr *NormalizeBounds(const BoundsDeclFact *F); // Returns the declared bounds for the lvalue expression E. Assignments // to E must satisfy these bounds. After checking a top-level statement, // the inferred bounds of E must imply these declared bounds. BoundsExpr *GetLValueDeclaredBounds(Expr *E, CheckedScopeSpecifier CSS = CheckedScopeSpecifier::CSS_Unchecked); // // Track variables that in-scope bounds declarations depend upon. // TODO: generalize this to other lvalue expressions. class BoundsDependencyTracker { public: typedef SmallVector<VarDecl *, 2> VarBoundsDecls; typedef VarBoundsDecls::iterator VarBoundsIterator; typedef llvm::iterator_range<VarBoundsIterator> VarBoundsIteratorRange; // mapping from variables to bounds that depend upon the variables. typedef std::map<VarDecl *, VarBoundsDecls> DependentMap; private: // Map variables to the bounds declarations that are // in scope and depend upon them. DependentMap Map; // Track the bounds that are in scope so that we can remove them from the // dependent map when the scope is exited. std::vector<VarDecl *> BoundsInScope; public: BoundsDependencyTracker() {} // Call these when entering/exiting scopes so that we can track when // variables go out of scope. EnterScope returns an integer // that should be passed to the corresponding ExitScope call. unsigned EnterScope(); void ExitScope(unsigned scopeBegin); // If D has a bounds declaration, add its dependencies to the existing // scope. void Add(VarDecl *D); VarBoundsIteratorRange DependentBoundsDecls(VarDecl *D) { auto Iter = Map.find(D); if (Iter == Map.end()) return VarBoundsIteratorRange(nullptr, nullptr); return VarBoundsIteratorRange(Iter->second.begin(),Iter->second.end()); } void Dump(raw_ostream &OS); }; BoundsDependencyTracker BoundsDependencies; // Map expressions that modify lvalues (assignments and pre/post // increment/decrement operations) to bounds that may depend on the modified // lvalues. We check the validity of bounds declarations after // expression statements using data flow analysis. During the analysis, // we need to know whether an expression modifies an lvalue involved in a // bounds invariant. The AST traversal order for determining this is lexical // and conflicts with preferred orderings for dataflow analysis, so we // precompute this information before analyzing a function body. class ModifiedBoundsDependencies { public: // A C lvalue expression with bounds on values stored in the lvalue. // It is either a variable or a member expression. struct LValueWithBounds { LValueWithBounds(llvm::PointerUnion<VarDecl *, MemberExpr *> Target, BoundsExpr *Bounds) : Target(Target), Bounds(Bounds) {} llvm::PointerUnion<VarDecl *, MemberExpr *> Target; BoundsExpr *Bounds; // Bounds for target. }; typedef SmallVector<LValueWithBounds,2> LValuesWithBounds; // Map assignments or pre/post increment/decrement expressions to bounds // that depend upon the lvalue modified by the expressions. typedef std::map<Expr *, LValuesWithBounds> DependentBounds; void Add(Expr *E, llvm::PointerUnion<VarDecl *, MemberExpr *> LValue, BoundsExpr *Bounds); void Dump(raw_ostream &OS, ASTContext &Context); ModifiedBoundsDependencies() {} DependentBounds Tracker; }; /// \brief Compute a mapping from statements that modify lvalues to /// in-scope bounds declarations that depend on those lvalues. /// FD is the function being declared and Body is the body of the /// function. They are passed in separately because Body hasn't /// been attached to FD yet. void ComputeBoundsDependencies(ModifiedBoundsDependencies &Tracker, FunctionDecl *FD, Stmt *Body); /// \brief Traverse a function in order to gather information that is /// used by different Checked C analyses such as bounds declaration /// checking, bounds widening, etc. void CheckedCAnalysesPrepass(PrepassInfo &Info, FunctionDecl *FD, Stmt *Body); /// \brief RAII class used to indicate that we are substituting an expression /// into another expression during bounds checking. We need to suppress /// diagnostics emission during this. We are doing type-preserving /// substitutions, so we don't expect semantic errors during substitution. /// There could be warnings, which would confuse users. The warnings could /// could also be escalated to errors, which would cause compilation failures. class ExprSubstitutionScope { Sema &SemaRef; bool PrevDisableSubstitionDiagnostics; public: explicit ExprSubstitutionScope(Sema &SemaRef, bool DisableDiagnostics = true) : SemaRef(SemaRef), PrevDisableSubstitionDiagnostics( SemaRef.DisableSubstitionDiagnostics) { SemaRef.DisableSubstitionDiagnostics = DisableDiagnostics; } ~ExprSubstitutionScope() { SemaRef.DisableSubstitionDiagnostics = PrevDisableSubstitionDiagnostics; } }; bool DisableSubstitionDiagnostics; ExprResult ActOnPackExpression(Expr *PackedExpr, QualType ExistType, TypeArgument SubstArg, SourceLocation StartLoc, SourceLocation EndLoc); /// \brief Information used to profile the Checked C extension. struct CheckedCProfileStats { // The number of MemberExprs created when synthesizing members during // bounds checking. int NumSynthesizedMemberExprs = 0; // The number of AbstractSets created for MemberExprs when synthesizing // members during bounds checking. int NumSynthesizedMemberAbstractSets = 0; }; struct CheckedCProfileStats CheckedCStats; /// \brief Print Checked C profiling information. void PrintCheckedCStats(); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<unsigned, bool, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = std::string(Ext); } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. SmallVector<SourceLocation, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<StringRef> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl * lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, NamedDeclSetType &SameDirectiveDecls); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. void ActOnOpenMPDeclareVariantDirective(FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion, bool isBoundsSafeInterfaceCast = false); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// IncompatibleCheckedCVoid - Assignments to/from void pointers to pointers /// to data containing checked pointers is not allowed in regular checked /// scopes. It is allowed only in unchecked and checked bounds_only scopes. IncompatibleCheckedCVoid, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true, QualType LHSInteropType = QualType()); public: /// \brief: Given a value with type Ty that has a bounds declaration, /// compute the bounds-safe interface type. Returns a null QualType /// if nnoe exists. QualType SynthesizeInteropType(QualType Ty, bool isParam); /// Rewrite function types with bounds-safe interfaces on unchecked /// types to use the checked types specified by the interfaces. Recursively /// apply the rewrite to function types nested within the type. QualType RewriteBoundsSafeInterfaceTypes(QualType Ty); /// \brief Get the bounds-safe interface type for LHS. /// Returns a null QualType if there isn't one. QualType GetCheckedCLValueInteropType(ExprResult LHS); /// \brief Get the bounds-safe interface type for RHS. /// Returns a null QualType if there isn't one. QualType GetCheckedCRValueInteropType(ExprResult RHS); /// \brief If T is an array type, create a checked array type version of T. /// This includes propagating the checked property to nested array types. If /// a valid checked array type cannot be constructed and Diagnose is true, /// print a diagnostic message for the problem. QualType MakeCheckedArrayType(QualType T, bool Diagnose = false, SourceLocation Loc = SourceLocation()); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD) { return targetDiag(Loc, PD.getDiagID()) << PD; } /// Check if the expression is allowed to be used in expressions for the /// offloading devices. void checkDeviceDecl(const ValueDecl *D, SourceLocation Loc); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; /// \brief RAII object that handles state changes for processing a member // bounds expressions. class EnterMemberBoundsExprRAII { Sema &S; bool SavedMemberBounds; public: EnterMemberBoundsExprRAII(Sema &S) : S(S), SavedMemberBounds(S.IsMemberBoundsExpr) { S.IsMemberBoundsExpr = true; } ~EnterMemberBoundsExprRAII() { S.IsMemberBoundsExpr = SavedMemberBounds; } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
munit.c
/* Copyright (c) 2013-2018 Evan Nemerson <evan@nemerson.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /*** Configuration ***/ /* This is just where the output from the test goes. It's really just * meant to let you choose stdout or stderr, but if anyone really want * to direct it to a file let me know, it would be fairly easy to * support. */ #if !defined(MUNIT_OUTPUT_FILE) # define MUNIT_OUTPUT_FILE stdout #endif /* This is a bit more useful; it tells µnit how to format the seconds in * timed tests. If your tests run for longer you might want to reduce * it, and if your computer is really fast and your tests are tiny you * can increase it. */ #if !defined(MUNIT_TEST_TIME_FORMAT) # define MUNIT_TEST_TIME_FORMAT "0.8f" #endif /* If you have long test names you might want to consider bumping * this. The result information takes 43 characters. */ #if !defined(MUNIT_TEST_NAME_LEN) # define MUNIT_TEST_NAME_LEN 37 #endif /* If you don't like the timing information, you can disable it by * defining MUNIT_DISABLE_TIMING. */ #if !defined(MUNIT_DISABLE_TIMING) # define MUNIT_ENABLE_TIMING #endif /*** End configuration ***/ #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE < 200809L) # undef _POSIX_C_SOURCE #endif #if !defined(_POSIX_C_SOURCE) # define _POSIX_C_SOURCE 200809L #endif /* Solaris freaks out if you try to use a POSIX or SUS standard without * the "right" C standard. */ #if defined(_XOPEN_SOURCE) # undef _XOPEN_SOURCE #endif #if defined(__STDC_VERSION__) # if __STDC_VERSION__ >= 201112L # define _XOPEN_SOURCE 700 # elif __STDC_VERSION__ >= 199901L # define _XOPEN_SOURCE 600 # endif #endif /* Because, according to Microsoft, POSIX is deprecated. You've got * to appreciate the chutzpah. */ #if defined(_MSC_VER) && !defined(_CRT_NONSTDC_NO_DEPRECATE) # define _CRT_NONSTDC_NO_DEPRECATE #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) # include <stdbool.h> #elif defined(_WIN32) /* https://msdn.microsoft.com/en-us/library/tf4dy80a.aspx */ #endif #include <limits.h> #include <time.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #if !defined(MUNIT_NO_NL_LANGINFO) && !defined(_WIN32) #define MUNIT_NL_LANGINFO #include <locale.h> #include <langinfo.h> #include <strings.h> #endif #if !defined(_WIN32) # include <unistd.h> # include <sys/types.h> # include <sys/wait.h> #else # include <windows.h> # include <io.h> # include <fcntl.h> # if !defined(STDERR_FILENO) # define STDERR_FILENO _fileno(stderr) # endif #endif #include "munit.h" #define MUNIT_STRINGIFY(x) #x #define MUNIT_XSTRINGIFY(x) MUNIT_STRINGIFY(x) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) # define MUNIT_THREAD_LOCAL __thread #elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) || defined(_Thread_local) # define MUNIT_THREAD_LOCAL _Thread_local #elif defined(_WIN32) # define MUNIT_THREAD_LOCAL __declspec(thread) #endif /* MSVC 12.0 will emit a warning at /W4 for code like 'do { ... } * while (0)', or 'do { ... } while (true)'. I'm pretty sure nobody * at Microsoft compiles with /W4. */ #if defined(_MSC_VER) && (_MSC_VER <= 1800) #pragma warning(disable: 4127) #endif #if defined(_WIN32) || defined(__EMSCRIPTEN__) # define MUNIT_NO_FORK #endif #if defined(__EMSCRIPTEN__) # define MUNIT_NO_BUFFER #endif /*** Logging ***/ static MunitLogLevel munit_log_level_visible = MUNIT_LOG_INFO; static MunitLogLevel munit_log_level_fatal = MUNIT_LOG_ERROR; #if defined(MUNIT_THREAD_LOCAL) static MUNIT_THREAD_LOCAL bool munit_error_jmp_buf_valid = false; static MUNIT_THREAD_LOCAL jmp_buf munit_error_jmp_buf; #endif /* At certain warning levels, mingw will trigger warnings about * suggesting the format attribute, which we've explicity *not* set * because it will then choke on our attempts to use the MS-specific * I64 modifier for size_t (which we have to use since MSVC doesn't * support the C99 z modifier). */ #if defined(__MINGW32__) || defined(__MINGW64__) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wsuggest-attribute=format" #endif MUNIT_PRINTF(5,0) static void munit_logf_exv(MunitLogLevel level, FILE* fp, const char* filename, int line, const char* format, va_list ap) { if (level < munit_log_level_visible) return; switch (level) { case MUNIT_LOG_DEBUG: fputs("Debug", fp); break; case MUNIT_LOG_INFO: fputs("Info", fp); break; case MUNIT_LOG_WARNING: fputs("Warning", fp); break; case MUNIT_LOG_ERROR: fputs("Error", fp); break; default: munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Invalid log level (%d)", level); return; } fputs(": ", fp); if (filename != NULL) fprintf(fp, "%s:%d: ", filename, line); vfprintf(fp, format, ap); fputc('\n', fp); } MUNIT_PRINTF(3,4) static void munit_logf_internal(MunitLogLevel level, FILE* fp, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, fp, NULL, 0, format, ap); va_end(ap); } static void munit_log_internal(MunitLogLevel level, FILE* fp, const char* message) { munit_logf_internal(level, fp, "%s", message); } void munit_logf_ex(MunitLogLevel level, const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(level, stderr, filename, line, format, ap); va_end(ap); if (level >= munit_log_level_fatal) { #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } } void munit_errorf_ex(const char* filename, int line, const char* format, ...) { va_list ap; va_start(ap, format); munit_logf_exv(MUNIT_LOG_ERROR, stderr, filename, line, format, ap); va_end(ap); #if defined(MUNIT_THREAD_LOCAL) if (munit_error_jmp_buf_valid) longjmp(munit_error_jmp_buf, 1); #endif abort(); } #if defined(__MINGW32__) || defined(__MINGW64__) #pragma GCC diagnostic pop #endif #if !defined(MUNIT_STRERROR_LEN) # define MUNIT_STRERROR_LEN 80 #endif static void munit_log_errno(MunitLogLevel level, FILE* fp, const char* msg) { #if defined(MUNIT_NO_STRERROR_R) || (defined(__MINGW32__) && !defined(MINGW_HAS_SECURE_API)) munit_logf_internal(level, fp, "%s: %s (%d)", msg, strerror(errno), errno); #else char munit_error_str[MUNIT_STRERROR_LEN]; munit_error_str[0] = '\0'; #if !defined(_WIN32) strerror_r(errno, munit_error_str, MUNIT_STRERROR_LEN); #else strerror_s(munit_error_str, MUNIT_STRERROR_LEN, errno); #endif munit_logf_internal(level, fp, "%s: %s (%d)", msg, munit_error_str, errno); #endif } /*** Memory allocation ***/ void* munit_malloc_ex(const char* filename, int line, size_t size) { void* ptr; if (size == 0) return NULL; ptr = calloc(1, size); if (MUNIT_UNLIKELY(ptr == NULL)) { munit_logf_ex(MUNIT_LOG_ERROR, filename, line, "Failed to allocate %" MUNIT_SIZE_MODIFIER "u bytes.", size); } return ptr; } /*** Timer code ***/ #if defined(MUNIT_ENABLE_TIMING) #define psnip_uint64_t munit_uint64_t #define psnip_uint32_t munit_uint32_t /* Code copied from portable-snippets * <https://github.com/nemequ/portable-snippets/>. If you need to * change something, please do it there so we can keep the code in * sync. */ /* Clocks (v1) * Portable Snippets - https://gitub.com/nemequ/portable-snippets * Created by Evan Nemerson <evan@nemerson.com> * * To the extent possible under law, the authors have waived all * copyright and related or neighboring rights to this code. For * details, see the Creative Commons Zero 1.0 Universal license at * https://creativecommons.org/publicdomain/zero/1.0/ */ #if !defined(PSNIP_CLOCK_H) #define PSNIP_CLOCK_H #if !defined(psnip_uint64_t) # include "../exact-int/exact-int.h" #endif #if !defined(PSNIP_CLOCK_STATIC_INLINE) # if defined(__GNUC__) # define PSNIP_CLOCK__COMPILER_ATTRIBUTES __attribute__((__unused__)) # else # define PSNIP_CLOCK__COMPILER_ATTRIBUTES # endif # define PSNIP_CLOCK__FUNCTION PSNIP_CLOCK__COMPILER_ATTRIBUTES static #endif enum PsnipClockType { /* This clock provides the current time, in units since 1970-01-01 * 00:00:00 UTC not including leap seconds. In other words, UNIX * time. Keep in mind that this clock doesn't account for leap * seconds, and can go backwards (think NTP adjustments). */ PSNIP_CLOCK_TYPE_WALL = 1, /* The CPU time is a clock which increases only when the current * process is active (i.e., it doesn't increment while blocking on * I/O). */ PSNIP_CLOCK_TYPE_CPU = 2, /* Monotonic time is always running (unlike CPU time), but it only ever moves forward unless you reboot the system. Things like NTP adjustments have no effect on this clock. */ PSNIP_CLOCK_TYPE_MONOTONIC = 3 }; struct PsnipClockTimespec { psnip_uint64_t seconds; psnip_uint64_t nanoseconds; }; /* Methods we support: */ #define PSNIP_CLOCK_METHOD_CLOCK_GETTIME 1 #define PSNIP_CLOCK_METHOD_TIME 2 #define PSNIP_CLOCK_METHOD_GETTIMEOFDAY 3 #define PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER 4 #define PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME 5 #define PSNIP_CLOCK_METHOD_CLOCK 6 #define PSNIP_CLOCK_METHOD_GETPROCESSTIMES 7 #define PSNIP_CLOCK_METHOD_GETRUSAGE 8 #define PSNIP_CLOCK_METHOD_GETSYSTEMTIMEPRECISEASFILETIME 9 #define PSNIP_CLOCK_METHOD_GETTICKCOUNT64 10 #include <assert.h> #if defined(HEDLEY_UNREACHABLE) # define PSNIP_CLOCK_UNREACHABLE() HEDLEY_UNREACHABLE() #else # define PSNIP_CLOCK_UNREACHABLE() assert(0) #endif /* Choose an implementation */ /* #undef PSNIP_CLOCK_WALL_METHOD */ /* #undef PSNIP_CLOCK_CPU_METHOD */ /* #undef PSNIP_CLOCK_MONOTONIC_METHOD */ /* We want to be able to detect the libc implementation, so we include <limits.h> (<features.h> isn't available everywhere). */ #if defined(__unix__) || defined(__unix) || defined(__linux__) # include <limits.h> # include <unistd.h> #endif #if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) /* These are known to work without librt. If you know of others * please let us know so we can add them. */ # if \ (defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 17))) || \ (defined(__FreeBSD__)) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # elif !defined(PSNIP_CLOCK_NO_LIBRT) # define PSNIP_CLOCK_HAVE_CLOCK_GETTIME # endif #endif #if defined(_WIN32) # if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_GETPROCESSTIMES # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER # endif #endif #if defined(__MACH__) && !defined(__gnu_hurd__) # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME # endif #endif #if defined(PSNIP_CLOCK_HAVE_CLOCK_GETTIME) # include <time.h> # if !defined(PSNIP_CLOCK_WALL_METHOD) # if defined(CLOCK_REALTIME_PRECISE) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME_PRECISE # elif !defined(__sun) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_WALL CLOCK_REALTIME # endif # endif # if !defined(PSNIP_CLOCK_CPU_METHOD) # if defined(_POSIX_CPUTIME) || defined(CLOCK_PROCESS_CPUTIME_ID) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_PROCESS_CPUTIME_ID # elif defined(CLOCK_VIRTUAL) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_CPU CLOCK_VIRTUAL # endif # endif # if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) # if defined(CLOCK_MONOTONIC_RAW) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # elif defined(CLOCK_MONOTONIC_PRECISE) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC_PRECISE # elif defined(_POSIX_MONOTONIC_CLOCK) || defined(CLOCK_MONOTONIC) # define PSNIP_CLOCK_MONOTONIC_METHOD PSNIP_CLOCK_METHOD_CLOCK_GETTIME # define PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC CLOCK_MONOTONIC # endif # endif #endif #if defined(_POSIX_VERSION) && (_POSIX_VERSION >= 200112L) # if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_GETTIMEOFDAY # endif #endif #if !defined(PSNIP_CLOCK_WALL_METHOD) # define PSNIP_CLOCK_WALL_METHOD PSNIP_CLOCK_METHOD_TIME #endif #if !defined(PSNIP_CLOCK_CPU_METHOD) # define PSNIP_CLOCK_CPU_METHOD PSNIP_CLOCK_METHOD_CLOCK #endif /* Primarily here for testing. */ #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) && defined(PSNIP_CLOCK_REQUIRE_MONOTONIC) # error No monotonic clock found. #endif /* Implementations */ #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_TIME)) # include <time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY)) # include <sys/time.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES)) || \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64)) # include <windows.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE)) # include <sys/time.h> # include <sys/resource.h> #endif #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME)) # include <CoreServices/CoreServices.h> # include <mach/mach.h> # include <mach/mach_time.h> #endif /*** Implementations ***/ #define PSNIP_CLOCK_NSEC_PER_SEC ((psnip_uint32_t) (1000000000ULL)) #if \ (defined(PSNIP_CLOCK_CPU_METHOD) && (PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_WALL_METHOD) && (PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) || \ (defined(PSNIP_CLOCK_MONOTONIC_METHOD) && (PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME)) PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock__clock_getres (clockid_t clk_id) { struct timespec res; int r; r = clock_getres(clk_id, &res); if (r != 0) return 0; return (psnip_uint32_t) (PSNIP_CLOCK_NSEC_PER_SEC / res.tv_nsec); } PSNIP_CLOCK__FUNCTION int psnip_clock__clock_gettime (clockid_t clk_id, struct PsnipClockTimespec* res) { struct timespec ts; if (clock_gettime(clk_id, &ts) != 0) return -10; res->seconds = (psnip_uint64_t) (ts.tv_sec); res->nanoseconds = (psnip_uint64_t) (ts.tv_nsec); return 0; } #endif PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_wall_get_precision (void) { #if !defined(PSNIP_CLOCK_WALL_METHOD) return 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_WALL); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY return 1000000; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME return 1; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_wall_get_time (struct PsnipClockTimespec* res) { (void) res; #if !defined(PSNIP_CLOCK_WALL_METHOD) return -2; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_WALL, res); #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_TIME res->seconds = time(NULL); res->nanoseconds = 0; #elif defined(PSNIP_CLOCK_WALL_METHOD) && PSNIP_CLOCK_WALL_METHOD == PSNIP_CLOCK_METHOD_GETTIMEOFDAY struct timeval tv; if (gettimeofday(&tv, NULL) != 0) return -6; res->seconds = tv.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_cpu_get_precision (void) { #if !defined(PSNIP_CLOCK_CPU_METHOD) return 0; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_CPU); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK return CLOCKS_PER_SEC; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES return PSNIP_CLOCK_NSEC_PER_SEC / 100; #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_cpu_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_CPU_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_CPU, res); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_CLOCK clock_t t = clock(); if (t == ((clock_t) -1)) return -5; res->seconds = t / CLOCKS_PER_SEC; res->nanoseconds = (t % CLOCKS_PER_SEC) * (PSNIP_CLOCK_NSEC_PER_SEC / CLOCKS_PER_SEC); #elif defined(PSNIP_CLOCK_CPU_METHOD) && PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETPROCESSTIMES FILETIME CreationTime, ExitTime, KernelTime, UserTime; LARGE_INTEGER date, adjust; if (!GetProcessTimes(GetCurrentProcess(), &CreationTime, &ExitTime, &KernelTime, &UserTime)) return -7; /* http://www.frenk.com/2009/12/convert-filetime-to-unix-timestamp/ */ date.HighPart = UserTime.dwHighDateTime; date.LowPart = UserTime.dwLowDateTime; adjust.QuadPart = 11644473600000 * 10000; date.QuadPart -= adjust.QuadPart; res->seconds = date.QuadPart / 10000000; res->nanoseconds = (date.QuadPart % 10000000) * (PSNIP_CLOCK_NSEC_PER_SEC / 100); #elif PSNIP_CLOCK_CPU_METHOD == PSNIP_CLOCK_METHOD_GETRUSAGE struct rusage usage; if (getrusage(RUSAGE_SELF, &usage) != 0) return -8; res->seconds = usage.ru_utime.tv_sec; res->nanoseconds = tv.tv_usec * 1000; #else (void) res; return -2; #endif return 0; } PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_monotonic_get_precision (void) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) return 0; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_getres(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); return (psnip_uint32_t) (tbi.numer / tbi.denom); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 return 1000; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); return (psnip_uint32_t) ((Frequency.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) ? PSNIP_CLOCK_NSEC_PER_SEC : Frequency.QuadPart); #else return 0; #endif } PSNIP_CLOCK__FUNCTION int psnip_clock_monotonic_get_time (struct PsnipClockTimespec* res) { #if !defined(PSNIP_CLOCK_MONOTONIC_METHOD) (void) res; return -2; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_CLOCK_GETTIME return psnip_clock__clock_gettime(PSNIP_CLOCK_CLOCK_GETTIME_MONOTONIC, res); #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_MACH_ABSOLUTE_TIME psnip_uint64_t nsec = mach_absolute_time(); static mach_timebase_info_data_t tbi = { 0, }; if (tbi.denom == 0) mach_timebase_info(&tbi); nsec *= ((psnip_uint64_t) tbi.numer) / ((psnip_uint64_t) tbi.denom); res->seconds = nsec / PSNIP_CLOCK_NSEC_PER_SEC; res->nanoseconds = nsec % PSNIP_CLOCK_NSEC_PER_SEC; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_QUERYPERFORMANCECOUNTER LARGE_INTEGER t, f; if (QueryPerformanceCounter(&t) == 0) return -12; QueryPerformanceFrequency(&f); res->seconds = t.QuadPart / f.QuadPart; res->nanoseconds = t.QuadPart % f.QuadPart; if (f.QuadPart > PSNIP_CLOCK_NSEC_PER_SEC) res->nanoseconds /= f.QuadPart / PSNIP_CLOCK_NSEC_PER_SEC; else res->nanoseconds *= PSNIP_CLOCK_NSEC_PER_SEC / f.QuadPart; #elif defined(PSNIP_CLOCK_MONOTONIC_METHOD) && PSNIP_CLOCK_MONOTONIC_METHOD == PSNIP_CLOCK_METHOD_GETTICKCOUNT64 const ULONGLONG msec = GetTickCount64(); res->seconds = msec / 1000; res->nanoseconds = sec % 1000; #else return -2; #endif return 0; } /* Returns the number of ticks per second for the specified clock. * For example, a clock with millisecond precision would return 1000, * and a clock with 1 second (such as the time() function) would * return 1. * * If the requested clock isn't available, it will return 0. * Hopefully this will be rare, but if it happens to you please let us * know so we can work on finding a way to support your system. * * Note that different clocks on the same system often have a * different precisions. */ PSNIP_CLOCK__FUNCTION psnip_uint32_t psnip_clock_get_precision (enum PsnipClockType clock_type) { switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_precision (); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_precision (); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_precision (); } PSNIP_CLOCK_UNREACHABLE(); return 0; } /* Set the provided timespec to the requested time. Returns 0 on * success, or a negative value on failure. */ PSNIP_CLOCK__FUNCTION int psnip_clock_get_time (enum PsnipClockType clock_type, struct PsnipClockTimespec* res) { assert(res != NULL); switch (clock_type) { case PSNIP_CLOCK_TYPE_MONOTONIC: return psnip_clock_monotonic_get_time (res); case PSNIP_CLOCK_TYPE_CPU: return psnip_clock_cpu_get_time (res); case PSNIP_CLOCK_TYPE_WALL: return psnip_clock_wall_get_time (res); } return -1; } #endif /* !defined(PSNIP_CLOCK_H) */ static psnip_uint64_t munit_clock_get_elapsed(struct PsnipClockTimespec* start, struct PsnipClockTimespec* end) { psnip_uint64_t r = (end->seconds - start->seconds) * PSNIP_CLOCK_NSEC_PER_SEC; if (end->nanoseconds < start->nanoseconds) { r -= (start->nanoseconds - end->nanoseconds); } else { r += (end->nanoseconds - start->nanoseconds); } return r; } #else # include <time.h> #endif /* defined(MUNIT_ENABLE_TIMING) */ /*** PRNG stuff ***/ /* This is (unless I screwed up, which is entirely possible) the * version of PCG with 32-bit state. It was chosen because it has a * small enough state that we should reliably be able to use CAS * instead of requiring a lock for thread-safety. * * If I did screw up, I probably will not bother changing it unless * there is a significant bias. It's really not important this be * particularly strong, as long as it is fairly random it's much more * important that it be reproducible, so bug reports have a better * chance of being reproducible. */ #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__) && !defined(__EMSCRIPTEN__) && (!defined(__GNUC_MINOR__) || (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ > 8)) # define HAVE_STDATOMIC #elif defined(__clang__) # if __has_extension(c_atomic) # define HAVE_CLANG_ATOMICS # endif #endif /* Workaround for http://llvm.org/bugs/show_bug.cgi?id=26911 */ #if defined(__clang__) && defined(_WIN32) # undef HAVE_STDATOMIC # if defined(__c2__) # undef HAVE_CLANG_ATOMICS # endif #endif #if defined(_OPENMP) # define ATOMIC_UINT32_T uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(HAVE_STDATOMIC) # include <stdatomic.h> # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) ATOMIC_VAR_INIT(x) #elif defined(HAVE_CLANG_ATOMICS) # define ATOMIC_UINT32_T _Atomic uint32_t # define ATOMIC_UINT32_INIT(x) (x) #elif defined(_WIN32) # define ATOMIC_UINT32_T volatile LONG # define ATOMIC_UINT32_INIT(x) (x) #else # define ATOMIC_UINT32_T volatile uint32_t # define ATOMIC_UINT32_INIT(x) (x) #endif static ATOMIC_UINT32_T munit_rand_state = ATOMIC_UINT32_INIT(42); #if defined(_OPENMP) static inline void munit_atomic_store(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T value) { #pragma omp critical (munit_atomics) *dest = value; } static inline uint32_t munit_atomic_load(ATOMIC_UINT32_T* src) { int ret; #pragma omp critical (munit_atomics) ret = *src; return ret; } static inline uint32_t munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { bool ret; #pragma omp critical (munit_atomics) { if (*dest == *expected) { *dest = desired; ret = true; } else { ret = false; } } return ret; } #elif defined(HAVE_STDATOMIC) # define munit_atomic_store(dest, value) atomic_store(dest, value) # define munit_atomic_load(src) atomic_load(src) # define munit_atomic_cas(dest, expected, value) atomic_compare_exchange_weak(dest, expected, value) #elif defined(HAVE_CLANG_ATOMICS) # define munit_atomic_store(dest, value) __c11_atomic_store(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __c11_atomic_load(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __c11_atomic_compare_exchange_weak(dest, expected, value, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) # define munit_atomic_store(dest, value) __atomic_store_n(dest, value, __ATOMIC_SEQ_CST) # define munit_atomic_load(src) __atomic_load_n(src, __ATOMIC_SEQ_CST) # define munit_atomic_cas(dest, expected, value) __atomic_compare_exchange_n(dest, expected, value, true, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST) #elif defined(__GNUC__) && (__GNUC__ >= 4) # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) __sync_bool_compare_and_swap(dest, *expected, value) #elif defined(_WIN32) /* Untested */ # define munit_atomic_store(dest,value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) # define munit_atomic_cas(dest, expected, value) InterlockedCompareExchange((dest), (value), *(expected)) #else # warning No atomic implementation, PRNG will not be thread-safe # define munit_atomic_store(dest, value) do { *(dest) = (value); } while (0) # define munit_atomic_load(src) (*(src)) static inline bool munit_atomic_cas(ATOMIC_UINT32_T* dest, ATOMIC_UINT32_T* expected, ATOMIC_UINT32_T desired) { if (*dest == *expected) { *dest = desired; return true; } else { return false; } } #endif #define MUNIT_PRNG_MULTIPLIER (747796405U) #define MUNIT_PRNG_INCREMENT (1729U) static munit_uint32_t munit_rand_next_state(munit_uint32_t state) { return state * MUNIT_PRNG_MULTIPLIER + MUNIT_PRNG_INCREMENT; } static munit_uint32_t munit_rand_from_state(munit_uint32_t state) { munit_uint32_t res = ((state >> ((state >> 28) + 4)) ^ state) * (277803737U); res ^= res >> 22; return res; } void munit_rand_seed(munit_uint32_t seed) { munit_uint32_t state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); munit_atomic_store(&munit_rand_state, state); } static munit_uint32_t munit_rand_generate_seed(void) { munit_uint32_t seed, state; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wc = { 0, 0 }; psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wc); seed = (munit_uint32_t) wc.nanoseconds; #else seed = (munit_uint32_t) time(NULL); #endif state = munit_rand_next_state(seed + MUNIT_PRNG_INCREMENT); return munit_rand_from_state(state); } static munit_uint32_t munit_rand_state_uint32(munit_uint32_t* state) { const munit_uint32_t old = *state; *state = munit_rand_next_state(old); return munit_rand_from_state(old); } munit_uint32_t munit_rand_uint32(void) { munit_uint32_t old, state; do { old = munit_atomic_load(&munit_rand_state); state = munit_rand_next_state(old); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return munit_rand_from_state(old); } static void munit_rand_state_memory(munit_uint32_t* state, size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { size_t members_remaining = size / sizeof(munit_uint32_t); size_t bytes_remaining = size % sizeof(munit_uint32_t); munit_uint8_t* b = data; munit_uint32_t rv; while (members_remaining-- > 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, sizeof(munit_uint32_t)); b += sizeof(munit_uint32_t); } if (bytes_remaining != 0) { rv = munit_rand_state_uint32(state); memcpy(b, &rv, bytes_remaining); } } void munit_rand_memory(size_t size, munit_uint8_t data[MUNIT_ARRAY_PARAM(size)]) { munit_uint32_t old, state; do { state = old = munit_atomic_load(&munit_rand_state); munit_rand_state_memory(&state, size, data); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); } static munit_uint32_t munit_rand_state_at_most(munit_uint32_t* state, munit_uint32_t salt, munit_uint32_t max) { /* We want (UINT32_MAX + 1) % max, which in unsigned arithmetic is the same * as (UINT32_MAX + 1 - max) % max = -max % max. We compute -max using not * to avoid compiler warnings. */ const munit_uint32_t min = (~max + 1U) % max; munit_uint32_t x; if (max == (~((munit_uint32_t) 0U))) return munit_rand_state_uint32(state) ^ salt; max++; do { x = munit_rand_state_uint32(state) ^ salt; } while (x < min); return x % max; } static munit_uint32_t munit_rand_at_most(munit_uint32_t salt, munit_uint32_t max) { munit_uint32_t old, state; munit_uint32_t retval; do { state = old = munit_atomic_load(&munit_rand_state); retval = munit_rand_state_at_most(&state, salt, max); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } int munit_rand_int_range(int min, int max) { munit_uint64_t range = (munit_uint64_t) max - (munit_uint64_t) min; if (min > max) return munit_rand_int_range(max, min); if (range > (~((munit_uint32_t) 0U))) range = (~((munit_uint32_t) 0U)); return min + munit_rand_at_most(0, (munit_uint32_t) range); } double munit_rand_double(void) { munit_uint32_t old, state; double retval = 0.0; do { state = old = munit_atomic_load(&munit_rand_state); /* See http://mumble.net/~campbell/tmp/random_real.c for how to do * this right. Patches welcome if you feel that this is too * biased. */ retval = munit_rand_state_uint32(&state) / ((~((munit_uint32_t) 0U)) + 1.0); } while (!munit_atomic_cas(&munit_rand_state, &old, state)); return retval; } /*** Test suite handling ***/ typedef struct { unsigned int successful; unsigned int skipped; unsigned int failed; unsigned int errored; #if defined(MUNIT_ENABLE_TIMING) munit_uint64_t cpu_clock; munit_uint64_t wall_clock; #endif } MunitReport; typedef struct { const char* prefix; const MunitSuite* suite; const char** tests; munit_uint32_t seed; unsigned int iterations; MunitParameter* parameters; bool single_parameter_mode; void* user_data; MunitReport report; bool colorize; bool fork; bool show_stderr; bool fatal_failures; } MunitTestRunner; const char* munit_parameters_get(const MunitParameter params[], const char* key) { const MunitParameter* param; for (param = params ; param != NULL && param->name != NULL ; param++) if (strcmp(param->name, key) == 0) return param->value; return NULL; } #if defined(MUNIT_ENABLE_TIMING) static void munit_print_time(FILE* fp, munit_uint64_t nanoseconds) { fprintf(fp, "%" MUNIT_TEST_TIME_FORMAT, ((double) nanoseconds) / ((double) PSNIP_CLOCK_NSEC_PER_SEC)); } #endif /* Add a paramter to an array of parameters. */ static MunitResult munit_parameters_add(size_t* params_size, MunitParameter* params[MUNIT_ARRAY_PARAM(*params_size)], char* name, char* value) { *params = realloc(*params, sizeof(MunitParameter) * (*params_size + 2)); if (*params == NULL) return MUNIT_ERROR; (*params)[*params_size].name = name; (*params)[*params_size].value = value; (*params_size)++; (*params)[*params_size].name = NULL; (*params)[*params_size].value = NULL; return MUNIT_OK; } /* Concatenate two strings, but just return one of the components * unaltered if the other is NULL or "". */ static char* munit_maybe_concat(size_t* len, char* prefix, char* suffix) { char* res; size_t res_l; const size_t prefix_l = prefix != NULL ? strlen(prefix) : 0; const size_t suffix_l = suffix != NULL ? strlen(suffix) : 0; if (prefix_l == 0 && suffix_l == 0) { res = NULL; res_l = 0; } else if (prefix_l == 0 && suffix_l != 0) { res = suffix; res_l = suffix_l; } else if (prefix_l != 0 && suffix_l == 0) { res = prefix; res_l = prefix_l; } else { res_l = prefix_l + suffix_l; res = malloc(res_l + 1); memcpy(res, prefix, prefix_l); memcpy(res + prefix_l, suffix, suffix_l); res[res_l] = 0; } if (len != NULL) *len = res_l; return res; } /* Possbily free a string returned by munit_maybe_concat. */ static void munit_maybe_free_concat(char* s, const char* prefix, const char* suffix) { if (prefix != s && suffix != s) free(s); } /* Cheap string hash function, just used to salt the PRNG. */ static munit_uint32_t munit_str_hash(const char* name) { const char *p; munit_uint32_t h = 5381U; for (p = name; *p != '\0'; p++) h = (h << 5) + h + *p; return h; } static void munit_splice(int from, int to) { munit_uint8_t buf[1024]; #if !defined(_WIN32) ssize_t len; ssize_t bytes_written; ssize_t write_res; #else int len; int bytes_written; int write_res; #endif do { len = read(from, buf, sizeof(buf)); if (len > 0) { bytes_written = 0; do { write_res = write(to, buf + bytes_written, len - bytes_written); if (write_res < 0) break; bytes_written += write_res; } while (bytes_written < len); } else break; } while (true); } /* This is the part that should be handled in the child process */ static MunitResult munit_test_runner_exec(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[], MunitReport* report) { unsigned int iterations = runner->iterations; MunitResult result = MUNIT_FAIL; #if defined(MUNIT_ENABLE_TIMING) struct PsnipClockTimespec wall_clock_begin = { 0, 0 }, wall_clock_end = { 0, 0 }; struct PsnipClockTimespec cpu_clock_begin = { 0, 0 }, cpu_clock_end = { 0, 0 }; #endif unsigned int i = 0; if ((test->options & MUNIT_TEST_OPTION_SINGLE_ITERATION) == MUNIT_TEST_OPTION_SINGLE_ITERATION) iterations = 1; else if (iterations == 0) iterations = runner->suite->iterations; munit_rand_seed(runner->seed); do { void* data = (test->setup == NULL) ? runner->user_data : test->setup(params, runner->user_data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_begin); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_begin); #endif result = test->test(params, data); #if defined(MUNIT_ENABLE_TIMING) psnip_clock_get_time(PSNIP_CLOCK_TYPE_WALL, &wall_clock_end); psnip_clock_get_time(PSNIP_CLOCK_TYPE_CPU, &cpu_clock_end); #endif if (test->tear_down != NULL) test->tear_down(data); if (MUNIT_LIKELY(result == MUNIT_OK)) { report->successful++; #if defined(MUNIT_ENABLE_TIMING) report->wall_clock += munit_clock_get_elapsed(&wall_clock_begin, &wall_clock_end); report->cpu_clock += munit_clock_get_elapsed(&cpu_clock_begin, &cpu_clock_end); #endif } else { switch ((int) result) { case MUNIT_SKIP: report->skipped++; break; case MUNIT_FAIL: report->failed++; break; case MUNIT_ERROR: report->errored++; break; default: break; } break; } } while (++i < iterations); return result; } #if defined(MUNIT_EMOTICON) # define MUNIT_RESULT_STRING_OK ":)" # define MUNIT_RESULT_STRING_SKIP ":|" # define MUNIT_RESULT_STRING_FAIL ":(" # define MUNIT_RESULT_STRING_ERROR ":o" # define MUNIT_RESULT_STRING_TODO ":/" #else # define MUNIT_RESULT_STRING_OK "OK " # define MUNIT_RESULT_STRING_SKIP "SKIP " # define MUNIT_RESULT_STRING_FAIL "FAIL " # define MUNIT_RESULT_STRING_ERROR "ERROR" # define MUNIT_RESULT_STRING_TODO "TODO " #endif static void munit_test_runner_print_color(const MunitTestRunner* runner, const char* string, char color) { if (runner->colorize) fprintf(MUNIT_OUTPUT_FILE, "\x1b[3%cm%s\x1b[39m", color, string); else fputs(string, MUNIT_OUTPUT_FILE); } #if !defined(MUNIT_NO_BUFFER) static int munit_replace_stderr(FILE* stderr_buf) { if (stderr_buf != NULL) { const int orig_stderr = dup(STDERR_FILENO); int errfd = fileno(stderr_buf); if (MUNIT_UNLIKELY(errfd == -1)) { exit(EXIT_FAILURE); } dup2(errfd, STDERR_FILENO); return orig_stderr; } return -1; } static void munit_restore_stderr(int orig_stderr) { if (orig_stderr != -1) { dup2(orig_stderr, STDERR_FILENO); close(orig_stderr); } } #endif /* !defined(MUNIT_NO_BUFFER) */ /* Run a test with the specified parameters. */ static void munit_test_runner_run_test_with_params(MunitTestRunner* runner, const MunitTest* test, const MunitParameter params[]) { MunitResult result = MUNIT_OK; MunitReport report = { 0, 0, 0, 0, #if defined(MUNIT_ENABLE_TIMING) 0, 0 #endif }; unsigned int output_l; bool first; const MunitParameter* param; FILE* stderr_buf; #if !defined(MUNIT_NO_FORK) int pipefd[2]; pid_t fork_pid; ssize_t bytes_written = 0; ssize_t write_res; ssize_t bytes_read = 0; ssize_t read_res; int status = 0; pid_t changed_pid; #endif if (params != NULL) { output_l = 2; fputs(" ", MUNIT_OUTPUT_FILE); first = true; for (param = params ; param != NULL && param->name != NULL ; param++) { if (!first) { fputs(", ", MUNIT_OUTPUT_FILE); output_l += 2; } else { first = false; } output_l += fprintf(MUNIT_OUTPUT_FILE, "%s=%s", param->name, param->value); } while (output_l++ < MUNIT_TEST_NAME_LEN) { fputc(' ', MUNIT_OUTPUT_FILE); } } fflush(MUNIT_OUTPUT_FILE); stderr_buf = NULL; #if !defined(_WIN32) || defined(__MINGW32__) stderr_buf = tmpfile(); #else tmpfile_s(&stderr_buf); #endif if (stderr_buf == NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create buffer for stderr"); result = MUNIT_ERROR; goto print_result; } #if !defined(MUNIT_NO_FORK) if (runner->fork) { pipefd[0] = -1; pipefd[1] = -1; if (pipe(pipefd) != 0) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to create pipe"); result = MUNIT_ERROR; goto print_result; } fork_pid = fork(); if (fork_pid == 0) { int orig_stderr; close(pipefd[0]); orig_stderr = munit_replace_stderr(stderr_buf); munit_test_runner_exec(runner, test, params, &report); /* Note that we don't restore stderr. This is so we can buffer * things written to stderr later on (such as by * asan/tsan/ubsan, valgrind, etc.) */ close(orig_stderr); do { write_res = write(pipefd[1], ((munit_uint8_t*) (&report)) + bytes_written, sizeof(report) - bytes_written); if (write_res < 0) { if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to write to pipe"); } exit(EXIT_FAILURE); } bytes_written += write_res; } while ((size_t) bytes_written < sizeof(report)); if (stderr_buf != NULL) fclose(stderr_buf); close(pipefd[1]); exit(EXIT_SUCCESS); } else if (fork_pid == -1) { close(pipefd[0]); close(pipefd[1]); if (stderr_buf != NULL) { munit_log_errno(MUNIT_LOG_ERROR, stderr, "unable to fork"); } report.errored++; result = MUNIT_ERROR; } else { close(pipefd[1]); do { read_res = read(pipefd[0], ((munit_uint8_t*) (&report)) + bytes_read, sizeof(report) - bytes_read); if (read_res < 1) break; bytes_read += read_res; } while (bytes_read < (ssize_t) sizeof(report)); changed_pid = waitpid(fork_pid, &status, 0); if (MUNIT_LIKELY(changed_pid == fork_pid) && MUNIT_LIKELY(WIFEXITED(status))) { if (bytes_read != sizeof(report)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited unexpectedly with status %d", WEXITSTATUS(status)); report.errored++; } else if (WEXITSTATUS(status) != EXIT_SUCCESS) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child exited with status %d", WEXITSTATUS(status)); report.errored++; } } else { if (WIFSIGNALED(status)) { #if defined(_XOPEN_VERSION) && (_XOPEN_VERSION >= 700) munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d (%s)", WTERMSIG(status), strsignal(WTERMSIG(status))); #else munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child killed by signal %d", WTERMSIG(status)); #endif } else if (WIFSTOPPED(status)) { munit_logf_internal(MUNIT_LOG_ERROR, stderr_buf, "child stopped by signal %d", WSTOPSIG(status)); } report.errored++; } close(pipefd[0]); waitpid(fork_pid, NULL, 0); } } else #endif { #if !defined(MUNIT_NO_BUFFER) const volatile int orig_stderr = munit_replace_stderr(stderr_buf); #endif #if defined(MUNIT_THREAD_LOCAL) if (MUNIT_UNLIKELY(setjmp(munit_error_jmp_buf) != 0)) { result = MUNIT_FAIL; report.failed++; } else { munit_error_jmp_buf_valid = true; result = munit_test_runner_exec(runner, test, params, &report); } #else result = munit_test_runner_exec(runner, test, params, &report); #endif #if !defined(MUNIT_NO_BUFFER) munit_restore_stderr(orig_stderr); #endif /* Here just so that the label is used on Windows and we don't get * a warning */ goto print_result; } print_result: fputs("[ ", MUNIT_OUTPUT_FILE); if ((test->options & MUNIT_TEST_OPTION_TODO) == MUNIT_TEST_OPTION_TODO) { if (report.failed != 0 || report.errored != 0 || report.skipped != 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_TODO, '3'); result = MUNIT_OK; } else { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); if (MUNIT_LIKELY(stderr_buf != NULL)) munit_log_internal(MUNIT_LOG_ERROR, stderr_buf, "Test marked TODO, but was successful."); runner->report.failed++; result = MUNIT_ERROR; } } else if (report.failed > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_FAIL, '1'); runner->report.failed++; result = MUNIT_FAIL; } else if (report.errored > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_ERROR, '1'); runner->report.errored++; result = MUNIT_ERROR; } else if (report.skipped > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_SKIP, '3'); runner->report.skipped++; result = MUNIT_SKIP; } else if (report.successful > 1) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock / report.successful); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock / report.successful); fprintf(MUNIT_OUTPUT_FILE, " CPU ]\n %-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s Total: [ ", ""); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } else if (report.successful > 0) { munit_test_runner_print_color(runner, MUNIT_RESULT_STRING_OK, '2'); #if defined(MUNIT_ENABLE_TIMING) fputs(" ] [ ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.wall_clock); fputs(" / ", MUNIT_OUTPUT_FILE); munit_print_time(MUNIT_OUTPUT_FILE, report.cpu_clock); fputs(" CPU", MUNIT_OUTPUT_FILE); #endif runner->report.successful++; result = MUNIT_OK; } fputs(" ]\n", MUNIT_OUTPUT_FILE); if (stderr_buf != NULL) { if (result == MUNIT_FAIL || result == MUNIT_ERROR || runner->show_stderr) { fflush(MUNIT_OUTPUT_FILE); rewind(stderr_buf); munit_splice(fileno(stderr_buf), STDERR_FILENO); fflush(stderr); } fclose(stderr_buf); } } static void munit_test_runner_run_test_wild(MunitTestRunner* runner, const MunitTest* test, const char* test_name, MunitParameter* params, MunitParameter* p) { const MunitParameterEnum* pe; char** values; MunitParameter* next; for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { if (p->name == pe->name) break; } if (pe == NULL) return; for (values = pe->values ; *values != NULL ; values++) { next = p + 1; p->value = *values; if (next->name == NULL) { munit_test_runner_run_test_with_params(runner, test, params); } else { munit_test_runner_run_test_wild(runner, test, test_name, params, next); } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) break; } } /* Run a single test, with every combination of parameters * requested. */ static void munit_test_runner_run_test(MunitTestRunner* runner, const MunitTest* test, const char* prefix) { char* test_name = munit_maybe_concat(NULL, (char*) prefix, (char*) test->name); /* The array of parameters to pass to * munit_test_runner_run_test_with_params */ MunitParameter* params = NULL; size_t params_l = 0; /* Wildcard parameters are parameters which have possible values * specified in the test, but no specific value was passed to the * CLI. That means we want to run the test once for every * possible combination of parameter values or, if --single was * passed to the CLI, a single time with a random set of * parameters. */ MunitParameter* wild_params = NULL; size_t wild_params_l = 0; const MunitParameterEnum* pe; const MunitParameter* cli_p; bool filled; unsigned int possible; char** vals; size_t first_wild; const MunitParameter* wp; int pidx; munit_rand_seed(runner->seed); fprintf(MUNIT_OUTPUT_FILE, "%-" MUNIT_XSTRINGIFY(MUNIT_TEST_NAME_LEN) "s", test_name); if (test->parameters == NULL) { /* No parameters. Simple, nice. */ munit_test_runner_run_test_with_params(runner, test, NULL); } else { fputc('\n', MUNIT_OUTPUT_FILE); for (pe = test->parameters ; pe != NULL && pe->name != NULL ; pe++) { /* Did we received a value for this parameter from the CLI? */ filled = false; for (cli_p = runner->parameters ; cli_p != NULL && cli_p->name != NULL ; cli_p++) { if (strcmp(cli_p->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, cli_p->value) != MUNIT_OK)) goto cleanup; filled = true; break; } } if (filled) continue; /* Nothing from CLI, is the enum NULL/empty? We're not a * fuzzer… */ if (pe->values == NULL || pe->values[0] == NULL) continue; /* If --single was passed to the CLI, choose a value from the * list of possibilities randomly. */ if (runner->single_parameter_mode) { possible = 0; for (vals = pe->values ; *vals != NULL ; vals++) possible++; /* We want the tests to be reproducible, even if you're only * running a single test, but we don't want every test with * the same number of parameters to choose the same parameter * number, so use the test name as a primitive salt. */ pidx = munit_rand_at_most(munit_str_hash(test_name), possible - 1); if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[pidx]) != MUNIT_OK)) goto cleanup; } else { /* We want to try every permutation. Put in a placeholder * entry, we'll iterate through them later. */ if (MUNIT_UNLIKELY(munit_parameters_add(&wild_params_l, &wild_params, pe->name, NULL) != MUNIT_OK)) goto cleanup; } } if (wild_params_l != 0) { first_wild = params_l; for (wp = wild_params ; wp != NULL && wp->name != NULL ; wp++) { for (pe = test->parameters ; pe != NULL && pe->name != NULL && pe->values != NULL ; pe++) { if (strcmp(wp->name, pe->name) == 0) { if (MUNIT_UNLIKELY(munit_parameters_add(&params_l, &params, pe->name, pe->values[0]) != MUNIT_OK)) goto cleanup; } } } munit_test_runner_run_test_wild(runner, test, test_name, params, params + first_wild); } else { munit_test_runner_run_test_with_params(runner, test, params); } cleanup: free(params); free(wild_params); } munit_maybe_free_concat(test_name, prefix, test->name); } /* Recurse through the suite and run all the tests. If a list of * tests to run was provied on the command line, run only those * tests. */ static void munit_test_runner_run_suite(MunitTestRunner* runner, const MunitSuite* suite, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const char** test_name; const MunitSuite* child_suite; /* Run the tests. */ for (test = suite->tests ; test != NULL && test->test != NULL ; test++) { if (runner->tests != NULL) { /* Specific tests were requested on the CLI */ for (test_name = runner->tests ; test_name != NULL && *test_name != NULL ; test_name++) { if ((pre_l == 0 || strncmp(pre, *test_name, pre_l) == 0) && strncmp(test->name, *test_name + pre_l, strlen(*test_name + pre_l)) == 0) { munit_test_runner_run_test(runner, test, pre); if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; } } } else { /* Run all tests */ munit_test_runner_run_test(runner, test, pre); } } if (runner->fatal_failures && (runner->report.failed != 0 || runner->report.errored != 0)) goto cleanup; /* Run any child suites. */ for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_test_runner_run_suite(runner, child_suite, pre); } cleanup: munit_maybe_free_concat(pre, prefix, suite->prefix); } static void munit_test_runner_run(MunitTestRunner* runner) { munit_test_runner_run_suite(runner, runner->suite, NULL); } static void munit_print_help(int argc, char* const argv[MUNIT_ARRAY_PARAM(argc)], void* user_data, const MunitArgument arguments[]) { const MunitArgument* arg; (void) argc; printf("USAGE: %s [OPTIONS...] [TEST...]\n\n", argv[0]); puts(" --seed SEED\n" " Value used to seed the PRNG. Must be a 32-bit integer in decimal\n" " notation with no separators (commas, decimals, spaces, etc.), or\n" " hexidecimal prefixed by \"0x\".\n" " --iterations N\n" " Run each test N times. 0 means the default number.\n" " --param name value\n" " A parameter key/value pair which will be passed to any test with\n" " takes a parameter of that name. If not provided, the test will be\n" " run once for each possible parameter value.\n" " --list Write a list of all available tests.\n" " --list-params\n" " Write a list of all available tests and their possible parameters.\n" " --single Run each parameterized test in a single configuration instead of\n" " every possible combination\n" " --log-visible debug|info|warning|error\n" " --log-fatal debug|info|warning|error\n" " Set the level at which messages of different severities are visible,\n" " or cause the test to terminate.\n" #if !defined(MUNIT_NO_FORK) " --no-fork Do not execute tests in a child process. If this option is supplied\n" " and a test crashes (including by failing an assertion), no further\n" " tests will be performed.\n" #endif " --fatal-failures\n" " Stop executing tests as soon as a failure is found.\n" " --show-stderr\n" " Show data written to stderr by the tests, even if the test succeeds.\n" " --color auto|always|never\n" " Colorize (or don't) the output.\n" /* 12345678901234567890123456789012345678901234567890123456789012345678901234567890 */ " --help Print this help message and exit.\n"); #if defined(MUNIT_NL_LANGINFO) setlocale(LC_ALL, ""); fputs((strcasecmp("UTF-8", nl_langinfo(CODESET)) == 0) ? "µnit" : "munit", stdout); #else puts("munit"); #endif printf(" %d.%d.%d\n" "Full documentation at: https://nemequ.github.io/munit/\n", (MUNIT_CURRENT_VERSION >> 16) & 0xff, (MUNIT_CURRENT_VERSION >> 8) & 0xff, (MUNIT_CURRENT_VERSION >> 0) & 0xff); for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) arg->write_help(arg, user_data); } static const MunitArgument* munit_arguments_find(const MunitArgument arguments[], const char* name) { const MunitArgument* arg; for (arg = arguments ; arg != NULL && arg->name != NULL ; arg++) if (strcmp(arg->name, name) == 0) return arg; return NULL; } static void munit_suite_list_tests(const MunitSuite* suite, bool show_params, const char* prefix) { size_t pre_l; char* pre = munit_maybe_concat(&pre_l, (char*) prefix, (char*) suite->prefix); const MunitTest* test; const MunitParameterEnum* params; bool first; char** val; const MunitSuite* child_suite; for (test = suite->tests ; test != NULL && test->name != NULL ; test++) { if (pre != NULL) fputs(pre, stdout); puts(test->name); if (show_params) { for (params = test->parameters ; params != NULL && params->name != NULL ; params++) { fprintf(stdout, " - %s: ", params->name); if (params->values == NULL) { puts("Any"); } else { first = true; for (val = params->values ; *val != NULL ; val++ ) { if(!first) { fputs(", ", stdout); } else { first = false; } fputs(*val, stdout); } putc('\n', stdout); } } } } for (child_suite = suite->suites ; child_suite != NULL && child_suite->prefix != NULL ; child_suite++) { munit_suite_list_tests(child_suite, show_params, pre); } munit_maybe_free_concat(pre, prefix, suite->prefix); } static bool munit_stream_supports_ansi(FILE *stream) { #if !defined(_WIN32) return isatty(fileno(stream)); #else #if !defined(__MINGW32__) size_t ansicon_size = 0; #endif if (isatty(fileno(stream))) { #if !defined(__MINGW32__) getenv_s(&ansicon_size, NULL, 0, "ANSICON"); return ansicon_size != 0; #else return getenv("ANSICON") != NULL; #endif } return false; #endif } int munit_suite_main_custom(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc)], const MunitArgument arguments[]) { int result = EXIT_FAILURE; MunitTestRunner runner; size_t parameters_size = 0; size_t tests_size = 0; int arg; char* envptr; unsigned long ts; char* endptr; unsigned long long iterations; MunitLogLevel level; const MunitArgument* argument; const char** runner_tests; unsigned int tests_run; unsigned int tests_total; runner.prefix = NULL; runner.suite = NULL; runner.tests = NULL; runner.seed = 0; runner.iterations = 0; runner.parameters = NULL; runner.single_parameter_mode = false; runner.user_data = NULL; runner.report.successful = 0; runner.report.skipped = 0; runner.report.failed = 0; runner.report.errored = 0; #if defined(MUNIT_ENABLE_TIMING) runner.report.cpu_clock = 0; runner.report.wall_clock = 0; #endif runner.colorize = false; #if !defined(_WIN32) runner.fork = true; #else runner.fork = false; #endif runner.show_stderr = false; runner.fatal_failures = false; runner.suite = suite; runner.user_data = user_data; runner.seed = munit_rand_generate_seed(); runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); for (arg = 1 ; arg < argc ; arg++) { if (strncmp("--", argv[arg], 2) == 0) { if (strcmp("seed", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } envptr = argv[arg + 1]; ts = strtoul(argv[arg + 1], &envptr, 0); if (*envptr != '\0' || ts > (~((munit_uint32_t) 0U))) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.seed = (munit_uint32_t) ts; arg++; } else if (strcmp("iterations", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } endptr = argv[arg + 1]; iterations = strtoul(argv[arg + 1], &endptr, 0); if (*endptr != '\0' || iterations > UINT_MAX) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } runner.iterations = (unsigned int) iterations; arg++; } else if (strcmp("param", argv[arg] + 2) == 0) { if (arg + 2 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires two arguments", argv[arg]); goto cleanup; } runner.parameters = realloc(runner.parameters, sizeof(MunitParameter) * (parameters_size + 2)); if (runner.parameters == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.parameters[parameters_size].name = (char*) argv[arg + 1]; runner.parameters[parameters_size].value = (char*) argv[arg + 2]; parameters_size++; runner.parameters[parameters_size].name = NULL; runner.parameters[parameters_size].value = NULL; arg += 2; } else if (strcmp("color", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "always") == 0) runner.colorize = true; else if (strcmp(argv[arg + 1], "never") == 0) runner.colorize = false; else if (strcmp(argv[arg + 1], "auto") == 0) runner.colorize = munit_stream_supports_ansi(MUNIT_OUTPUT_FILE); else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } arg++; } else if (strcmp("help", argv[arg] + 2) == 0) { munit_print_help(argc, argv, user_data, arguments); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("single", argv[arg] + 2) == 0) { runner.single_parameter_mode = true; } else if (strcmp("show-stderr", argv[arg] + 2) == 0) { runner.show_stderr = true; #if !defined(_WIN32) } else if (strcmp("no-fork", argv[arg] + 2) == 0) { runner.fork = false; #endif } else if (strcmp("fatal-failures", argv[arg] + 2) == 0) { runner.fatal_failures = true; } else if (strcmp("log-visible", argv[arg] + 2) == 0 || strcmp("log-fatal", argv[arg] + 2) == 0) { if (arg + 1 >= argc) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "%s requires an argument", argv[arg]); goto cleanup; } if (strcmp(argv[arg + 1], "debug") == 0) level = MUNIT_LOG_DEBUG; else if (strcmp(argv[arg + 1], "info") == 0) level = MUNIT_LOG_INFO; else if (strcmp(argv[arg + 1], "warning") == 0) level = MUNIT_LOG_WARNING; else if (strcmp(argv[arg + 1], "error") == 0) level = MUNIT_LOG_ERROR; else { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "invalid value ('%s') passed to %s", argv[arg + 1], argv[arg]); goto cleanup; } if (strcmp("log-visible", argv[arg] + 2) == 0) munit_log_level_visible = level; else munit_log_level_fatal = level; arg++; } else if (strcmp("list", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, false, NULL); result = EXIT_SUCCESS; goto cleanup; } else if (strcmp("list-params", argv[arg] + 2) == 0) { munit_suite_list_tests(suite, true, NULL); result = EXIT_SUCCESS; goto cleanup; } else { argument = munit_arguments_find(arguments, argv[arg] + 2); if (argument == NULL) { munit_logf_internal(MUNIT_LOG_ERROR, stderr, "unknown argument ('%s')", argv[arg]); goto cleanup; } if (!argument->parse_argument(suite, user_data, &arg, argc, argv)) goto cleanup; } } else { runner_tests = realloc((void*) runner.tests, sizeof(char*) * (tests_size + 2)); if (runner_tests == NULL) { munit_log_internal(MUNIT_LOG_ERROR, stderr, "failed to allocate memory"); goto cleanup; } runner.tests = runner_tests; runner.tests[tests_size++] = argv[arg]; runner.tests[tests_size] = NULL; } } fflush(stderr); fprintf(MUNIT_OUTPUT_FILE, "Running test suite with seed 0x%08" PRIx32 "...\n", runner.seed); munit_test_runner_run(&runner); tests_run = runner.report.successful + runner.report.failed + runner.report.errored; tests_total = tests_run + runner.report.skipped; if (tests_run == 0) { fprintf(stderr, "No tests run, %d (100%%) skipped.\n", runner.report.skipped); } else { fprintf(MUNIT_OUTPUT_FILE, "%d of %d (%0.0f%%) tests successful, %d (%0.0f%%) test skipped.\n", runner.report.successful, tests_run, (((double) runner.report.successful) / ((double) tests_run)) * 100.0, runner.report.skipped, (((double) runner.report.skipped) / ((double) tests_total)) * 100.0); } if (runner.report.failed == 0 && runner.report.errored == 0) { result = EXIT_SUCCESS; } cleanup: free(runner.parameters); free((void*) runner.tests); return result; } int munit_suite_main(const MunitSuite* suite, void* user_data, int argc, char* const argv[MUNIT_ARRAY_PARAM(argc)]) { return munit_suite_main_custom(suite, user_data, argc, argv, NULL); }
wand-view.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % W W AAA N N DDDD % % W W A A NN N D D % % W W W AAAAA N N N D D % % WW WW A A N NN D D % % W W A A N N DDDD % % % % V V IIIII EEEEE W W % % V V I E W W % % V V I EEE W W W % % V V I E WW WW % % V IIIII EEEEE W W % % % % % % MagickWand Wand View Methods % % % % Software Design % % Cristy % % March 2003 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickWand/studio.h" #include "MagickWand/MagickWand.h" #include "MagickWand/magick-wand-private.h" #include "MagickWand/wand.h" #include "MagickCore/monitor-private.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #define WandViewId "WandView" /* Typedef declarations. */ struct _WandView { size_t id; char name[MagickPathExtent], *description; RectangleInfo extent; MagickWand *wand; Image *image; CacheView *view; PixelWand ***pixel_wands; ExceptionInfo *exception; MagickBooleanType debug; size_t signature; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneWandView() makes a copy of the specified wand view. % % The format of the CloneWandView method is: % % WandView *CloneWandView(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport WandView *CloneWandView(const WandView *wand_view) { WandView *clone_view; register ssize_t i; assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); if (wand_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name); clone_view=(WandView *) AcquireMagickMemory(sizeof(*clone_view)); if (clone_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", wand_view->name); (void) memset(clone_view,0,sizeof(*clone_view)); clone_view->id=AcquireWandId(); (void) FormatLocaleString(clone_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) clone_view->id); clone_view->description=ConstantString(wand_view->description); clone_view->image=CloneImage(wand_view->image,0,0,MagickTrue, wand_view->exception); clone_view->view=CloneCacheView(wand_view->view); clone_view->extent=wand_view->extent; clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,wand_view->exception); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) clone_view->pixel_wands[i]=ClonePixelWands((const PixelWand **) wand_view->pixel_wands[i],wand_view->extent.width); clone_view->debug=wand_view->debug; if (clone_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_view->name); clone_view->signature=MagickWandSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyWandView() deallocates memory associated with a wand view. % % The format of the DestroyWandView method is: % % WandView *DestroyWandView(WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ static PixelWand ***DestroyPixelsThreadSet(PixelWand ***pixel_wands, const size_t number_wands) { register ssize_t i; assert(pixel_wands != (PixelWand ***) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_wands[i] != (PixelWand **) NULL) pixel_wands[i]=DestroyPixelWands(pixel_wands[i],number_wands); pixel_wands=(PixelWand ***) RelinquishMagickMemory(pixel_wands); return(pixel_wands); } WandExport WandView *DestroyWandView(WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); wand_view->pixel_wands=DestroyPixelsThreadSet(wand_view->pixel_wands, wand_view->extent.width); wand_view->image=DestroyImage(wand_view->image); wand_view->view=DestroyCacheView(wand_view->view); wand_view->exception=DestroyExceptionInfo(wand_view->exception); wand_view->signature=(~MagickWandSignature); RelinquishWandId(wand_view->id); wand_view=(WandView *) RelinquishMagickMemory(wand_view); return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferWandViewIterator() iterates over three wand views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel extent is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination wand view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % The callback signature is: % % MagickBooleanType DuplexTransferImageViewMethod(const WandView *source, % const WandView *duplex,WandView *destination,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferWandViewIterator method is: % % MagickBooleanType DuplexTransferWandViewIterator(WandView *source, % WandView *duplex,WandView *destination, % DuplexTransferWandViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o duplex: the duplex wand view. % % o destination: the destination wand view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType DuplexTransferWandViewIterator(WandView *source, WandView *duplex,WandView *destination,DuplexTransferWandViewMethod transfer, void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (transfer == (DuplexTransferWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict duplex_pixels, *magick_restrict pixels; register ssize_t x; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->extent.x,y, duplex->extent.width,1,duplex->exception); if (duplex_pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) duplex->extent.width; x++) { PixelSetQuantumPixel(duplex->image,duplex_pixels, duplex->pixel_wands[id][x]); duplex_pixels+=GetPixelChannels(duplex->image); } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelSetQuantumPixel(destination->image,destination_pixels, destination->pixel_wands[id][x]); destination_pixels+=GetPixelChannels(destination->image); } if (transfer(source,duplex,destination,y,id,context) == MagickFalse) status=MagickFalse; destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], destination_pixels); destination_pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_DuplexTransferWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewException() returns the severity, reason, and description of any % error that occurs when utilizing a wand view. % % The format of the GetWandViewException method is: % % char *GetWandViewException(const WandView *wand_view, % ExceptionType *severity) % % A description of each parameter follows: % % o wand_view: the pixel wand_view. % % o severity: the severity of the error is returned here. % */ WandExport char *GetWandViewException(const WandView *wand_view, ExceptionType *severity) { char *description; assert(wand_view != (const WandView *) NULL); assert(wand_view->signature == MagickWandSignature); if (wand_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand_view->name); assert(severity != (ExceptionType *) NULL); *severity=wand_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MagickPathExtent, sizeof(*description)); if (description == (char *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", wand_view->name); *description='\0'; if (wand_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( wand_view->exception->severity,wand_view->exception->reason), MagickPathExtent); if (wand_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MagickPathExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( wand_view->exception->severity,wand_view->exception->description), MagickPathExtent); (void) ConcatenateMagickString(description,")",MagickPathExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewExtent() returns the wand view extent. % % The format of the GetWandViewExtent method is: % % RectangleInfo GetWandViewExtent(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport RectangleInfo GetWandViewExtent(const WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewIterator() iterates over the wand view in parallel and calls % your get method for each scanline of the view. The pixel extent is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % The callback signature is: % % MagickBooleanType GetImageViewMethod(const WandView *source, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetWandViewIterator method is: % % MagickBooleanType GetWandViewIterator(WandView *source, % GetWandViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o get: the get callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType GetWandViewIterator(WandView *source, GetWandViewMethod get,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (get == (GetWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); register const Quantum *pixels; register ssize_t x; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } if (get(source,y,id,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_GetWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewPixels() returns the wand view pixel_wands. % % The format of the GetWandViewPixels method is: % % PixelWand *GetWandViewPixels(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport PixelWand **GetWandViewPixels(const WandView *wand_view) { const int id = GetOpenMPThreadId(); assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->pixel_wands[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t W a n d V i e w W a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetWandViewWand() returns the magick wand associated with the wand view. % % The format of the GetWandViewWand method is: % % MagickWand *GetWandViewWand(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport MagickWand *GetWandViewWand(const WandView *wand_view) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); return(wand_view->wand); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsWandView() returns MagickTrue if the the parameter is verified as a wand % view object. % % The format of the IsWandView method is: % % MagickBooleanType IsWandView(const WandView *wand_view) % % A description of each parameter follows: % % o wand_view: the wand view. % */ WandExport MagickBooleanType IsWandView(const WandView *wand_view) { size_t length; if (wand_view == (const WandView *) NULL) return(MagickFalse); if (wand_view->signature != MagickWandSignature) return(MagickFalse); length=strlen(WandViewId); if (LocaleNCompare(wand_view->name,WandViewId,length) != 0) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w W a n d V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewWandView() returns a wand view required for all other methods in the % Wand View API. % % The format of the NewWandView method is: % % WandView *NewWandView(MagickWand *wand) % % A description of each parameter follows: % % o wand: the wand. % */ static PixelWand ***AcquirePixelsThreadSet(const size_t number_wands) { PixelWand ***pixel_wands; register ssize_t i; size_t number_threads; number_threads=GetOpenMPMaximumThreads(); pixel_wands=(PixelWand ***) AcquireQuantumMemory(number_threads, sizeof(*pixel_wands)); if (pixel_wands == (PixelWand ***) NULL) return((PixelWand ***) NULL); (void) memset(pixel_wands,0,number_threads*sizeof(*pixel_wands)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_wands[i]=NewPixelWands(number_wands); if (pixel_wands[i] == (PixelWand **) NULL) return(DestroyPixelsThreadSet(pixel_wands,number_wands)); } return(pixel_wands); } WandExport WandView *NewWandView(MagickWand *wand) { ExceptionInfo *exception; WandView *wand_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickWandSignature); wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view)); if (wand_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) memset(wand_view,0,sizeof(*wand_view)); wand_view->id=AcquireWandId(); (void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) wand_view->id); wand_view->description=ConstantString("WandView"); wand_view->wand=wand; exception=AcquireExceptionInfo(); wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception); wand_view->extent.width=wand->images->columns; wand_view->extent.height=wand->images->rows; wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width); wand_view->exception=exception; if (wand_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); wand_view->debug=IsEventLogging(); wand_view->signature=MagickWandSignature; return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w W a n d V i e w E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewWandViewExtent() returns a wand view required for all other methods % in the Wand View API. % % The format of the NewWandViewExtent method is: % % WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a extent of % pixel_wands view. % */ WandExport WandView *NewWandViewExtent(MagickWand *wand,const ssize_t x, const ssize_t y,const size_t width,const size_t height) { ExceptionInfo *exception; WandView *wand_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickWandSignature); wand_view=(WandView *) AcquireMagickMemory(sizeof(*wand_view)); if (wand_view == (WandView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) memset(wand_view,0,sizeof(*wand_view)); wand_view->id=AcquireWandId(); (void) FormatLocaleString(wand_view->name,MagickPathExtent,"%s-%.20g", WandViewId,(double) wand_view->id); wand_view->description=ConstantString("WandView"); exception=AcquireExceptionInfo(); wand_view->view=AcquireVirtualCacheView(wand_view->wand->images,exception); wand_view->wand=wand; wand_view->extent.width=width; wand_view->extent.height=height; wand_view->extent.x=x; wand_view->extent.y=y; wand_view->exception=exception; wand_view->pixel_wands=AcquirePixelsThreadSet(wand_view->extent.width); if (wand_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); wand_view->debug=IsEventLogging(); wand_view->signature=MagickWandSignature; return(wand_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t W a n d V i e w D e s c r i p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetWandViewDescription() associates a description with an image view. % % The format of the SetWandViewDescription method is: % % void SetWandViewDescription(WandView *image_view,const char *description) % % A description of each parameter follows: % % o wand_view: the wand view. % % o description: the wand view description. % */ MagickExport void SetWandViewDescription(WandView *wand_view, const char *description) { assert(wand_view != (WandView *) NULL); assert(wand_view->signature == MagickWandSignature); wand_view->description=ConstantString(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetWandViewIterator() iterates over the wand view in parallel and calls % your set method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % The callback signature is: % % MagickBooleanType SetImageViewMethod(ImageView *destination, % const ssize_t y,const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetWandViewIterator method is: % % MagickBooleanType SetWandViewIterator(WandView *destination, % SetWandViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the wand view. % % o set: the set callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType SetWandViewIterator(WandView *destination, SetWandViewMethod set,void *context) { Image *destination_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(destination != (WandView *) NULL); assert(destination->signature == MagickWandSignature); if (set == (SetWandViewMethod) NULL) return(MagickFalse); destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=destination->extent.height-destination->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(destination_image,destination_image,height,1) #endif for (y=destination->extent.y; y < (ssize_t) destination->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->extent.x, y,destination->extent.width,1,destination->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } if (set(destination,y,id,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], pixels); pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_SetWandViewIterator) #endif proceed=SetImageProgress(destination_image,destination->description, progress++,destination->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferWandViewIterator() iterates over two wand views in parallel and % calls your transfer method for each scanline of the view. The source pixel % extent is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination wand view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % The callback signature is: % % MagickBooleanType TransferImageViewMethod(const WandView *source, % WandView *destination,const ssize_t y,const int thread_id, % void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferWandViewIterator method is: % % MagickBooleanType TransferWandViewIterator(WandView *source, % WandView *destination,TransferWandViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o destination: the destination wand view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType TransferWandViewIterator(WandView *source, WandView *destination,TransferWandViewMethod transfer,void *context) { Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (transfer == (TransferWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; destination_image=destination->wand->images; status=SetImageStorageClass(destination_image,DirectClass, destination->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,destination_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const Quantum *magick_restrict pixels; register ssize_t x; register Quantum *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); if (destination_pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelSetQuantumPixel(destination->image,destination_pixels, destination->pixel_wands[id][x]); destination_pixels+=GetPixelChannels(destination->image); } if (transfer(source,destination,y,id,context) == MagickFalse) status=MagickFalse; destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->extent.x,y,destination->extent.width,1, destination->exception); for (x=0; x < (ssize_t) destination->extent.width; x++) { PixelGetQuantumPixel(destination->image,destination->pixel_wands[id][x], destination_pixels); destination_pixels+=GetPixelChannels(destination->image); } sync=SyncCacheViewAuthenticPixels(destination->view,destination->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_TransferWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e W a n d V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdateWandViewIterator() iterates over the wand view in parallel and calls % your update method for each scanline of the view. The pixel extent is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % The callback signature is: % % MagickBooleanType UpdateImageViewMethod(WandView *source,const ssize_t y, % const int thread_id,void *context) % % Use this pragma if the view is not single threaded: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdateWandViewIterator method is: % % MagickBooleanType UpdateWandViewIterator(WandView *source, % UpdateWandViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source wand view. % % o update: the update callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType UpdateWandViewIterator(WandView *source, UpdateWandViewMethod update,void *context) { Image *source_image; MagickBooleanType status; MagickOffsetType progress; #if defined(MAGICKCORE_OPENMP_SUPPORT) size_t height; #endif ssize_t y; assert(source != (WandView *) NULL); assert(source->signature == MagickWandSignature); if (update == (UpdateWandViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; status=SetImageStorageClass(source_image,DirectClass,source->exception); if (status == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) height=source->extent.height-source->extent.y; #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,source_image,height,1) #endif for (y=source->extent.y; y < (ssize_t) source->extent.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register ssize_t x; register Quantum *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->extent.x,y, source->extent.width,1,source->exception); if (pixels == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source->extent.width; x++) { PixelSetQuantumPixel(source->image,pixels,source->pixel_wands[id][x]); pixels+=GetPixelChannels(source->image); } if (update(source,y,id,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) source->extent.width; x++) { PixelGetQuantumPixel(source->image,source->pixel_wands[id][x],pixels); pixels+=GetPixelChannels(source->image); } sync=SyncCacheViewAuthenticPixels(source->view,source->exception); if (sync == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_UpdateWandViewIterator) #endif proceed=SetImageProgress(source_image,source->description,progress++, source->extent.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); }
benchmark.c
/** * @file benchmark.c * @brief benchmark the amount of time saved by parallel program * @note compile with '--std=c99' * @author Lumin <cdluminate@gmail.com> */ #define USE_CUDA #undef USE_CUDA #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <omp.h> #include <sys/time.h> // high precision timer, gettimeofday() #include <assert.h> #ifdef USE_CUDA #include "cudabench.h" // cuda benchmarks #endif double * new_vector (size_t len); void fill_vector (double * v, size_t len, double val); void dump_vector (double * v, size_t size); void del_vector (double * v); /** * @brief flag, set 1 to dump all debug information */ int debug = 0; /** * @brief vector length used in L-1 benchmarks */ #define VLEN 1024*1024*16 /** * @brief matrix size used in L-2 benchmarks */ #define MVLEN 1024*4 /** * @brief matrix size used in L-3 benchmarks */ #define MMLEN 256 /** * @brief IMLEN image size, KLEN kernel size, FLEN(IM,K) feature map size */ #define IMLEN 512 #define KLEN 17 #define FLEN(im,k) ((im-k+1)) /** * @brief helper function for tester */ void check_vector_eq (const double * src, const double * dest, size_t n) { for (size_t i = 0; i < n; i++) { if (fabs(src[i] - dest[i]) > 1e-5) { fprintf (stderr, "E: check_vector_eq failure at element %ld\n", i); return; } } } /** * @breif dcopy, L-1 BLAS, serial */ void dcopy_serial (const double * src, double * dest, size_t n) { for (long i = 0; i < n; i++) dest[i] = src[i]; return; } /** * @brief dcopy, L-1 BLAS, parallel */ void dcopy_parallel (const double * src, double * dest, size_t n) { #pragma omp parallel for shared(src, dest) for (long i = 0; i < n; i++) dest[i] = src[i]; return; } /** * @brief tester for dcopy */ void test_dcopy (void (* dcopy)(const double * src, double * dest, size_t n)) { printf("[ .. ] test dcopy@%p\n", dcopy); // short vector double * A = new_vector(128); double * C = new_vector(128); fill_vector(A, 128, 1.); fill_vector(C, 128, 0.); dcopy (A, C, 128); check_vector_eq (A, C, 128); del_vector(A); del_vector(C); // long vector double * B = new_vector(65536); double * D = new_vector(65536); fill_vector(B, 65536, 2.); fill_vector(D, 65536, 0.); dcopy (B, D, 65536); check_vector_eq (B, D, 65536); del_vector (B); del_vector (D); printf("[ OK ] test dcopy@%p\n", dcopy); } /** * @brief dasum, L-1 BLAS, serial */ double dasum_serial (const double * a, size_t n) { double ret = 0.; for (long i = 0; i < n; i++) { ret += (a[i]>0.)?(a[i]):(-a[i]); //if (0 == i % 1000000) printf (" iter %ld, n = %lf\n", i, ret); // debug } return ret; } /** * @brief dasum, L-1 BLAS, parallel */ double dasum_parallel (const double * a, size_t n) { double ret = 0.; #pragma omp parallel for reduction (+:ret) for (long i = 0; i < n; i++) ret += (a[i]>0.)?(a[i]):(-a[i]); return ret; } /** * @brief tester for dasum */ void test_dasum (double (* dasum)(const double * a, size_t n)) { printf("[ .. ] test dasum@%p\n", dasum); // long vector double * A = new_vector(1280); fill_vector(A, 1280, 1.); //dump_vector (A, 128); double ret = dasum (A, 1280); //printf ("%lf\n", ret); assert(fabs(ret - 1280.) < 1e-5); del_vector (A); // short vector // FIXME: BUG: wrong result dasum_cuda when size 128 double * B = new_vector(128); fill_vector(B, 128, 1.0); ret = dasum(B, 128); assert(fabs(ret - 128.) < 1e-5); del_vector (B); // another long vector double * C = new_vector(1200); fill_vector(C, 1200, 1.); //dump_vector (A, 128); ret = dasum (C, 1200); //printf ("%lf\n", ret); assert(fabs(ret - 1200.) < 1e-5); del_vector (C); printf("[ OK ] test dasum@%p\n", dasum); } /** * @brief dscal, L-1 BLAS, serial */ void dscal_serial (double * x, const double a, size_t n) { for (size_t i = 0; i < n; i++) x[i] *= a; } /** * @brief dscal, L-1 BLAS, parallel */ void dscal_parallel (double * x, const double a, size_t n) { #pragma omp parallel for shared(x) for (size_t i = 0; i < n; i++) x[i] *= a; } /** * @brief ddot, L-1 BLAS, serial */ double ddot_serial (const double * a, const double * b, size_t n) { double ret = 0.; for (long i = 0; i < n; i++) ret += a[i] * b[i]; return ret; } /** * @brief ddot, L-1 BLAS, parallel */ double ddot_parallel (const double * a, const double * b, size_t n) { double ret = 0.; #pragma omp parallel for reduction (+:ret) for (long i = 0; i < n; i++) ret += a[i] * b[i]; return ret; } /** * @brief daxpby, L-1 BLAS Extension, serial */ void daxpby_serial (const double * x, const double a, double * y, const double b, size_t n) { // a x + b y -> y for (long i = 0; i < n; i++) y[i] += a * x[i] + b * y[i]; } /** * @brief daxpby, L-1 BLAS Extension, parallel */ void daxpby_parallel (const double * x, const double a, double * y, const double b, size_t n) { // a x + b y -> y #pragma omp parallel for shared(x, y) for (long i = 0; i < n; i++) y[i] += a * x[i] + b * y[i]; } /** * @brief dgemv, L-2 BLAS, serial * @f[ a x * b y -> dest @f] */ void dgemv_serial (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { // note, x is matrix ! for (size_t i = 0; i < n; i++) { // for each row of x dest[i] = y[i]; for (size_t j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; } } } /** * @brief dgemv, L-2 BLAS, parallel * @f[ a x * b y -> dest @f] */ void dgemv_parallel (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { size_t j = 0; #pragma omp parallel for shared(x, y, dest) private(j) for (size_t i = 0; i < n; i++) { // for each row of x dest[i] = y[i]; for (j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; } } } /** * @brief dgemv, L-2 BLAS, parallel version 2 * @f[ a x * b y -> dest @f] */ void dgemv_parallelv2 (const double * x, const double a, const double * y, const double b, size_t n, double * dest) { size_t j = 0; size_t i = 0; dcopy_parallel(y, dest, n); #pragma omp parallel for collapse(2) shared(x, y, dest) private(i,j) for (i = 0; i < n; i++) { // for each row of x for (j = 0; j < n; j++) { // for each column of y dest[i] += a * *(x+(i*n)+j) * b * y[j]; }} } /** * @brief dgemm, L-3 BLAS, serial version * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_serial (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } } } } /** * @brief dgemm, L-3 BLAS, parallel version * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_parallel (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; #pragma omp parallel for collapse(2) shared(A, B) private(nn) // Note, dynamic scheduler seems to reduce performance here for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } }} } /** * @brief dgemm, L-3 BLAS, parallel version 2 * @f[ A_{m x n} * B_{n x k} -> C_{m x k} @f] */ void dgemm_parallelv2 (const double * A, const double * B, size_t m, size_t n, size_t k, double * C) { size_t mm = 0, nn = 0, kk = 0; #pragma omp parallel for shared(A, B) private(kk,nn) for (mm = 0; mm < m; mm++) { for (kk = 0; kk < k; kk++) { *(C+mm*k+kk) = 0; for (nn = 0; nn < n; nn++) { *(C+mm*k+kk) += *(A+mm*n+nn) * *(B+nn*k+kk); } } } } /** * @brief 2-D convolution in serial * (Computer Vision Convolution, not Signal Convolution) * @param[in] smap source map * @param[in] dmap destination map * @param[in] m smap size * @param[in] k kernel size * @note no padding */ void conv2_serial (const double * smap, const double * kernel, size_t ssize, size_t ksize, double * dmap) { for (unsigned int i = 0; i < FLEN(ssize,ksize); i++) { // for each row of output map for (unsigned int j = 0; j < FLEN(ssize,ksize); j++) { // for each column of output map // element wise mult, smap part with kernel double sum = 0.; for (unsigned int m = 0; m < ksize; m++) { for (unsigned int n = 0; n < ksize; n++) { sum += kernel[m*ksize +n] * smap[(i+m)*ssize + j+n]; }} // finish (i,j) of output feature map dmap[i*FLEN(ssize,ksize)+j] = sum; }} return; } /** * @brief 2-D convolution in parallel * (Computer Vision Convolution, not Signal Convolution) */ void conv2_parallel (const double * smap, const double * kernel, size_t ssize, size_t ksize, double * dmap) { double sum = 0.; #pragma omp parallel for collapse(2) shared(smap,kernel,dmap) private(sum) for (unsigned int i = 0; i < FLEN(ssize,ksize); i++) { // for each row of output map for (unsigned int j = 0; j < FLEN(ssize,ksize); j++) { // for each column of output map // element wise mult, smap part with kernel sum = 0.; for (unsigned int m = 0; m < ksize; m++) { for (unsigned int n = 0; n < ksize; n++) { sum += kernel[m*ksize +n] * smap[(i+m)*ssize + j+n]; }} // finish (i,j) of output feature map dmap[i*FLEN(ssize,ksize)+j] = sum; }} return; } /** * @brief tell user the time difference in second. * @param tvs the starting time stamp. * @param tve the ending timp stamp. * @see sys/time.h, gettimeofday(2) */ void timediff (struct timeval tvs, struct timeval tve, char * msg) { long diff_sec = tve.tv_sec - tvs.tv_sec; long diff_usec = tve.tv_usec - tvs.tv_usec; double dtime = diff_sec + diff_usec/1e+6; fprintf (stdout, "I: [%s] time cost is %1.6f seconds.\n", (msg==NULL)?"":msg, dtime); } /** * @brief find the time difference in second */ double gettimediff (struct timeval tvs, struct timeval tve) { return ((tve.tv_sec - tvs.tv_sec) + (tve.tv_usec - tvs.tv_usec)/1e+6); } /** * @brief print a spliting line on screen */ void hrulefill (void) { for (int i = 0; i < 80; i++) fprintf (stdout, "-"); fprintf (stdout, "\n"); return; } /** * @brief dump a vector to screen */ void dump_vector (double * v, size_t size) { for (size_t i = 0; i < size; i++) fprintf (stdout, " %.3lf", v[i]); fprintf (stdout, "\n"); return; } /** * @brief dump a matrix to screen */ void dump_matrix (double * m, size_t row, size_t col) { for (size_t i = 0; i < row; i++) { for (size_t j = 0; j < col; j++) fprintf (stdout, " %.3lf", m[i*col+j]); fprintf (stdout, "\n"); } return; } /** * @brief allocate a vector in double * @note values of vector not initialized on allocation. */ double * new_vector (size_t len) { double * ret = (double *)malloc(len*sizeof(double)); assert(ret != NULL); return ret; } /** * @brief delete a vector in double */ void del_vector (double * v) { free(v); } /** * @brief fill a double vector with a value */ void fill_vector (double * v, size_t len, double val) { for (size_t i = 0; i < len; i++) v[i] = val; return; } /** * @brief allocate a double matrix */ double * new_matrix (size_t row, size_t col) { double * ret = (double *)malloc(row*col*sizeof(double)); assert(ret != NULL); return ret; } /** * @brief delete a matrix in double */ void del_matrix (double * m) { free(m); } /** * @brief fill a double matrix with a value */ void fill_matrix (double * m, size_t row, size_t col, double val) { for (size_t i = 0; i < row; i++) for (size_t j = 0; j < col; j++) m[i*col+j] = val; return; } // benchmark for dcopy void benchmark_dcopy (void (* dcopy)(const double * src, double * dest, size_t n)) { struct timeval tvs; struct timeval tve; long sizes[8] ={ 1, 16, 256, 4096, 65536, 1048576, 16777216, 33554432 }; double results[8]={ 0.,0., 0., 0., 0., 0., 0., 0. }; // print table header for (int i = 0; i < 8; i++) printf ("|%8ld", sizes[i]); printf ("|\n"); for (int i = 0; i < 8; i++) { // prepare memory for data double * A = new_vector(sizes[i]); double * C = new_vector(sizes[i]); fill_vector (A, sizes[i], 1.); fill_vector (C, sizes[i], 0.); // calculate gettimeofday (&tvs, NULL); dcopy (A, C, sizes[i]); gettimeofday (&tve, NULL); check_vector_eq (A, C, sizes[i]); // store result results[i] = gettimediff (tvs, tve); del_vector (A); del_vector (C); } // print results for (int i = 0; i < 8; i++) printf ("|%8.6lf", results[i]); printf ("|\n"); } // benchmark for dasum void benchmark_dasum (double (* dasum)(const double * src, size_t n)) { struct timeval tvs; struct timeval tve; long sizes[8] ={ 1, 16, 256, 4096, 65536, 1048576, 16777216, 33554432 }; double results[8]={ 0.,0., 0., 0., 0., 0., 0., 0. }; // print table header for (int i = 0; i < 8; i++) printf ("|%8ld", sizes[i]); printf ("|\n"); for (int i = 0; i < 8; i++) { // prepare memory for data double * A = new_vector(sizes[i]); fill_vector (A, sizes[i], 1.); // calculate gettimeofday (&tvs, NULL); (void) dasum (A, sizes[i]); // discard the summary gettimeofday (&tve, NULL); // store result results[i] = gettimediff (tvs, tve); del_vector (A); } // print results for (int i = 0; i < 8; i++) printf ("|%8.6lf", results[i]); printf ("|\n"); } // benchmark for ddot void benchmark_ddot (double (* ddot)(const double * a, const double * b, size_t n)) { struct timeval tvs; struct timeval tve; long sizes[8] ={ 1, 16, 256, 4096, 65536, 1048576, 16777216, 33554432 }; double results[8]={ 0.,0., 0., 0., 0., 0., 0., 0. }; // print table header for (int i = 0; i < 8; i++) printf ("|%8ld", sizes[i]); printf ("|\n"); for (int i = 0; i < 8; i++) { // prepare memory for data double * A = new_vector(sizes[i]); double * B = new_vector(sizes[i]); fill_vector (A, sizes[i], 1.); fill_vector (B, sizes[i], 1.); // calculate gettimeofday (&tvs, NULL); (void) ddot (A, B, sizes[i]); // discard the summary gettimeofday (&tve, NULL); // store result results[i] = gettimediff (tvs, tve); del_vector (A); del_vector (B); } // print results for (int i = 0; i < 8; i++) printf ("|%8.6lf", results[i]); printf ("|\n"); } // benchmark for dscal void benchmark_dscal (void (* dscal)(double * x, const double a, size_t n)) { struct timeval tvs; struct timeval tve; long sizes[8] ={ 1, 16, 256, 4096, 65536, 1048576, 16777216, 33554432 }; double results[8]={ 0.,0., 0., 0., 0., 0., 0., 0. }; // print table header for (int i = 0; i < 8; i++) printf ("|%8ld", sizes[i]); printf ("|\n"); for (int i = 0; i < 8; i++) { // prepare memory for data double * A = new_vector(sizes[i]); fill_vector (A, sizes[i], 1.); // calculate gettimeofday (&tvs, NULL); dscal (A, 0.5, sizes[i]); // discard the summary gettimeofday (&tve, NULL); // store result results[i] = gettimediff (tvs, tve); del_vector (A); } // print results for (int i = 0; i < 8; i++) printf ("|%8.6lf", results[i]); printf ("|\n"); } /** * @brief Lumin's benchmark */ int main (int argc, char ** argv, char ** envp) { fprintf (stdout, "Lumin's serial/parallel/cuda benchmark\nI: initializing ... "); fflush(stdout); struct timeval tvs; // tv_s, for starting point struct timeval tve; // tv_e, for ending point // init times struct timeval tvi; // tv_init struct timeval tvt; // tv_terminate gettimeofday(&tvi, NULL); fprintf(stdout, "[OK]\n"); hrulefill(); { // start unit tests test_dcopy(dcopy_serial); test_dcopy(dcopy_parallel); #ifdef USE_CUDA test_dcopy(dcopy_cuda); #endif // USE_CUDA test_dasum(dasum_serial); test_dasum(dasum_parallel); #ifdef USE_CUDA test_dasum(dasum_cuda); #endif } // end unit tests hrulefill(); { // copy test printf ("I: [dcopy_serial] test series\n"); benchmark_dcopy (dcopy_serial); printf ("I: [dcopy_parallel] test series\n"); benchmark_dcopy (dcopy_parallel); #ifdef USE_CUDA printf ("I: [dcopy_cuda] test series\n"); benchmark_dcopy (dcopy_cuda); #endif // USE_CUDA } hrulefill(); { // asum test printf ("I: [dasum_serial] test series\n"); benchmark_dasum (dasum_serial); printf ("I: [dasum_parallel] test series\n"); benchmark_dasum (dasum_parallel); #ifdef USE_CUDA printf ("I: [dasum_cuda] test series\n"); benchmark_dasum (dasum_cuda); #endif // USE_CUDA } hrulefill(); { // dot test // FIXME: add unit tests for ddot // run benchmarks printf ("I: [ddot_serial] test series\n"); benchmark_ddot (ddot_serial); printf ("I: [ddot_parallel] test series\n"); benchmark_ddot (ddot_parallel); } hrulefill(); { // scal test // FIXME: add unit tests // run benchmarks printf ("I: [dscal_serial] test series\n"); benchmark_dscal (dscal_serial); printf ("I: [dscal_parallel] test series\n"); benchmark_dscal (dscal_parallel); #ifdef USE_CUDA printf ("I: [dscal_cuda] test series\n"); benchmark_dscal (dscal_cuda); #endif // USE_CUDA } hrulefill(); { // axpby test // data double * A = new_vector(VLEN); double * C = new_vector(VLEN); fill_vector(A, VLEN, 1.); fill_vector(C, VLEN, 1.); // serial gettimeofday(&tvs, NULL); daxpby_serial (A, 0.5, C, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "daxpby in serial"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // parallel gettimeofday(&tvs, NULL); daxpby_parallel (A, 0.5, C, 0.5, VLEN); gettimeofday(&tve, NULL); timediff (tvs, tve, "daxpby in parallel"); if (debug) dump_vector(A, VLEN); if (debug) dump_vector(C, VLEN); // post-test del_vector(A); del_vector(C); } hrulefill(); { // gemv test // data double * M = new_matrix(MVLEN, MVLEN); double * A = new_vector(MVLEN); double * Y = new_vector(MVLEN); fill_matrix(M, MVLEN, MVLEN, 1.); fill_vector(A, MVLEN, 1.); fill_vector(Y, MVLEN, 1.); if (debug) dump_matrix(M, MVLEN, MVLEN); if (debug) dump_vector(A, MVLEN); // serial gettimeofday(&tvs, NULL); dgemv_serial (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in serial"); if (debug) dump_vector(Y, MVLEN); // parallel gettimeofday(&tvs, NULL); dgemv_parallel (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in parallel"); if (debug) dump_vector(Y, MVLEN); // parallelv2 gettimeofday(&tvs, NULL); dgemv_parallelv2 (M, 1., A, 1., MVLEN, Y); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemv in parallelv2"); if (debug) dump_vector(Y, MVLEN); // post-test del_matrix(M); del_vector(A); del_vector(Y); } hrulefill(); { // gemm // data double * X = new_matrix(MMLEN, MMLEN); double * Y = new_matrix(MMLEN, MMLEN); double * Z = new_matrix(MMLEN, MMLEN); fill_matrix(X, MMLEN, MMLEN, 1.); fill_matrix(Y, MMLEN, MMLEN, 1.); fill_matrix(Z, MMLEN, MMLEN, 0.); if (debug) dump_matrix(X, MMLEN, MMLEN); if (debug) dump_matrix(Y, MMLEN, MMLEN); // serial gettimeofday(&tvs, NULL); dgemm_serial (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in serial"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // parallel gettimeofday(&tvs, NULL); dgemm_parallel (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in parallel"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // parallel v2 gettimeofday(&tvs, NULL); dgemm_parallelv2 (X, Y, MMLEN, MMLEN, MMLEN, Z); gettimeofday(&tve, NULL); timediff (tvs, tve, "dgemm in parallelv2"); if (debug) dump_matrix(Z, MMLEN, MMLEN); // post-test del_matrix(X); del_matrix(Y); del_matrix(Z); } hrulefill(); { // convolution // data double * image = new_matrix(IMLEN, IMLEN); double * kernel = new_matrix(KLEN, KLEN); double * fmap = new_matrix(FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); fill_matrix(image, IMLEN, IMLEN, 1.); fill_matrix(kernel, KLEN, KLEN, 1.); fill_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN), 0.); if (debug) dump_matrix(image, IMLEN, IMLEN); if (debug) dump_matrix(kernel, KLEN, KLEN); // serial gettimeofday(&tvs, NULL); conv2_serial (image, kernel, IMLEN, KLEN, fmap); gettimeofday(&tve, NULL); timediff (tvs, tve, "conv2 in serial"); if (debug) dump_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); // parallel gettimeofday(&tvs, NULL); conv2_parallel (image, kernel, IMLEN, KLEN, fmap); gettimeofday(&tve, NULL); timediff (tvs, tve, "conv2 in parallel"); if (debug) dump_matrix(fmap, FLEN(IMLEN,KLEN), FLEN(IMLEN,KLEN)); // post-test del_matrix(image); del_matrix(kernel); del_matrix(fmap); } hrulefill(); // how long all the benchmarks take gettimeofday(&tvt, NULL); timediff(tvi, tvt, "All benchmark"); return 0; }
cg.20190406_morph.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "globals.h" #include "randdp.h" #include "timers.h" #include <omp.h> //--------------------------------------------------------------------- #define CACHE_LINE_SIZE_PAD 128 #define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int) #define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double) /* common / main_int_mem / */ static int colidx[NZ]; static int rowstr[NA+1]; static int iv[NA]; static int arow[NA]; static int acol[NAZ]; /* common / main_flt_mem / */ static double aelt[NAZ]; static double a[NZ]; static double x[NA+2]; static double z[NA+2]; static double p[NA+2]; static double q[NA+2]; static double r[NA+2]; /* common / partit_size / */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /urando/ */ static double amult; static double tran; /* common /timers/ */ static logical timeron; //--------------------------------------------------------------------- //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]); static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift); static void sprnvc(int n, int nz, int nn1, double v[], int iv[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); //--------------------------------------------------------------------- int main(int argc, char *argv[]) { omp_set_num_threads(omp_get_num_procs()); int i, j, k, it; double zeta; double rnorm; double norm_temp1, norm_temp2; double t, mflops, tmax; //char Class; logical verified; double zeta_verify_value, epsilon, err; char *t_names[T_last]; for (i = 0; i < T_last; i++) { timer_clear(i); } timer_start(T_init); firstrow = 0; lastrow = NA-1; firstcol = 0; lastcol = NA-1; zeta_verify_value = VALID_RESULT; printf("\nCG start...\n\n"); printf(" Size: %11d\n", NA); printf(" Iterations: %5d\n", NITER); printf("\n"); naa = NA; nzz = NZ; //--------------------------------------------------------------------- // Inialize random number generator //--------------------------------------------------------------------- tran = 314159265.0; amult = 1220703125.0; zeta = randlc(&tran, amult); //--------------------------------------------------------------------- // //--------------------------------------------------------------------- makea(naa, nzz, a, colidx, rowstr, firstrow, lastrow, firstcol, lastcol, arow, (int (*)[NONZER+1])(void*)acol, (double (*)[NONZER+1])(void*)aelt, iv); //--------------------------------------------------------------------- // Note: as a result of the above call to makea: // values of j used in indexing rowstr go from 0 --> lastrow-firstrow // values of colidx which are col indexes go from firstcol --> lastcol // So: // Shift the col index vals from actual (firstcol --> lastcol ) // to local, i.e., (0 --> lastcol-firstcol) //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(i,j,k) { #pragma omp for nowait for (j = 0; j < lastrow - firstrow + 1; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol; } } //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp for nowait for (i = 0; i < NA+1; i++) { x[i] = 1.0; } #pragma omp for nowait for (j = 0; j < lastcol - firstcol + 1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = 0.0; p[j] = 0.0; } } zeta = 0.0; //--------------------------------------------------------------------- //----> // Do one iteration untimed to init all code and data page tables //----> (then reinit, start timing, to niter its) //--------------------------------------------------------------------- for (it = 1; it <= 1; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j] * z[j]; norm_temp2 = norm_temp2 + z[j] * z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of do one iteration untimed //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(i) for (i = 0; i < NA+1; i++) { x[i] = 1.0; } zeta = 0.0; timer_stop(T_init); printf(" Initialization time = %15.3f seconds\n", timer_read(T_init)); timer_start(T_bench); //--------------------------------------------------------------------- //----> // Main Iteration for inverse power method //----> //--------------------------------------------------------------------- for (it = 1; it <= NITER; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- if (timeron) timer_start(T_conj_grad); conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); if (timeron) timer_stop(T_conj_grad); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j]*z[j]; norm_temp2 = norm_temp2 + z[j]*z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); zeta = SHIFT + 1.0 / norm_temp1; if (it == 1) printf("\n iteration ||r|| zeta\n"); printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of main iter inv pow meth timer_stop(T_bench); //--------------------------------------------------------------------- // End of timed section //--------------------------------------------------------------------- t = timer_read(T_bench); printf("\nComplete...\n"); epsilon = 1.0e-10; err = fabs(zeta - zeta_verify_value) / zeta_verify_value; if (err <= epsilon) { verified = true; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.13E\n", zeta); printf(" Error is %20.13E\n", err); } else { verified = false; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.13E\n", zeta); printf(" The correct zeta is %20.13E\n", zeta_verify_value); } printf("\n\nExecution time : %lf seconds\n\n", t); return 0; } //--------------------------------------------------------------------- // Floaging point arrays here are named as in spec discussion of // CG algorithm //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm) { int j, k; int cgit, cgitmax = 25; double d, sum, rho, rho0, alpha, beta; rho = 0.0; //--------------------------------------------------------------------- // Initialize the CG algorithm: //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < naa+1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = x[j]; p[j] = r[j]; } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp for reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j]*r[j]; } } //--------------------------------------------------------------------- //----> // The conj grad iteration loop //----> //--------------------------------------------------------------------- for (cgit = 1; cgit <= cgitmax; cgit++) { //--------------------------------------------------------------------- // q = A.p // The partition submatrix-vector multiply: use workspace w //--------------------------------------------------------------------- // // NOTE: this version of the multiply is actually (slightly: maybe %5) // faster on the sp2 on 16 nodes than is the unrolled-by-2 version // below. On the Cray t3d, the reverse is true, i.e., the // unrolled-by-two version is some 10% faster. // The unrolled-by-8 version below is significantly faster // on the Cray t3d - overall speed of code is 1.5 times faster. rho0 = rho; d = 0.0; rho = 0.0; #pragma omp parallel default(shared) { #pragma omp for private(sum, j, k) for (j = 0; j < lastrow - firstrow + 1; j++) { sum = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k]*p[colidx[k]]; } q[j] = sum; } /* #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { double sum1 = 0.0; double sum2 = 0.0; int start_idx = rowstr[j]; int end_idx = rowstr[j+1]; int remainder = (end_idx-start_idx)%2; if(remainder == 1){ sum1 = sum1 + a[start_idx]*p[colidx[start_idx]]; } for (k = start_idx+remainder; k < end_idx; k+=2) { sum1 = sum1 + a[k]*p[colidx[k]]; sum2 = sum2 + a[k+1]*p[colidx[k+1]]; } q[j] = sum1+sum2; } */ /* #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { double sum0 = 0.0; double sum1 = 0.0; double sum2 = 0.0; double sum3 = 0.0; double sum4 = 0.0; double sum5 = 0.0; double sum6 = 0.0; double sum7 = 0.0; int start_idx = rowstr[j]; int end_idx = rowstr[j+1]; int remainder = (end_idx-start_idx)%8; for (k = start_idx; k < start_idx+remainder; k++){ sum0 = sum0 + a[k]*p[colidx[k]]; } for (k = start_idx+remainder; k < end_idx; k+=8) { sum0 = sum0 + a[k]*p[colidx[k]]; sum1 = sum1 + a[k+1]*p[colidx[k+1]]; sum2 = sum2 + a[k+2]*p[colidx[k+2]]; sum3 = sum3 + a[k+3]*p[colidx[k+3]]; sum4 = sum4 + a[k+4]*p[colidx[k+4]]; sum5 = sum5 + a[k+5]*p[colidx[k+5]]; sum6 = sum6 + a[k+6]*p[colidx[k+6]]; sum7 = sum7 + a[k+7]*p[colidx[k+7]]; } q[j] = sum0+sum1+sum2+sum3+sum4+sum5+sum6+sum7; } */ /* #pragma omp for private(j,k,sum) for (j = 0; j <= lastrow-firstrow+1; j++) { int iresidue; int i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 8; sum = 0.0; for (k = i; k <= i+iresidue-1; k++) { sum = sum + a[k] * p[colidx[k]]; } for (k = i+iresidue; k <= rowstr[j+1]-8; k += 8) { sum = sum + a[k ] * p[colidx[k ]] + a[k+1] * p[colidx[k+1]] + a[k+2] * p[colidx[k+2]] + a[k+3] * p[colidx[k+3]] + a[k+4] * p[colidx[k+4]] + a[k+5] * p[colidx[k+5]] + a[k+6] * p[colidx[k+6]] + a[k+7] * p[colidx[k+7]]; } q[j] = sum; } */ //--------------------------------------------------------------------- // Obtain p.q //--------------------------------------------------------------------- #pragma omp for private(j) reduction(+:d) for (j = 0; j < lastcol - firstcol + 1; j++) { d = d + p[j]*q[j]; } //--------------------------------------------------------------------- // Obtain alpha = rho / (p.q) //--------------------------------------------------------------------- #pragma omp single alpha = rho0 / d; //--------------------------------------------------------------------- // Obtain z = z + alpha*p // and r = r - alpha*q //--------------------------------------------------------------------- #pragma omp for private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { z[j] = z[j] + alpha*p[j]; r[j] = r[j] - alpha*q[j]; } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp for private(j) reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j]*r[j]; } //--------------------------------------------------------------------- // Obtain beta: //--------------------------------------------------------------------- #pragma omp single beta = rho / rho0; //--------------------------------------------------------------------- // p = r + beta*p //--------------------------------------------------------------------- #pragma omp for private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { p[j] = r[j] + beta*p[j]; } } } // end of do cgit=1,cgitmax //--------------------------------------------------------------------- // Compute residual norm explicitly: ||r|| = ||x - A.z|| // First, form A.z // The partition submatrix-vector multiply //--------------------------------------------------------------------- /* for (j = 0; j < lastrow - firstrow + 1; j++) { printf("j = %d, colidx[%d] = %d, z[%d] = %lf\n", j, j, colidx[j], colidx[j], z[colidx[j]][0]); } */ double d_tmp; #pragma omp parallel default(shared) private(j, d, d_tmp) shared(sum) { sum = 0.0; #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { d = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { d = d + a[k]*z[colidx[k]]; } r[j] = d; } //--------------------------------------------------------------------- // At this point, r contains A.z //--------------------------------------------------------------------- #pragma omp for reduction(+:sum) for (j = 0; j < lastcol-firstcol+1; j++) { d_tmp = x[j] - r[j]; sum = sum + d_tmp*d_tmp; } } *rnorm = sqrt(sum); } //--------------------------------------------------------------------- // generate the test problem for benchmark 6 // makea generates a sparse matrix with a // prescribed sparsity distribution // // parameter type usage // // input // // n i number of cols/rows of matrix // nz i nonzeros as declared array size // rcond r*8 condition number // shift r*8 main diagonal shift // // output // // a r*8 array for nonzeros // colidx i col indices // rowstr i row pointers // // workspace // // iv, arow, acol i // aelt r*8 //--------------------------------------------------------------------- static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]) { int iouter, ivelt, nzv, nn1; int ivc[NONZER+1]; double vc[NONZER+1]; //--------------------------------------------------------------------- // nonzer is approximately (int(sqrt(nnza /n))); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // nn1 is the smallest power of two not less than n //--------------------------------------------------------------------- nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); //--------------------------------------------------------------------- // Generate nonzero positions and save for the use in sparse. //--------------------------------------------------------------------- for (iouter = 0; iouter < n; iouter++) { nzv = NONZER; sprnvc(n, nzv, nn1, vc, ivc); vecset(n, vc, ivc, &nzv, iouter+1, 0.5); arow[iouter] = nzv; for (ivelt = 0; ivelt < nzv; ivelt++) { acol[iouter][ivelt] = ivc[ivelt] - 1; aelt[iouter][ivelt] = vc[ivelt]; } } //--------------------------------------------------------------------- // ... make the sparse matrix from list of elements with duplicates // (iv is used as workspace) //--------------------------------------------------------------------- sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol, aelt, firstrow, lastrow, iv, RCOND, SHIFT); } //--------------------------------------------------------------------- // rows range from firstrow to lastrow // the rowstr pointers are defined for nrows = lastrow-firstrow+1 values //--------------------------------------------------------------------- static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift) { int nrows; //--------------------------------------------------- // generate a sparse matrix from a list of // [col, row, element] tri //--------------------------------------------------- int i, j, j1, j2, nza, k, kk, nzrow, jcol; double size, scale, ratio, va; logical cont40; //--------------------------------------------------------------------- // how many rows of result //--------------------------------------------------------------------- nrows = lastrow - firstrow + 1; //--------------------------------------------------------------------- // ...count the number of triples in each row //--------------------------------------------------------------------- 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; } }
GB_unaryop__ainv_uint16_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_uint16_fp32 // op(A') function: GB_tran__ainv_uint16_fp32 // C type: uint16_t // A type: float // cast: uint16_t cij ; GB_CAST_UNSIGNED(cij,aij,16) // unaryop: cij = -aij #define GB_ATYPE \ float #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ uint16_t z ; GB_CAST_UNSIGNED(z,x,16) ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_UINT16 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_uint16_fp32 ( uint16_t *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_uint16_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
shaman_openmp.h
#pragma once // Requires openMP 4.0+ to get reductions on user defined types #ifdef _OPENMP // + #pragma omp declare reduction(+:Sfloat : omp_out=omp_in+omp_out) initializer(omp_priv=Sfloat(0.f)) #pragma omp declare reduction(+:Sdouble: omp_out=omp_in+omp_out) initializer(omp_priv=Sdouble(0.)) #pragma omp declare reduction(+:Slong_double: omp_out=omp_in+omp_out) initializer(omp_priv=Slong_double(0.L)) // - #pragma omp declare reduction(-:Sfloat : omp_out=omp_in+omp_out) initializer(omp_priv=Sfloat(0.f)) #pragma omp declare reduction(-:Sdouble: omp_out=omp_in+omp_out) initializer(omp_priv=Sdouble(0.)) #pragma omp declare reduction(-:Slong_double: omp_out=omp_in+omp_out) initializer(omp_priv=Slong_double(0.L)) // * #pragma omp declare reduction(*:Sfloat : omp_out=omp_in*omp_out) initializer(omp_priv=Sfloat(1.f)) #pragma omp declare reduction(*:Sdouble: omp_out=omp_in*omp_out) initializer(omp_priv=Sdouble(1.)) #pragma omp declare reduction(*:Slong_double: omp_out=omp_in*omp_out) initializer(omp_priv=Slong_double(1.L)) // max #pragma omp declare reduction(max:Sfloat : omp_out=Sstd::max(omp_in,omp_out)) initializer(omp_priv=Sfloat(std::numeric_limits<float>::lowest())) #pragma omp declare reduction(max:Sdouble : omp_out=Sstd::max(omp_in,omp_out)) initializer(omp_priv=Sdouble(std::numeric_limits<double>::lowest())) #pragma omp declare reduction(max:Slong_double : omp_out=Sstd::max(omp_in,omp_out)) initializer(omp_priv=Slong_double(std::numeric_limits<long double>::lowest())) // min #pragma omp declare reduction(min:Sfloat : omp_out=Sstd::min(omp_in,omp_out)) initializer(omp_priv=Sfloat(std::numeric_limits<float>::max())) #pragma omp declare reduction(min:Sdouble : omp_out=Sstd::min(omp_in,omp_out)) initializer(omp_priv=Sdouble(std::numeric_limits<double>::max())) #pragma omp declare reduction(min:Slong_double : omp_out=Sstd::min(omp_in,omp_out)) initializer(omp_priv=Slong_double(std::numeric_limits<long double>::max())) #endif //_OPENMP
VolumetricAdaptiveAveragePooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/VolumetricAdaptiveAveragePooling.c" #else #define START_IND(a,b,c) (int)floor((float)(a * c) / b) #define END_IND(a,b,c) (int)ceil((float)((a + 1) * c) / b) // #define START_IND(a,b,c) a * c / b // #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 // 5d tensor B x D x T x H x W static void THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)( real *input_p, real *output_p, int64_t sizeD, int64_t isizeT, int64_t isizeH, int64_t isizeW, int64_t osizeT, int64_t osizeH, int64_t osizeW, int64_t istrideD, int64_t istrideT, int64_t istrideH, int64_t istrideW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { /* loop over output */ int64_t ot, oh, ow; for(ot = 0; ot < osizeT; ot++) { int istartT = START_IND(ot, osizeT, isizeT); int iendT = END_IND(ot, osizeT, isizeT); int kT = iendT - istartT; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; /* local pointers */ real *ip = input_p + d*istrideD + istartT*istrideT + istartH*istrideH + istartW*istrideW; real *op = output_p + d*osizeT*osizeH*osizeW + ot*osizeH*osizeW + oh*osizeW + ow; /* compute local average: */ real sum = 0; int it, ih, iw; for(it = 0; it < kT; it++) { for(ih = 0; ih < kH; ih++) { for(iw = 0; iw < kW; iw++) { real val = *(ip + it*istrideT + ih*istrideH + iw*istrideW); sum += val; } } } /* set output to local average */ *op = sum / kT / kH / kW; } } } } } void THNN_(VolumetricAdaptiveAveragePooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int osizeT, int osizeW, int osizeH) { int dimD = 0; int dimT = 1; int dimH = 2; int dimW = 3; int64_t sizeB = 1; int64_t sizeD; int64_t isizeT; int64_t isizeH; int64_t isizeW; int64_t istrideB; int64_t istrideD; int64_t istrideT; int64_t istrideH; int64_t istrideW; real *input_data; real *output_data; THNN_ARGCHECK(input->nDimension == 4 || input->nDimension == 5, 2, input, "4D or 5D (batch mode) tensor expected for input, but got: %s"); if (input->nDimension == 5) { istrideB = input->stride[0]; sizeB = input->size[0]; dimD++; dimT++; dimH++; dimW++; } /* sizes */ sizeD = input->size[dimD]; isizeT = input->size[dimT]; isizeH = input->size[dimH]; isizeW = input->size[dimW]; /* strides */ istrideD = input->stride[dimD]; istrideT = input->stride[dimT]; istrideH = input->stride[dimH]; istrideW = input->stride[dimW]; /* resize output */ if (input->nDimension == 4) { THTensor_(resize4d)(output, sizeD, osizeT, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)(input_data, output_data, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW); } else { int64_t b; THTensor_(resize5d)(output, sizeB, sizeD, osizeT, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)(input_data+b*istrideB, output_data+b*sizeD*osizeT*osizeH*osizeW, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW); } } } static void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)( real *gradInput_p, real *gradOutput_p, int64_t sizeD, int64_t isizeT, int64_t isizeH, int64_t isizeW, int64_t osizeT, int64_t osizeH, int64_t osizeW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { real *gradInput_p_d = gradInput_p + d*isizeT*isizeW*isizeH; real *gradOutput_p_d = gradOutput_p + d*osizeT*osizeW*osizeH; /* calculate average */ int64_t ot, oh, ow; for(ot = 0; ot < osizeT; ot++) { int istartT = START_IND(ot, osizeT, isizeT); int iendT = END_IND(ot, osizeT, isizeT); int kT = iendT - istartT; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; real grad_delta = gradOutput_p_d[ot*osizeH*osizeW + oh*osizeW + ow] / kT / kH / kW; int it, ih, iw; for(it = istartT; it < iendT; it++) { for(ih = istartH; ih < iendH; ih++) { for(iw = istartW; iw < iendW; iw++) { /* update gradient */ gradInput_p_d[it*isizeH*isizeW + ih*isizeW + iw] += grad_delta; } } } } } } } } void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput) { int dimD = 0; int dimT = 1; int dimH = 2; int dimW = 3; int64_t sizeB = 1; int64_t sizeD; int64_t isizeT; int64_t isizeH; int64_t isizeW; int64_t osizeT; int64_t osizeH; int64_t osizeW; real *gradInput_data; real *gradOutput_data; /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->nDimension == 5) { sizeB = input->size[0]; dimD++; dimT++; dimH++; dimW++; } /* sizes */ sizeD = input->size[dimD]; isizeT = input->size[dimT]; isizeH = input->size[dimH]; isizeW = input->size[dimW]; osizeT = gradOutput->size[dimT]; osizeH = gradOutput->size[dimH]; osizeW = gradOutput->size[dimW]; /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); /* backprop */ if (input->nDimension == 4) { THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data, gradOutput_data, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW); } else { int64_t b; #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data+b*sizeD*isizeT*isizeH*isizeW, gradOutput_data+b*sizeD*osizeT*osizeH*osizeW, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW); } } /* cleanup */ THTensor_(free)(gradOutput); } #endif #undef START_IND #undef END_IND
laplace2d.c
/* * Copyright 2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <math.h> #include <string.h> #include "timer.h" #define NN 4096 #define NM 4096 double A[NN][NM]; double Anew[NN][NM]; int main(int argc, char** argv) { const int n = NN; const int m = NM; const int iter_max = 1000; const double tol = 1.0e-6; double error = 1.0; memset(A, 0, n * m * sizeof(double)); memset(Anew, 0, n * m * sizeof(double)); for (int j = 0; j < n; j++) { A[j][0] = 1.0; Anew[j][0] = 1.0; } printf("Jacobi relaxation Calculation: %d x %d mesh\n", n, m); StartTimer(); int iter = 0; while ( error > tol && iter < iter_max ) { error = 0.0; #pragma omp parallel for shared(m, n, Anew, A) #pragma acc kernels for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { Anew[j][i] = 0.25 * ( A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); error = fmax( error, fabs(Anew[j][i] - A[j][i])); } } #pragma omp parallel for shared(m, n, Anew, A) #pragma acc kernels for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } if(iter % 100 == 0) printf("%5d, %0.6f\n", iter, error); iter++; } double runtime = GetTimer(); printf(" total: %f s\n", runtime / 1000); }
scale.c
/* * OpenMP implementatation of scaling a 2D array. This simple code is used to illustrat benefits of * multi-threaded parallelism and limits on performance scalability (i.e., Amdahl's Law) * * @author Apan Qasem */ #include<stdio.h> #include<stdlib.h> #include<sys/time.h> #include <omp.h> #define REPS 100 double t0; double mysecond() { struct timeval tp; struct timezone tzp; int i; i = gettimeofday(&tp,&tzp); return ( (double) tp.tv_sec + (double) tp.tv_usec * 1.e-6 ); } int main(int argc, char *argv[]) { int **a, **b; int M = atoi(argv[1]); int N = atoi(argv[2]); omp_set_num_threads(N); a = (int **) malloc(sizeof(int *) * M); b = (int **) malloc(sizeof(int *) * M); int i, j, k; for (i = 0; i < M; i++) { a[i] = (int *) malloc(sizeof(int) * M); b[i] = (int *) malloc(sizeof(int) * M); } for (j = 0; j < M; j++) for (i = 0; i < M; i++) b[i][j] = i + j; t0 = mysecond(); #pragma omp parallel for private(j,i) for (k = 0; k < REPS; k++) { for (j = 0; j < M; j++) for (i = 0; i < M; i++) a[i][j] = b[i][j] * 17; } t0 = (mysecond() - t0) * 1.e3; printf("parallel loop = %3.2f ms\n", t0); return 0; }
GB_unaryop__lnot_int16_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int16_int32 // op(A') function: GB_tran__lnot_int16_int32 // C type: int16_t // A type: int32_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int32_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ int16_t z = (int16_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT16 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int16_int32 ( int16_t *restrict Cx, const int32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int16_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mkl_quantized_conv_ops.h
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_ #define TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_ #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/framework/tensor.h" #ifdef INTEL_MKL namespace tensorflow { template <class T> float MklFloatForOneQuantizedLevel(float range_min, float range_max) { int64 highest = static_cast<int64>(Eigen::NumTraits<T>::highest()); int64 lowest = static_cast<int64>(Eigen::NumTraits<T>::lowest()); // Adjusting for having a symmetric range. // for example: for 8-bit [-127, 127] as opposed to [-128, 127]. if (lowest < -highest) ++lowest; const float float_for_one_quantized_level = (range_max - range_min) / (highest - lowest); return float_for_one_quantized_level; } template <class T1, class T2, class T3> void MklQuantizationRangeForMultiplication(float min_a, float max_a, float min_b, float max_b, float* min_c, float* max_c) { const float a_float_for_one_quant_level = MklFloatForOneQuantizedLevel<T1>(min_a, max_a); const float b_float_for_one_quant_level = MklFloatForOneQuantizedLevel<T2>(min_b, max_b); const int64 c_highest = static_cast<int64>(Eigen::NumTraits<T3>::highest()); const int64 c_lowest = static_cast<int64>(Eigen::NumTraits<T3>::lowest()); const float c_float_for_one_quant_level = a_float_for_one_quant_level * b_float_for_one_quant_level; *min_c = c_float_for_one_quant_level * c_lowest; *max_c = c_float_for_one_quant_level * c_highest; } template <class T1, class T2, class T3> void MklQuantizationRangeForMultiplication(float min_a, float max_a, const Tensor& min_b_vector, const Tensor& max_b_vector, Tensor** min_c_vector, Tensor** max_c_vector) { DCHECK(min_b_vector.NumElements() == (*min_c_vector)->NumElements()); DCHECK(max_b_vector.NumElements() == (*max_c_vector)->NumElements()); size_t n_channel = min_b_vector.NumElements(); const int64 c_highest = static_cast<int64>(Eigen::NumTraits<T3>::highest()); const int64 c_lowest = static_cast<int64>(Eigen::NumTraits<T3>::lowest()); const float* min_b = min_b_vector.flat<float>().data(); const float* max_b = max_b_vector.flat<float>().data(); float* min_c = (*min_c_vector)->flat<float>().data(); float* max_c = (*max_c_vector)->flat<float>().data(); #ifndef ENABLE_MKLDNN_THREADPOOL #pragma omp parallel for #endif // !ENABLE_MKLDNN_THREADPOOL // TODO: Add eigen parallel_for for (size_t n = 0; n < n_channel; ++n) { float a_float_for_one_quant_level = MklFloatForOneQuantizedLevel<T1>(min_a, max_a); float b_float_for_one_quant_level = MklFloatForOneQuantizedLevel<T2>(min_b[n], max_b[n]); float c_float_for_one_quant_level = a_float_for_one_quant_level * b_float_for_one_quant_level; min_c[n] = c_float_for_one_quant_level * c_lowest; max_c[n] = c_float_for_one_quant_level * c_highest; } } } // namespace tensorflow #endif // INTEL_MKL #endif // TENSORFLOW_CORE_KERNELS_MKL_QUANTIZED_CONV_OPS_H_
quicksort.c
/* C implementation QuickSort from http://w...content-available-to-author-only...s.org/quick-sort/ */ #include<stdio.h> #include<stdlib.h> #include<omp.h> /* SPEED UP: 3.18 TEMPO SEQUENCIAL (omp_get_wtime): 2.049 seconds TEMPO PARALELO (omp_get_wtime): 0.644 seconds */ // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition (int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high- 1; j++) { // If current element is smaller than or // equal to pivot if (arr[j] <= pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); if (high - low + 1 <= 125000) { quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } else { // Separately sort elements before // partition and after partition #pragma omp parallel sections { #pragma omp section quickSort(arr, low, pi - 1); #pragma omp section quickSort(arr, pi + 1, high); } } } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } // Driver program to test above functions int main() { omp_set_nested(1); double start, end; int i,n = 10000000; int *arr = (int*) malloc(n*sizeof(int)); for(i=0; i < n; i++) arr[i] = rand()%n; start = omp_get_wtime(); quickSort(arr, 0, n-1); end = omp_get_wtime(); printf("Work took %f seconds\n", end - start); // printf("Sorted array: \n"); // printArray(arr, n); return 0; }
trmv_x_csr_n_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t trmv_x_csr_n_hi_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_Number tmp; alpha_setzero(tmp); for(ALPHA_INT ai = A->rows_start[i]; ai < A->rows_end[i]; ++ai) { const ALPHA_INT col = A->col_indx[ai]; if(col < i) { continue; } else { alpha_madde(tmp, A->values[ai], x[col]); } } alpha_mule(tmp, alpha); alpha_mule(y[i], beta); alpha_adde(y[i], tmp); } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSR *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return trmv_x_csr_n_hi_omp(alpha, A, x, beta, y); }
ab-totient-omp-5.c
// Distributed and parallel technologies, Andrew Beveridge, 03/03/2014 // To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c // To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end #include <stdio.h> #include <omp.h> /* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1). If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */ long getTotient (long number) { long result = number; // Check every prime number below the square root for divisibility if(number % 2 == 0){ result -= result / 2; do number /= 2; while(number %2 == 0); } // Primitive replacement for a list of primes, looping through every odd number long prime; for(prime = 3; prime * prime <= number; prime += 2){ if(number %prime == 0){ result -= result / prime; do number /= prime; while(number % prime == 0); } } // Last common factor if(number > 1) result -= result / number; // Return the result. return result; } // Main method. int main(int argc, char ** argv) { // Load inputs long lower, upper; sscanf(argv[1], "%ld", &lower); sscanf(argv[2], "%ld", &upper); int i; long result = 0.0; // We know the answer if it's 1; no need to execute the function if(lower == 1) { result = 1.0; lower = 2; } #pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(5) // Sum all totients in the specified range for (i = lower; i <= upper; i++) { result = result + getTotient(i); } // Print the result printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result); // A-OK! return 0; }
GB_unaryop__ainv_int8_uint8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__ainv_int8_uint8 // op(A') function: GB_tran__ainv_int8_uint8 // C type: int8_t // A type: uint8_t // cast: int8_t cij = (int8_t) aij // unaryop: cij = -aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = -x ; // casting #define GB_CASTING(z, x) \ int8_t z = (int8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_INT8 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_int8_uint8 ( int8_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__ainv_int8_uint8 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__iseq_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_01__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_02__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_03__iseq_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__iseq_int64) // A*D function (colscale): GB (_AxD__iseq_int64) // D*A function (rowscale): GB (_DxB__iseq_int64) // C+=B function (dense accum): GB (_Cdense_accumB__iseq_int64) // C+=b function (dense accum): GB (_Cdense_accumb__iseq_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__iseq_int64) // C=scalar+B GB (_bind1st__iseq_int64) // C=scalar+B' GB (_bind1st_tran__iseq_int64) // C=A+scalar GB (_bind2nd__iseq_int64) // C=A'+scalar GB (_bind2nd_tran__iseq_int64) // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISEQ || GxB_NO_INT64 || GxB_NO_ISEQ_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__iseq_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__iseq_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__iseq_int64) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__iseq_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__iseq_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__iseq_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__iseq_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__iseq_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__iseq_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__iseq_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__iseq_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__iseq_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
LogSoftMax.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/LogSoftMax.c" #else #ifdef _MSC_VER #define LOG_SOFTMAX_SIZE_TYPE int64_t #define LOG_SOFTMAX_CAST_TYPE (int64_t) #else #define LOG_SOFTMAX_SIZE_TYPE uint64_t #define LOG_SOFTMAX_CAST_TYPE #endif void THNN_(LogSoftMax_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int dim) { THArgCheck(dim >= 0 && dim < input->nDimension, 4, "dim out of range (got %d, but input has %d dims)", dim, input->nDimension); uint64_t outer_size = 1; uint64_t dim_size = input->size[dim]; uint64_t inner_size = 1; for (uint64_t i = 0; i < dim; ++i) outer_size *= input->size[i]; for (uint64_t i = dim + 1; i < input->nDimension; ++i) inner_size *= input->size[i]; input = THTensor_(newContiguous)(input); THTensor_(resizeAs)(output, input); real *input_data_base = THTensor_(data)(input); real *output_data_base = THTensor_(data)(output); uint64_t dim_stride = inner_size; uint64_t outer_stride = dim_size * dim_stride; LOG_SOFTMAX_SIZE_TYPE i, d; #pragma omp parallel for private(i, d) for (i = 0; i < LOG_SOFTMAX_CAST_TYPE (outer_size * inner_size); i++) { uint64_t outer_idx = i / inner_size; uint64_t inner_idx = i % inner_size; real *input_data = input_data_base + outer_idx * outer_stride + inner_idx; real *output_data = output_data_base + outer_idx * outer_stride + inner_idx; real max_input = -THInf; for (d = 0; d < LOG_SOFTMAX_CAST_TYPE dim_size; d++) max_input = THMax(max_input, input_data[d * dim_stride]); accreal logsum = 0; for (d = 0; d < LOG_SOFTMAX_CAST_TYPE dim_size; d++) logsum += exp(input_data[d * dim_stride] - max_input); logsum = max_input + log(logsum); for (d = 0; d < LOG_SOFTMAX_CAST_TYPE dim_size; d++) output_data[d * dim_stride] = input_data[d * dim_stride] - logsum; } THTensor_(free)(input); } void THNN_(LogSoftMax_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *output, int dim) { THNN_CHECK_SHAPE(output, gradOutput); THArgCheck(dim >= 0 && dim < output->nDimension, 6, "dim out of range (got %d, but input has %d dims)", dim, output->nDimension); uint64_t outer_size = 1; uint64_t dim_size = output->size[dim]; uint64_t inner_size = 1; for (uint64_t i = 0; i < dim; ++i) outer_size *= output->size[i]; for (uint64_t i = dim + 1; i < output->nDimension; ++i) inner_size *= output->size[i]; gradOutput = THTensor_(newContiguous)(gradOutput); output = THTensor_(newContiguous)(output); THTensor_(resizeAs)(gradInput, output); real *gradInput_data_base = THTensor_(data)(gradInput); real *output_data_base = THTensor_(data)(output); real *gradOutput_data_base = THTensor_(data)(gradOutput); uint64_t dim_stride = inner_size; uint64_t outer_stride = dim_size * dim_stride; LOG_SOFTMAX_SIZE_TYPE i, d; #pragma omp parallel for private(i, d) for (i = 0; i < LOG_SOFTMAX_CAST_TYPE (outer_size * inner_size); i++) { uint64_t outer_idx = i / inner_size; uint64_t inner_idx = i % inner_size; real *gradInput_data = gradInput_data_base + outer_idx * outer_stride + inner_idx; real *output_data = output_data_base + outer_idx * outer_stride + inner_idx; real *gradOutput_data = gradOutput_data_base + outer_idx * outer_stride + inner_idx; accreal sum = 0; for (d = 0; d < LOG_SOFTMAX_CAST_TYPE dim_size; d++) sum += gradOutput_data[d * dim_stride]; for (d = 0; d < LOG_SOFTMAX_CAST_TYPE dim_size; d++) gradInput_data[d * dim_stride] = gradOutput_data[d * dim_stride] - exp(output_data[d * dim_stride]) * sum; } THTensor_(free)(gradOutput); THTensor_(free)(output); } #endif
callback.h
#define _BSD_SOURCE #define _DEFAULT_SOURCE #include <stdio.h> #include <inttypes.h> #include <omp.h> #include <ompt.h> #include "ompt-signal.h" // Used to detect architecture #include "../../src/kmp_platform.h" static const char* ompt_thread_type_t_values[] = { NULL, "ompt_thread_initial", "ompt_thread_worker", "ompt_thread_other" }; static const char* ompt_task_status_t_values[] = { NULL, "ompt_task_complete", "ompt_task_yield", "ompt_task_cancel", "ompt_task_others" }; static const char* ompt_cancel_flag_t_values[] = { "ompt_cancel_parallel", "ompt_cancel_sections", "ompt_cancel_do", "ompt_cancel_taskgroup", "ompt_cancel_activated", "ompt_cancel_detected", "ompt_cancel_discarded_task" }; static ompt_set_callback_t ompt_set_callback; static ompt_get_task_info_t ompt_get_task_info; static ompt_get_thread_data_t ompt_get_thread_data; static ompt_get_parallel_info_t ompt_get_parallel_info; static ompt_get_unique_id_t ompt_get_unique_id; static ompt_get_num_procs_t ompt_get_num_procs; static ompt_get_num_places_t ompt_get_num_places; static ompt_get_place_proc_ids_t ompt_get_place_proc_ids; static ompt_get_place_num_t ompt_get_place_num; static ompt_get_partition_place_nums_t ompt_get_partition_place_nums; static ompt_get_proc_id_t ompt_get_proc_id; static ompt_enumerate_states_t ompt_enumerate_states; static ompt_enumerate_mutex_impls_t ompt_enumerate_mutex_impls; static void print_ids(int level) { ompt_frame_t* frame ; ompt_data_t* parallel_data; ompt_data_t* task_data; int exists_task = ompt_get_task_info(level, NULL, &task_data, &frame, &parallel_data, NULL); if (frame) { printf("%" PRIu64 ": task level %d: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", exit_frame=%p, reenter_frame=%p\n", ompt_get_thread_data()->value, level, exists_task ? parallel_data->value : 0, exists_task ? task_data->value : 0, frame->exit_frame, frame->enter_frame); } else printf("%" PRIu64 ": task level %d: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", frame=%p\n", ompt_get_thread_data()->value, level, exists_task ? parallel_data->value : 0, exists_task ? task_data->value : 0, frame); } #define print_frame(level)\ do {\ printf("%" PRIu64 ": __builtin_frame_address(%d)=%p\n", ompt_get_thread_data()->value, level, __builtin_frame_address(level));\ } while(0) // clang (version 5.0 and above) adds an intermediate function call with debug flag (-g) #if defined(TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN) #if defined(DEBUG) && defined(__clang__) && __clang_major__ >= 5 #define print_frame_from_outlined_fn(level) print_frame(level+1) #else #define print_frame_from_outlined_fn(level) print_frame(level) #endif #warning "Clang 5.0 and later add an additional wrapper function for tasks when compiling with debug information." #warning "Please define -DDEBUG iff you manually pass in -g!" #endif // This macro helps to define a label at the current position that can be used // to get the current address in the code. // // For print_current_address(): // To reliably determine the offset between the address of the label and the // actual return address, we insert a NOP instruction as a jump target as the // compiler would otherwise insert an instruction that we can't control. The // instruction length is target dependent and is explained below. // // (The empty block between "#pragma omp ..." and the __asm__ statement is a // workaround for a bug in the Intel Compiler.) #define define_ompt_label(id) \ {} \ __asm__("nop"); \ ompt_label_##id: // This macro helps to get the address of a label that is inserted by the above // macro define_ompt_label(). The address is obtained with a GNU extension // (&&label) that has been tested with gcc, clang and icc. #define get_ompt_label_address(id) (&& ompt_label_##id) // This macro prints the exact address that a previously called runtime function // returns to. #define print_current_address(id) \ define_ompt_label(id) \ print_possible_return_addresses(get_ompt_label_address(id)) #if KMP_ARCH_X86 || KMP_ARCH_X86_64 // On X86 the NOP instruction is 1 byte long. In addition, the comiler inserts // a MOV instruction for non-void runtime functions which is 3 bytes long. #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p or %p for non-void functions\n", \ ompt_get_thread_data()->value, ((char *)addr) - 1, ((char *)addr) - 4) #elif KMP_ARCH_PPC64 // On Power the NOP instruction is 4 bytes long. In addition, the compiler // inserts an LD instruction which accounts for another 4 bytes. In contrast to // X86 this instruction is always there, even for void runtime functions. #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p\n", ompt_get_thread_data()->value, \ ((char *)addr) - 8) #elif KMP_ARCH_AARCH64 // On AArch64 the NOP instruction is 4 bytes long, can be followed by inserted // store instruction (another 4 bytes long). #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p or %p\n", ompt_get_thread_data()->value, \ ((char *)addr) - 4, ((char *)addr) - 8) #else #error Unsupported target architecture, cannot determine address offset! #endif // This macro performs a somewhat similar job to print_current_address(), except // that it discards a certain number of nibbles from the address and only prints // the most significant bits / nibbles. This can be used for cases where the // return address can only be approximated. // // To account for overflows (ie the most significant bits / nibbles have just // changed as we are a few bytes above the relevant power of two) the addresses // of the "current" and of the "previous block" are printed. #define print_fuzzy_address(id) \ define_ompt_label(id) \ print_fuzzy_address_blocks(get_ompt_label_address(id)) // If you change this define you need to adapt all capture patterns in the tests // to include or discard the new number of nibbles! #define FUZZY_ADDRESS_DISCARD_NIBBLES 2 #define FUZZY_ADDRESS_DISCARD_BYTES (1 << ((FUZZY_ADDRESS_DISCARD_NIBBLES) * 4)) #define print_fuzzy_address_blocks(addr) \ printf("%" PRIu64 ": fuzzy_address=0x%" PRIx64 " or 0x%" PRIx64 " (%p)\n", \ ompt_get_thread_data()->value, \ ((uint64_t)addr) / FUZZY_ADDRESS_DISCARD_BYTES - 1, \ ((uint64_t)addr) / FUZZY_ADDRESS_DISCARD_BYTES, addr) static void format_task_type(int type, char* buffer) { char* progress = buffer; if(type & ompt_task_initial) progress += sprintf(progress, "ompt_task_initial"); if(type & ompt_task_implicit) progress += sprintf(progress, "ompt_task_implicit"); if(type & ompt_task_explicit) progress += sprintf(progress, "ompt_task_explicit"); if(type & ompt_task_target) progress += sprintf(progress, "ompt_task_target"); if(type & ompt_task_undeferred) progress += sprintf(progress, "|ompt_task_undeferred"); if(type & ompt_task_untied) progress += sprintf(progress, "|ompt_task_untied"); if(type & ompt_task_final) progress += sprintf(progress, "|ompt_task_final"); if(type & ompt_task_mergeable) progress += sprintf(progress, "|ompt_task_mergeable"); if(type & ompt_task_merged) progress += sprintf(progress, "|ompt_task_merged"); } static void on_ompt_callback_mutex_acquire( ompt_mutex_kind_t kind, unsigned int hint, unsigned int impl, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_wait_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_wait_nest_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_wait_critical: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_wait_atomic: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_wait_ordered: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; default: break; } } static void on_ompt_callback_mutex_acquired( ompt_mutex_kind_t kind, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_acquired_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_acquired_nest_lock_first: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_acquired_critical: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_acquired_atomic: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_acquired_ordered: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_mutex_released( ompt_mutex_kind_t kind, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_release_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_release_nest_lock_last: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_release_critical: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_release_atomic: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_release_ordered: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_nest_lock( ompt_scope_endpoint_t endpoint, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_acquired_nest_lock_next: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_release_nest_lock_prev: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; } } static void on_ompt_callback_sync_region( ompt_sync_region_kind_t kind, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_barrier_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); print_ids(0); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_taskwait_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_taskgroup_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } break; case ompt_scope_end: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_barrier_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_taskwait_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_taskgroup_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; } break; } } static void on_ompt_callback_sync_region_wait( ompt_sync_region_kind_t kind, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_wait_barrier_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_wait_taskwait_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_wait_taskgroup_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } break; case ompt_scope_end: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_wait_barrier_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_wait_taskwait_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_wait_taskgroup_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; } break; } } static void on_ompt_callback_flush( ompt_data_t *thread_data, const void *codeptr_ra) { printf("%" PRIu64 ": ompt_event_flush: codeptr_ra=%p\n", thread_data->value, codeptr_ra); } static void on_ompt_callback_cancel( ompt_data_t *task_data, int flags, const void *codeptr_ra) { const char* first_flag_value; const char* second_flag_value; if(flags & ompt_cancel_parallel) first_flag_value = ompt_cancel_flag_t_values[0]; else if(flags & ompt_cancel_sections) first_flag_value = ompt_cancel_flag_t_values[1]; else if(flags & ompt_cancel_do) first_flag_value = ompt_cancel_flag_t_values[2]; else if(flags & ompt_cancel_taskgroup) first_flag_value = ompt_cancel_flag_t_values[3]; if(flags & ompt_cancel_activated) second_flag_value = ompt_cancel_flag_t_values[4]; else if(flags & ompt_cancel_detected) second_flag_value = ompt_cancel_flag_t_values[5]; else if(flags & ompt_cancel_discarded_task) second_flag_value = ompt_cancel_flag_t_values[6]; printf("%" PRIu64 ": ompt_event_cancel: task_data=%" PRIu64 ", flags=%s|%s=%" PRIu32 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, task_data->value, first_flag_value, second_flag_value, flags, codeptr_ra); } static void on_ompt_callback_idle( ompt_scope_endpoint_t endpoint) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_idle_begin:\n", ompt_get_thread_data()->value); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_idle_end:\n", ompt_get_thread_data()->value); break; } } static void on_ompt_callback_implicit_task( ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, unsigned int team_size, unsigned int thread_num) { switch(endpoint) { case ompt_scope_begin: if(task_data->ptr) printf("%s\n", "0: task_data initially not null"); task_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_implicit_task_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", team_size=%" PRIu32 ", thread_num=%" PRIu32 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, team_size, thread_num); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_implicit_task_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", team_size=%" PRIu32 ", thread_num=%" PRIu32 "\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, team_size, thread_num); break; } } static void on_ompt_callback_lock_init( ompt_mutex_kind_t kind, unsigned int hint, unsigned int impl, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_init_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_init_nest_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; default: break; } } static void on_ompt_callback_lock_destroy( ompt_mutex_kind_t kind, ompt_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_destroy_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_destroy_nest_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_work( ompt_work_type_t wstype, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, uint64_t count, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(wstype) { case ompt_work_loop: printf("%" PRIu64 ": ompt_event_loop_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_sections: printf("%" PRIu64 ": ompt_event_sections_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_executor: printf("%" PRIu64 ": ompt_event_single_in_block_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_other: printf("%" PRIu64 ": ompt_event_single_others_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_workshare: //impl break; case ompt_work_distribute: printf("%" PRIu64 ": ompt_event_distribute_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_taskloop: //impl printf("%" PRIu64 ": ompt_event_taskloop_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; } break; case ompt_scope_end: switch(wstype) { case ompt_work_loop: printf("%" PRIu64 ": ompt_event_loop_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_sections: printf("%" PRIu64 ": ompt_event_sections_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_executor: printf("%" PRIu64 ": ompt_event_single_in_block_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_other: printf("%" PRIu64 ": ompt_event_single_others_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_workshare: //impl break; case ompt_work_distribute: printf("%" PRIu64 ": ompt_event_distribute_end: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_taskloop: //impl printf("%" PRIu64 ": ompt_event_taskloop_end: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; } break; } } static void on_ompt_callback_master( ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_master_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_master_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } } static void on_ompt_callback_parallel_begin( ompt_data_t *encountering_task_data, const ompt_frame_t *encountering_task_frame, ompt_data_t* parallel_data, uint32_t requested_team_size, ompt_invoker_t invoker, const void *codeptr_ra) { if(parallel_data->ptr) printf("0: parallel_data initially not null\n"); parallel_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_parallel_begin: parent_task_id=%" PRIu64 ", parent_task_frame.exit=%p, parent_task_frame.reenter=%p, parallel_id=%" PRIu64 ", requested_team_size=%" PRIu32 ", codeptr_ra=%p, invoker=%d\n", ompt_get_thread_data()->value, encountering_task_data->value, encountering_task_frame->exit_frame, encountering_task_frame->enter_frame, parallel_data->value, requested_team_size, codeptr_ra, invoker); } static void on_ompt_callback_parallel_end( ompt_data_t *parallel_data, ompt_data_t *encountering_task_data, ompt_invoker_t invoker, const void *codeptr_ra) { printf("%" PRIu64 ": ompt_event_parallel_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", invoker=%d, codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, encountering_task_data->value, invoker, codeptr_ra); } static void on_ompt_callback_task_create( ompt_data_t *encountering_task_data, const ompt_frame_t *encountering_task_frame, ompt_data_t* new_task_data, int type, int has_dependences, const void *codeptr_ra) { if(new_task_data->ptr) printf("0: new_task_data initially not null\n"); new_task_data->value = ompt_get_unique_id(); char buffer[2048]; format_task_type(type, buffer); //there is no parallel_begin callback for implicit parallel region //thus it is initialized in initial task if(type & ompt_task_initial) { ompt_data_t *parallel_data; ompt_get_parallel_info(0, &parallel_data, NULL); if(parallel_data->ptr) printf("%s\n", "0: parallel_data initially not null"); parallel_data->value = ompt_get_unique_id(); } printf("%" PRIu64 ": ompt_event_task_create: parent_task_id=%" PRIu64 ", parent_task_frame.exit=%p, parent_task_frame.reenter=%p, new_task_id=%" PRIu64 ", codeptr_ra=%p, task_type=%s=%d, has_dependences=%s\n", ompt_get_thread_data()->value, encountering_task_data ? encountering_task_data->value : 0, encountering_task_frame ? encountering_task_frame->exit_frame : NULL, encountering_task_frame ? encountering_task_frame->enter_frame : NULL, new_task_data->value, codeptr_ra, buffer, type, has_dependences ? "yes" : "no"); } static void on_ompt_callback_task_schedule( ompt_data_t *first_task_data, ompt_task_status_t prior_task_status, ompt_data_t *second_task_data) { printf("%" PRIu64 ": ompt_event_task_schedule: first_task_id=%" PRIu64 ", second_task_id=%" PRIu64 ", prior_task_status=%s=%d\n", ompt_get_thread_data()->value, first_task_data->value, second_task_data->value, ompt_task_status_t_values[prior_task_status], prior_task_status); if(prior_task_status == ompt_task_complete) { printf("%" PRIu64 ": ompt_event_task_end: task_id=%" PRIu64 "\n", ompt_get_thread_data()->value, first_task_data->value); } } static void on_ompt_callback_task_dependences( ompt_data_t *task_data, const ompt_task_dependence_t *deps, int ndeps) { printf("%" PRIu64 ": ompt_event_task_dependences: task_id=%" PRIu64 ", deps=%p, ndeps=%d\n", ompt_get_thread_data()->value, task_data->value, (void *)deps, ndeps); } static void on_ompt_callback_task_dependence( ompt_data_t *first_task_data, ompt_data_t *second_task_data) { printf("%" PRIu64 ": ompt_event_task_dependence_pair: first_task_id=%" PRIu64 ", second_task_id=%" PRIu64 "\n", ompt_get_thread_data()->value, first_task_data->value, second_task_data->value); } static void on_ompt_callback_thread_begin( ompt_thread_type_t thread_type, ompt_data_t *thread_data) { if(thread_data->ptr) printf("%s\n", "0: thread_data initially not null"); thread_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_thread_begin: thread_type=%s=%d, thread_id=%" PRIu64 "\n", ompt_get_thread_data()->value, ompt_thread_type_t_values[thread_type], thread_type, thread_data->value); } static void on_ompt_callback_thread_end( ompt_data_t *thread_data) { printf("%" PRIu64 ": ompt_event_thread_end: thread_id=%" PRIu64 "\n", ompt_get_thread_data()->value, thread_data->value); } static int on_ompt_callback_control_tool( uint64_t command, uint64_t modifier, void *arg, const void *codeptr_ra) { ompt_frame_t* omptTaskFrame; ompt_get_task_info(0, NULL, (ompt_data_t**) NULL, &omptTaskFrame, NULL, NULL); printf("%" PRIu64 ": ompt_event_control_tool: command=%" PRIu64 ", modifier=%" PRIu64 ", arg=%p, codeptr_ra=%p, current_task_frame.exit=%p, current_task_frame.reenter=%p \n", ompt_get_thread_data()->value, command, modifier, arg, codeptr_ra, omptTaskFrame->exit_frame, omptTaskFrame->enter_frame); return 0; //success } #define register_callback_t(name, type) \ do{ \ type f_##name = &on_##name; \ if (ompt_set_callback(name, (ompt_callback_t)f_##name) == \ ompt_set_never) \ printf("0: Could not register callback '" #name "'\n"); \ }while(0) #define register_callback(name) register_callback_t(name, name##_t) int ompt_initialize( ompt_function_lookup_t lookup, ompt_data_t *tool_data) { ompt_set_callback = (ompt_set_callback_t) lookup("ompt_set_callback"); ompt_get_task_info = (ompt_get_task_info_t) lookup("ompt_get_task_info"); ompt_get_thread_data = (ompt_get_thread_data_t) lookup("ompt_get_thread_data"); ompt_get_parallel_info = (ompt_get_parallel_info_t) lookup("ompt_get_parallel_info"); ompt_get_unique_id = (ompt_get_unique_id_t) lookup("ompt_get_unique_id"); ompt_get_num_procs = (ompt_get_num_procs_t) lookup("ompt_get_num_procs"); ompt_get_num_places = (ompt_get_num_places_t) lookup("ompt_get_num_places"); ompt_get_place_proc_ids = (ompt_get_place_proc_ids_t) lookup("ompt_get_place_proc_ids"); ompt_get_place_num = (ompt_get_place_num_t) lookup("ompt_get_place_num"); ompt_get_partition_place_nums = (ompt_get_partition_place_nums_t) lookup("ompt_get_partition_place_nums"); ompt_get_proc_id = (ompt_get_proc_id_t) lookup("ompt_get_proc_id"); ompt_enumerate_states = (ompt_enumerate_states_t) lookup("ompt_enumerate_states"); ompt_enumerate_mutex_impls = (ompt_enumerate_mutex_impls_t) lookup("ompt_enumerate_mutex_impls"); register_callback(ompt_callback_mutex_acquire); register_callback_t(ompt_callback_mutex_acquired, ompt_callback_mutex_t); register_callback_t(ompt_callback_mutex_released, ompt_callback_mutex_t); register_callback(ompt_callback_nest_lock); register_callback(ompt_callback_sync_region); register_callback_t(ompt_callback_sync_region_wait, ompt_callback_sync_region_t); register_callback(ompt_callback_control_tool); register_callback(ompt_callback_flush); register_callback(ompt_callback_cancel); register_callback(ompt_callback_idle); register_callback(ompt_callback_implicit_task); register_callback_t(ompt_callback_lock_init, ompt_callback_mutex_acquire_t); register_callback_t(ompt_callback_lock_destroy, ompt_callback_mutex_t); register_callback(ompt_callback_work); register_callback(ompt_callback_master); register_callback(ompt_callback_parallel_begin); register_callback(ompt_callback_parallel_end); register_callback(ompt_callback_task_create); register_callback(ompt_callback_task_schedule); register_callback(ompt_callback_task_dependences); register_callback(ompt_callback_task_dependence); register_callback(ompt_callback_thread_begin); register_callback(ompt_callback_thread_end); printf("0: NULL_POINTER=%p\n", (void*)NULL); return 1; //success } void ompt_finalize(ompt_data_t *tool_data) { printf("0: ompt_event_runtime_shutdown\n"); } ompt_start_tool_result_t* ompt_start_tool( unsigned int omp_version, const char *runtime_version) { static ompt_start_tool_result_t ompt_start_tool_result = {&ompt_initialize,&ompt_finalize, 0}; return &ompt_start_tool_result; }
cacheblockingsimulator.h
#ifndef LIBGEODECOMP_PARALLELIZATION_CACHEBLOCKINGSIMULATOR_H #define LIBGEODECOMP_PARALLELIZATION_CACHEBLOCKINGSIMULATOR_H #include <libgeodecomp/config.h> #ifdef LIBGEODECOMP_WITH_THREADS #include <omp.h> #include <libgeodecomp/io/logger.h> #include <libgeodecomp/parallelization/monolithicsimulator.h> #include <libgeodecomp/storage/displacedgrid.h> #include <libgeodecomp/storage/updatefunctor.h> namespace LibGeoDecomp { /** * CacheBlockingSimulator is an experimental simulator to explore the * infrastructure required to implement a pipelined wavefront update * algorith and which benefits is may provide. */ template<typename CELL> class CacheBlockingSimulator : public MonolithicSimulator<CELL> { public: friend class CacheBlockingSimulatorTest; typedef typename APITraits::SelectTopology<CELL>::Value Topology; typedef typename TopologiesHelpers::Topology<3, Topology::template WrapsAxis<0>::VALUE, Topology::template WrapsAxis<1>::VALUE, true> BufferTopology; typedef Grid<CELL, Topology> GridType; typedef DisplacedGrid<CELL, BufferTopology> BufferType; typedef std::vector<std::vector<Region<3> > > WavefrontFrames; static const int DIM = Topology::DIM; using MonolithicSimulator<CELL>::NANO_STEPS; using MonolithicSimulator<CELL>::chronometer; CacheBlockingSimulator( Initializer<CELL> *initializer, int pipelineLength, const Coord<DIM - 1>& wavefrontDim) : MonolithicSimulator<CELL>(initializer), buffers(omp_get_max_threads()), pipelineLength(pipelineLength), wavefrontDim(wavefrontDim) { Coord<DIM> dim = initializer->gridBox().dimensions; curGrid = new GridType(dim); newGrid = new GridType(dim); initializer->grid(curGrid); initializer->grid(newGrid); Coord<DIM> bufferDim; for (int i = 0; i < DIM - 1; ++i) { bufferDim[i] = wavefrontDim[i] + 2 * pipelineLength - 2; } bufferDim[DIM - 1] = pipelineLength * 4 - 4; for (std::size_t i = 0; i < buffers.size(); ++i) { buffers[i] = BufferType(CoordBox<DIM>(Coord<DIM>(), bufferDim), curGrid->getEdgeCell(), curGrid->getEdgeCell()); } LOG(DBG, "created " << buffers.size() << " buffers"); generateFrames(); nanoStep = 0; } virtual ~CacheBlockingSimulator() { delete newGrid; delete curGrid; } virtual void step() { // fixme } virtual void run() { initializer->grid(curGrid); stepNum = initializer->startStep(); nanoStep = 0; for(unsigned i = 0; i < writers.size(); ++i) { writers[i]->stepFinished( *getGrid(), getStep(), WRITER_INITIALIZED); } for (stepNum = initializer->startStep(); stepNum < initializer->maxSteps();) { hop(); } for(unsigned i = 0; i < writers.size(); ++i) { writers[i]->stepFinished( *getGrid(), getStep(), WRITER_ALL_DONE); } } virtual const GridType *getGrid() { return curGrid; } private: using MonolithicSimulator<CELL>::initializer; using MonolithicSimulator<CELL>::steerers; using MonolithicSimulator<CELL>::stepNum; using MonolithicSimulator<CELL>::writers; using MonolithicSimulator<CELL>::getStep; GridType *curGrid; GridType *newGrid; std::vector<BufferType> buffers; int pipelineLength; Coord<DIM - 1> wavefrontDim; Grid<WavefrontFrames> frames; unsigned nanoStep; void generateFrames() { Coord<DIM> gridDim = initializer->gridBox().dimensions; Coord<DIM - 1> framesDim; for (int i = 0; i < (DIM - 1); ++i) { framesDim[i] = gridDim[i] / wavefrontDim[i]; if ((gridDim[i] % wavefrontDim[i]) != 0) { framesDim[i] += 1; } } frames.resize(framesDim); for (int y = 0; y < framesDim.y(); ++y) { for (int x = 0; x < framesDim.x(); ++x) { frames[Coord<2>(x, y)] = generateWavefrontFrames( Coord<3>(x * wavefrontDim.x(), y * wavefrontDim.y(), 0)); } } } WavefrontFrames generateWavefrontFrames(const Coord<DIM> offset) { Coord<DIM> gridDim = initializer->gridBox().dimensions; Coord<DIM> wavefrontRegionDim; for (int i = 0; i < (DIM - 1); ++i) { wavefrontRegionDim[i] = wavefrontDim[i]; } wavefrontRegionDim[DIM - 1] = gridDim[DIM - 1] - offset[DIM - 1]; Region<DIM> region; region << CoordBox<DIM>(offset, wavefrontRegionDim); std::vector<Region<3> > regions(pipelineLength); regions[pipelineLength - 1] = region.expandWithTopology( 0, gridDim, Topologies::Cube<3>::Topology()); for (int i = pipelineLength - 2; i >= 0; --i) { regions[i] = regions[i + 1].expandWithTopology( 1, gridDim, Topologies::Cube<3>::Topology()); } int wavefrontLength = gridDim[DIM - 1] + 1; WavefrontFrames ret(wavefrontLength, std::vector<Region<DIM> >(pipelineLength)); for (int index = 0; index < wavefrontLength; ++index) { Coord<DIM> maskOrigin; maskOrigin[DIM - 1] = index; Topology::normalize(maskOrigin, initializer->gridDimensions()); Coord<DIM> maskDim = gridDim; maskDim[DIM - 1] = 1; Region<DIM> mask; mask << CoordBox<DIM>(maskOrigin, maskDim); for (int i = 0; i < pipelineLength; ++i) { ret[index][i] = regions[i] & mask; } } return ret; } void hop() { using std::swap; TimeTotal t(&chronometer); CoordBox<DIM - 1> frameBox = frames.boundingBox(); // for (typename CoordBox<DIM -1>::Iterator waveIter = frameBox.begin(); // waveIter != frameBox.end(); // ++waveIter) { // updateWavefront(*waveIter); // } #pragma omp parallel for for (int y = 0; y < frameBox.dimensions.y(); ++y) { for (int x = 0; x < frameBox.dimensions.x(); ++x) { updateWavefront(&buffers[omp_get_thread_num()], Coord<2>(x, y)); } } swap(curGrid, newGrid); int curNanoStep = nanoStep + pipelineLength; stepNum += curNanoStep / NANO_STEPS; nanoStep = curNanoStep % NANO_STEPS; } void updateWavefront(BufferType *buffer, const Coord<DIM - 1>& wavefrontCoord) { LOG(INFO, "wavefrontCoord(" << wavefrontCoord << ")"); buffer->setEdge(curGrid->getEdge()); // buffer->fill(buffer->boundingBox(), curGrid->getEdgeCell()); fixBufferOrigin(buffer, wavefrontCoord); int index = 0; CoordBox<DIM> boundingBox = curGrid->boundingBox(); int maxIndex = boundingBox.origin[DIM - 1] + boundingBox.dimensions[DIM - 1]; // fill pipeline for (; index < 2 * pipelineLength - 2; ++index) { int lastStage = (index >> 1) + 1; pipelinedUpdate(buffer, wavefrontCoord, index, index, 0, lastStage); } // normal operation for (; index < maxIndex; ++index) { pipelinedUpdate(buffer, wavefrontCoord, index, index, 0, pipelineLength); } // let pipeline drain for (; index < (maxIndex + 2 * pipelineLength - 2); ++index) { int firstStage = (index - maxIndex + 1) >> 1 ; pipelinedUpdate(buffer, wavefrontCoord, index, index, firstStage, pipelineLength); } } void fixBufferOrigin(BufferType *buffer, const Coord<DIM - 1>& frameCoord) { Coord<DIM> bufferOrigin; // fixme: wrong on boundary with Torus topology for (int d = 0; d < (DIM - 1); ++d) { bufferOrigin[d] = (std::max)(0, frameCoord[d] * wavefrontDim[d] - pipelineLength + 1); } bufferOrigin[DIM - 1] = 0; buffer->setOrigin(bufferOrigin); } void pipelinedUpdate( BufferType *buffer, const Coord<DIM - 1>& frameCoord, int globalIndex, int localIndex, int firstStage, int lastStage) { LOG(DBG, " pipelinedUpdate(frameCoord = " << frameCoord << ", globalIndex = " << globalIndex << ", localIndex = " << localIndex << ", firstStage = " << firstStage << ", lastStage = " << lastStage << ")"); for (int i = firstStage; i < lastStage; ++i) { bool firstIteration = (i == 0); bool lastIteration = (i == (pipelineLength - 1)); int currentGlobalIndex = globalIndex - 2 * i; bool needsFlushing = (i == firstStage) && (currentGlobalIndex >= newGrid->getDimensions()[DIM - 1]); int sourceIndex = firstIteration ? currentGlobalIndex : normalizeIndex(localIndex + 2 - 4 * i); int targetIndex = lastIteration ? currentGlobalIndex : normalizeIndex(localIndex + 0 - 4 * i); const Region<DIM>& updateFrame = frames[frameCoord][globalIndex - 2 * i][i]; unsigned curNanoStep = (nanoStep + i) % NANO_STEPS; if ( firstIteration && lastIteration) { frameUpdate(needsFlushing, updateFrame, sourceIndex, targetIndex, *curGrid, newGrid, curNanoStep); } if ( firstIteration && !lastIteration) { frameUpdate(needsFlushing, updateFrame, sourceIndex, targetIndex, *curGrid, buffer, curNanoStep); } if (!firstIteration && lastIteration) { frameUpdate(needsFlushing, updateFrame, sourceIndex, targetIndex, *buffer, newGrid, curNanoStep); } if (!firstIteration && !lastIteration) { frameUpdate(needsFlushing, updateFrame, sourceIndex, targetIndex, *buffer, buffer, curNanoStep); } } } template<class GRID1, class GRID2> void frameUpdate( bool needsFlushing, const Region<DIM>& updateFrame, int sourceIndex, int targetIndex, const GRID1& sourceGrid, GRID2 *targetGrid, unsigned curNanoStep) { LOG(DBG, " frameUpdate(" << needsFlushing << ", " << updateFrame.boundingBox() << ", " << sourceIndex << ", " << targetIndex << ")"); if (needsFlushing) { // fixme: only works with cube topologies Coord<DIM> fillOrigin = buffers[omp_get_thread_num()].getOrigin(); fillOrigin[DIM - 1] = targetIndex; Coord<DIM> fillDim = buffers[omp_get_thread_num()].getDimensions(); fillDim[DIM - 1] = 1; // buffers[omp_get_thread_num()].fill( // CoordBox<DIM>(fillOrigin, fillDim), // buffers[omp_get_thread_num()].getEdgeCell()); } else { Coord<DIM> sourceOffset; Coord<DIM> targetOffset; sourceOffset[DIM - 1] = sourceIndex; targetOffset[DIM - 1] = targetIndex; UpdateFunctor<CELL>()(updateFrame, sourceOffset, targetOffset, sourceGrid, targetGrid, curNanoStep); } } // wraps the index (for 3D this will be the Z coordinate) around // the buffer's dimension int normalizeIndex(int localIndex) { int bufferSize = buffers[0].getDimensions()[DIM - 1]; return (localIndex + bufferSize) % bufferSize; } }; } #endif #endif
energy.h
#pragma once #include "core.h" #include "geometry.h" #include "space.h" #include "potentials.h" #include "multipole.h" #include "penalty.h" #include "mpi.h" #include <Eigen/Dense> #include <set> #ifdef ENABLE_POWERSASA #include <power_sasa.h> #endif namespace Faunus { namespace Energy { class Energybase { public: enum keys {OLD, NEW, NONE}; keys key=NONE; std::string name; std::string cite; virtual double energy(Change&)=0; //!< energy due to change virtual void to_json(json &j) const;; //!< json output virtual void sync(Energybase*, Change&); virtual void init(); //!< reset and initialize virtual inline void force(std::vector<Point> &forces) {}; // update forces on all particles }; void to_json(json &j, const Energybase &base); //!< Converts any energy class to json object /** * This holds Ewald setup and must *not* depend on particle type, nor depend on Space */ struct EwaldData { typedef std::complex<double> Tcomplex; Eigen::Matrix3Xd kVectors; // k-vectors, 3xK Eigen::VectorXd Aks; // 1xK, to minimize computational effort (Eq.24,DOI:10.1063/1.481216) Eigen::VectorXcd Qion, Qdip; // 1xK double alpha, rc, kc, check_k2_zero, lB; double const_inf, eps_surf; bool spherical_sum=true; bool ipbc=false; int kVectorsInUse=0; Point L; //!< Box dimensions void update(const Point &box); }; void from_json(const json &j, EwaldData &d); void to_json(json &j, const EwaldData &d); #ifdef DOCTEST_LIBRARY_INCLUDED TEST_CASE("[Faunus] Ewald - EwaldData") { using doctest::Approx; EwaldData data = R"({ "ipbc": false, "epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0, "kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json; data.update( Point(10,10,10) ); CHECK(data.ipbc == false); CHECK(data.const_inf == 1); CHECK(data.alpha == 0.894427190999916); CHECK(data.kVectors.cols() == 2975); CHECK(data.Qion.size() == data.kVectors.cols()); data.ipbc=true; data.update( Point(10,10,10) ); CHECK(data.kVectors.cols() == 846); CHECK(data.Qion.size() == data.kVectors.cols()); } #endif /** @brief recipe or policies for ion-ion ewald */ template<class Tspace, bool eigenopt=false /** use Eigen matrix ops where possible */> struct PolicyIonIon { typedef typename Tspace::Tpvec::iterator iter; Tspace *spc; Tspace *old=nullptr; // set only if key==NEW at first call to `sync()` PolicyIonIon(Tspace &spc) : spc(&spc) {} void updateComplex(EwaldData &data) const { if (eigenopt) if (data.ipbc==false) { auto pos = asEigenMatrix(spc->p.begin(), spc->p.end(), &Tspace::Tparticle::pos); // Nx3 auto charge = asEigenVector(spc->p.begin(), spc->p.end(), &Tspace::Tparticle::charge); // Nx1 Eigen::MatrixXd kr = pos.matrix() * data.kVectors; // Nx3 * 3xK = NxK data.Qion.real() = (kr.array().cos().colwise()*charge).colwise().sum(); data.Qion.imag() = kr.array().sin().colwise().sum(); return; } for (int k=0; k<data.kVectors.cols(); k++) { const Point& kv = data.kVectors.col(k); EwaldData::Tcomplex Q(0,0); if (data.ipbc) for (auto &i : spc->p) Q += kv.cwiseProduct(i.pos).array().cos().prod() * i.charge; else for (auto &i : spc->p) { double dot = kv.dot(i.pos); Q += i.charge * EwaldData::Tcomplex( std::cos(dot), std::sin(dot) ); } data.Qion[k] = Q; } } //!< Update all k vectors void updateComplex(EwaldData &data, iter begin, iter end) const { assert(old!=nullptr); assert(spc->p.size() == old->p.size()); size_t ibeg = std::distance(spc->p.begin(), begin); // it->index size_t iend = std::distance(spc->p.begin(), end); // it->index for (int k=0; k<data.kVectors.cols(); k++) { auto& Q = data.Qion[k]; Point q = data.kVectors.col(k); if (data.ipbc) for (size_t i=ibeg; i<=iend; i++) { Q += q.cwiseProduct( spc->p[i].pos ).array().cos().prod() * spc->p[i].charge; Q -= q.cwiseProduct( old->p[i].pos ).array().cos().prod() * old->p[i].charge; } else for (size_t i=ibeg; i<=iend; i++) { double _new = q.dot(spc->p[i].pos); double _old = q.dot(old->p[i].pos); Q += spc->p[i].charge * EwaldData::Tcomplex( std::cos(_new), std::sin(_new) ); Q -= old->p[i].charge * EwaldData::Tcomplex( std::cos(_old), std::sin(_old) ); } } } //!< Optimized update of k subset. Require access to old positions through `old` pointer double selfEnergy(const EwaldData &d) { double E = 0; for (auto& i : spc->p) E += i.charge * i.charge; return -d.alpha*E / std::sqrt(pc::pi) * d.lB; } double surfaceEnergy(const EwaldData &d) { if (d.const_inf < 0.5) return 0; Point qr(0,0,0); for (auto &i : spc->p) qr += i.charge*i.pos; return d.const_inf * 2 * pc::pi / ( (2*d.eps_surf+1) * spc->geo.getVolume() ) * qr.dot(qr) * d.lB; } double reciprocalEnergy(const EwaldData &d) { double E = 0; if (eigenopt) // known at compile time E = d.Aks.cwiseProduct( d.Qion.cwiseAbs2() ).sum(); else for (int k=0; k<d.Qion.size(); k++) E += d.Aks[k] * std::norm( d.Qion[k] ); return 2 * pc::pi / spc->geo.getVolume() * E * d.lB; } }; #ifdef DOCTEST_LIBRARY_INCLUDED TEST_CASE("[Faunus] Ewald - IonIonPolicy") { using doctest::Approx; typedef Space<Geometry::Cuboid, Particle<Charge,Dipole>> Tspace; Tspace spc; spc.p.resize(2); spc.geo = R"( {"length": 10} )"_json; spc.p[0] = R"( {"pos": [0,0,0], "q": 1.0} )"_json; spc.p[1] = R"( {"pos": [1,0,0], "q": -1.0} )"_json; PolicyIonIon<Tspace> ionion(spc); EwaldData data = R"({ "epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0, "kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json; data.ipbc = false; // PBC Ewald (http://dx.doi.org/10.1063/1.481216) data.update( spc.geo.getLength() ); ionion.updateComplex( data ); CHECK( ionion.selfEnergy(data) == Approx(-1.0092530088080642*data.lB) ); CHECK( ionion.surfaceEnergy(data) == Approx(0.0020943951023931952*data.lB) ); CHECK( ionion.reciprocalEnergy(data) == Approx(0.21303063979675319*data.lB) ); data.ipbc = true; // IPBC Ewald data.update( spc.geo.getLength() ); ionion.updateComplex( data ); CHECK( ionion.selfEnergy(data) == Approx(-1.0092530088080642*data.lB) ); CHECK( ionion.surfaceEnergy(data) == Approx(0.0020943951023931952*data.lB) ); CHECK( ionion.reciprocalEnergy(data) == Approx(0.0865107467*data.lB) ); } #endif /** @brief Ewald summation reciprocal energy */ template<class Tspace, class Policy=PolicyIonIon<Tspace>> class Ewald : public Energybase { private: EwaldData data; Policy policy; Tspace& spc; public: Ewald(const json &j, Tspace &spc) : policy(spc), spc(spc) { name = "ewald"; data = j; init(); } void init() override { data.update( spc.geo.getLength() ); policy.updateComplex(data); // brute force. todo: be selective } double energy(Change &change) override { double u=0; if (!change.empty()) { // If the state is NEW (trial state), then update all k-vectors if (key==NEW) { if (change.all || change.dV) { // everything changes data.update( spc.geo.getLength() ); policy.updateComplex(data); // update all (expensive!) } else { if (change.groups.size()==1) { // exactly one group is moved auto& d = change.groups[0]; auto& g = spc.groups[d.index]; if (d.atoms.size()==1) // exactly one atom is moved policy.updateComplex(data, g.begin()+d.atoms[0], g.begin()+d.atoms[0]); else policy.updateComplex(data, g.begin(), g.end()); } else policy.updateComplex(data); } } u = policy.selfEnergy(data) + policy.surfaceEnergy(data) + policy.reciprocalEnergy(data); } return u; } void sync(Energybase *basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); assert(other); if (other->key==OLD) policy.old = &(other->spc); // give NEW access to OLD space for optimized updates data = other->data; // copy everything! } //!< Called after a move is rejected/accepted as well as before simulation void to_json(json &j) const override { j = data; } }; template<typename Tspace> class Isobaric : public Energybase { private: Tspace& spc; double P; // P/kT public: Isobaric(const json &j, Tspace &spc) : spc(spc) { name = "isobaric"; cite = "Frenkel & Smith 2nd Ed (Eq. 5.4.13)"; P = j.value("P/mM", 0.0) * 1.0_mM; if (P<1e-10) { P = j.value("P/Pa", 0.0) * 1.0_Pa; if (P<1e-10) P = j.at("P/atm").get<double>() * 1.0_atm; } } double energy(Change &change) override { if (change.dV || change.all) { double V = spc.geo.getVolume(); size_t N=0; for (auto &g : spc.groups) if (!g.empty()) { if (g.atomic) N += g.size(); else N++; } return P*V-(N+1)*std::log(V); } else return 0; } void to_json(json &j) const override { j["P/atm"] = P / 1.0_atm; j["P/mM"] = P / 1.0_mM; j["P/Pa"] = P / 1.0_Pa; _roundjson(j,5); } }; /** * @brief Base class for external potentials * * This will apply an external energy to a defined * list of molecules, either acting on individual * atoms or the mass-center. The specific energy * function, `func` is injected in derived classes. */ template<typename Tspace> class ExternalPotential : public Energybase { protected: typedef typename Tspace::Tpvec Tpvec; typedef typename Tspace::Tparticle Tparticle; bool COM=false; // apply on center-of-mass Tspace& spc; std::set<int> molids; // molecules to act upon std::function<double(const Tparticle&)> func=nullptr; // energy of single particle std::vector<std::string> _names; template<class Tparticle> double _energy(const Group<Tparticle> &g) const { double u=0; if (molids.find(g.id) != molids.end()) { if (COM) { // apply only to center of mass Tparticle cm; cm.pos = g.cm; u = func(cm); } else { for (auto &p : g) { u += func(p); if (std::isnan(u)) break; } } } return u; } //!< External potential on a single particle public: ExternalPotential(const json &j, Tspace &spc) : spc(spc) { name="external"; COM = j.value("com", false); _names = j.at("molecules").get<decltype(_names)>(); // molecule names auto _ids = names2ids(molecules<Tpvec>, _names); // names --> molids molids = std::set<int>(_ids.begin(), _ids.end()); // vector --> set if (molids.empty() || molids.size()!=_names.size() ) throw std::runtime_error(name + ": molecule list is empty"); } double energy(Change &change) override { assert(func!=nullptr); double u=0; if (change.dV or change.all) { for (auto &g : spc.groups) { // check all groups u += _energy(g); if (std::isnan(u)) break; } } else for (auto &d : change.groups) { auto &g = spc.groups.at(d.index); // check specified groups if (d.all or COM) // check all atoms in group u += _energy(g); // _energy also checks for molecule id else { // check only specified atoms in group if (molids.find(g.id) != molids.end()) for (auto i : d.atoms) u += func( *(g.begin()+i) ); } if (std::isnan(u)) break; } return u; } void to_json(json &j) const override { j["molecules"] = _names; j["com"] = COM; } }; //!< Base class for external potentials, acting on particles /** * @brief Confines molecules inside geometric shapes */ template<typename Tspace, typename base=ExternalPotential<Tspace>> class Confine : public base { public: enum Variant {sphere, cylinder, cuboid, none}; Variant type=none; private: Point origo={0,0,0}, dir={1,1,1}; Point low, high; double radius, k; bool scale=false; std::map<std::string, Variant> m = { {"sphere", sphere}, {"cylinder", cylinder}, {"cuboid", cuboid} }; public: Confine(const json &j, Tspace &spc) : base(j,spc) { base::name = "confine"; k = value_inf(j, "k") * 1.0_kJmol; // get floating point; allow inf/-inf type = m.at( j.at("type") ); if (type==sphere or type==cylinder) { radius = j.at("radius"); origo = j.value("origo", origo); scale = j.value("scale", scale); if (type==cylinder) dir = {1,1,0}; base::func = [&radius=radius, origo=origo, k=k, dir=dir](const typename base::Tparticle &p) { double d2 = (origo-p.pos).cwiseProduct(dir).squaredNorm() - radius*radius; if (d2>0) return 0.5*k*d2; return 0.0; }; // If volume is scaled, also scale the confining radius by adding a trigger // to `Space::scaleVolume()` if (scale) spc.scaleVolumeTriggers.push_back( [&radius=radius](Tspace &spc, double Vold, double Vnew) { radius *= std::cbrt(Vnew/Vold); } ); } if (type==cuboid) { low = j.at("low").get<Point>(); high = j.at("high").get<Point>(); base::func = [low=low, high=high, k=k](const typename base::Tparticle &p) { double u=0; Point d = low-p.pos; for (int i=0; i<3; ++i) if (d[i]>0) u+=d[i]*d[i]; d = p.pos-high; for (int i=0; i<3; ++i) if (d[i]>0) u+=d[i]*d[i]; return 0.5*k*u; }; } } void to_json(json &j) const override { if (type==cuboid) j = {{"low", low}, {"high", high}}; if (type==sphere or type==cylinder) j = {{"radius", radius}}; if (type==sphere) { j["origo"] = origo; j["scale"] = scale; } for (auto &i : m) if (i.second==type) j["type"] = i.first; j["k"] = k/1.0_kJmol; base::to_json(j); _roundjson(j,5); } }; //!< Confine particles to a sub-region of the simulation container /* * The keys of the `intra` map are group index and the values * is a vector of `BondData`. For bonds between groups, fill * in `inter` which is evaluated for every update of call to * `energy`. * * @todo Optimize. */ template<typename Tspace> class Bonded : public Energybase { private: Tspace& spc; typedef typename Tspace::Tpvec Tpvec; typedef std::vector<std::shared_ptr<Potential::BondData>> BondVector; BondVector inter; // inter-molecular bonds std::map<int,BondVector> intra; // intra-molecular bonds void update() { using namespace Potential; intra.clear(); for (size_t i=0; i<spc.groups.size(); i++) { if (!spc.groups.empty()) { auto &g = spc.groups[i]; for (auto &b : molecules<Tpvec>.at(g.id).bonds) { intra[i].push_back( b->clone() ); // deep copy BondData from MoleculeData intra[i].back()->shift( std::distance(spc.p.begin(), g.begin()) ); Potential::setBondEnergyFunction( intra[i].back(), spc.p ); } } } } // finds and adds all intra-molecular bonds of active molecules double sum( const BondVector &v ) const { double u=0; for (auto &b : v) { assert(b->hasEnergyFunction()); u += b->energy(spc.geo.distanceFunc); } return u; } // sum energy in vector of BondData public: Bonded(const json &j, Tspace &spc) : spc(spc) { name = "bonded"; update(); if (j.is_object()) if (j.count("bondlist")==1) inter = j["bondlist"].get<BondVector>(); for (auto &i : inter) // set all energy functions Potential::setBondEnergyFunction( i, spc.p ); } void to_json(json &j) const override { if (!inter.empty()) j["bondlist"] = inter; if (!intra.empty()) { json& _j = j["bondlist-intramolecular"]; _j = json::array(); for (auto &i : intra) for (auto &b : i.second) _j.push_back(b); } } double energy(Change &c) override { double u=0; if ( !c.empty() ) { u = sum(inter); // energy of inter-molecular bonds if ( c.all || c.dV ) { for (auto& i : intra) // energy of intra-molecular bonds if (!spc.groups[i.first].empty()) // add only if group is active u += sum(i.second); } else for (auto &d : c.groups) if (d.internal) u += sum( intra[d.index] ); } return u; }; // brute force -- refine this! }; /** * @brief Nonbonded energy using a pair-potential */ template<typename Tspace, typename Tpairpot> class Nonbonded : public Energybase { private: double g2gcnt=0, g2gskip=0; protected: typedef typename Tspace::Tgroup Tgroup; double Rc2_g2g=pc::infty; void to_json(json &j) const override { j["pairpot"] = pairpot; j["cutoff_g2g"] = std::sqrt(Rc2_g2g); } template<typename T> inline bool cut(const T &g1, const T &g2) { g2gcnt++; if (g1.atomic || g2.atomic) return false; if ( spc.geo.sqdist(g1.cm, g2.cm)<Rc2_g2g ) return false; g2gskip++; return true; } //!< true if group<->group interaction can be skipped template<typename T> inline double i2i(const T &a, const T &b) { assert(&a!=&b && "a and b cannot be the same particle"); return pairpot(a, b, spc.geo.vdist(a.pos, b.pos)); } /* * Internal energy in group, calculating all with all or, if `index` * is given, only a subset. Index specifies the internal index (starting * at zero) of changed particles within the group. */ double g_internal(const Tgroup &g, const std::vector<int> &index=std::vector<int>()) { using namespace ranges; double u=0; if (index.empty()) // assume that all atoms have changed for ( auto i = g.begin(); i != g.end(); ++i ) for ( auto j=i; ++j != g.end(); ) u += i2i(*i, *j); else { // only a subset have changed auto fixed = view::ints( 0, int(g.size()) ) | view::remove_if( [&index](int i){return std::binary_search(index.begin(), index.end(), i);}); for (int i : index) {// moved<->static for (int j : fixed ) { u += i2i( *(g.begin()+i), *(g.begin()+j)); } } for (int i : index) // moved<->moved for (int j : index) if (j>i) { u += i2i( *(g.begin()+i), *(g.begin()+j)); } } return u; } /* * Calculates the interaction energy of a particle, `i`, * and checks (1) if it is already part of Space, or (2) * external to space. */ double i2all(const typename Tspace::Tparticle &i) { double u=0; auto it = spc.findGroupContaining(i); // iterator to group if (it!=spc.groups.end()) { // check if i belongs to group in space for (auto &g : spc.groups) // i with all other particles if (&g!=&(*it)) // avoid self-interaction if (!cut(g, *it)) // check g2g cut-off for (auto &j : g) // loop over particles in other group u += i2i(i,j); for (auto &j : *it) // i with all particles in own group if (&j!=&i) u += i2i(i,j); } else // particle does not belong to any group for (auto &g : spc.groups) // i with all other *active* particles for (auto &j : g) // (this will include only active particles) u += i2i(i,j); return u; } /* * Group-to-group energy. A subset of `g1` can be given with `index` which refers * to the internal index (starting at zero) of the first group, `g1 * NOTE: the interpretation of this function is extended to also consider the mutual interactions * of a subset of each group and in such case returns sub1 <-> 2 and !sub1<->sub2, * hence excluding !sub1 <-> !sub2 in comparision to calling onconstrained g2g. In absence * of sub1 any sub2 is ignored. */ virtual double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index=std::vector<int>(), const std::vector<int> &jndex=std::vector<int>()) { using namespace ranges; double u = 0; if (!cut(g1,g2)) { if ( index.empty() && jndex.empty() ) // if index is empty, assume all in g1 have changed for (auto &i : g1) for (auto &j : g2) { u += i2i(i,j); } else {// only a subset of g1 for (auto i : index) for (auto j=g2.begin(); j!=g2.end(); ++j) { u += i2i( *(g1.begin()+i), *j); } if ( !jndex.empty() ) { auto fixed = view::ints( 0, int(g1.size()) ) | view::remove_if( [&index](int i){return std::binary_search(index.begin(), index.end(), i);}); for (auto i : jndex) // moved2 <-| for (auto j : fixed) {// static1 <-| u += i2i( *(g2.begin()+i), *(g1.begin()+j)); } } } } return u; } public: Tspace& spc; //!< Space to operate on Tpairpot pairpot; //!< Pair potential Nonbonded(const json &j, Tspace &spc) : spc(spc) { name="nonbonded"; pairpot = j; Rc2_g2g = std::pow( j.value("cutoff_g2g", pc::infty), 2); } void force(std::vector<Point> &forces) override { auto &p = spc.p; // alias to particle vector (reference) assert(forces.size() == p.size() && "the forces size must match the particle size"); for (size_t i=0; i<p.size()-1; i++) for (size_t j=i+1; j<p.size(); j++) { Point r = spc.geo.vdist(p[i].pos, p[j].pos); // minimum distance vector Point f ;//= pairpot.force( p[i], p[j], r.squaredNorm(), r ); forces[i] += f; forces[j] -= f; } } double energy(Change &change) override { using namespace ranges; double u=0; if (!change.empty()) { if (change.dV) { #pragma omp parallel for reduction (+:u) schedule (dynamic) for ( auto i = spc.groups.begin(); i < spc.groups.end(); ++i ) { for ( auto j=i; ++j != spc.groups.end(); ) u += g2g( *i, *j ); if (i->atomic) u += g_internal(*i); } return u; } // did everything change? if (change.all) { #pragma omp parallel for reduction (+:u) schedule (dynamic) for ( auto i = spc.groups.begin(); i < spc.groups.end(); ++i ) { for ( auto j=i; ++j != spc.groups.end(); ) u += g2g( *i, *j ); u += g_internal(*i); } // more todo here... return u; } // if exactly ONE molecule is changed if (change.groups.size()==1 && !change.dNpart) { auto& d = change.groups[0]; auto gindex = spc.groups.at(d.index).to_index(spc.p.begin()).first; if (d.atoms.size()==1) // exactly one atom has moved return i2all(spc.p.at(gindex+d.atoms[0])); auto& g1 = spc.groups.at(d.index); for (auto &g2 : spc.groups) if (&g1 != &g2) u += g2g(g1, g2, d.atoms); if (d.internal) u += g_internal(g1, d.atoms); return u; } // if (change.dNpart) { auto moved = change.touchedGroupIndex(); // index of moved groups std::vector<int> Moved; for (auto i: moved) Moved.push_back(i); std::sort( Moved.begin(), Moved.end() ); auto fixed = view::ints( 0, int(spc.groups.size()) ) | view::remove_if( [&Moved](int i){return std::binary_search(Moved.begin(), Moved.end(), i);} ); // index of static groups for ( auto cg1 = change.groups.begin(); cg1 < change.groups.end() ; ++cg1 ) { // Loop over all changed groups std::vector<int> ifiltered, jfiltered; for (auto i: cg1->atoms) { if ( i < spc.groups.at(cg1->index).size() ) ifiltered.push_back(i); } if ( !( cg1->dNpart && ifiltered.empty() ) ) // Skip if particles are removed for ( auto j : fixed) { u += g2g( spc.groups.at(cg1->index), spc.groups[j], ifiltered, jfiltered ); } for ( auto cg2 = cg1; ++cg2 != change.groups.end(); ) { for (auto i: cg2->atoms) if ( i < spc.groups.at(cg2->index).size() ) jfiltered.push_back(i); if ( !( (cg1->dNpart && ifiltered.empty()) && (cg2->dNpart && jfiltered.empty()) ) ) //Skip if particles are removed from both u += g2g( spc.groups.at(cg1->index), spc.groups.at(cg2->index), ifiltered, jfiltered ); jfiltered.clear(); } if ( ifiltered.size() != 0 ) u += g_internal( spc.groups.at( cg1->index ), ifiltered ); } return u; } auto moved = change.touchedGroupIndex(); // index of moved groups auto fixed = view::ints( 0, int(spc.groups.size()) ) | view::remove_if( [&moved](int i){return std::binary_search(moved.begin(), moved.end(), i);} ); // index of static groups // moved<->moved for ( auto i = moved.begin(); i != moved.end(); ++i ) { for ( auto j=i; ++j != moved.end(); ) u += g2g( spc.groups[*i], spc.groups[*j] ); } // moved<->static for ( auto i : moved) for ( auto j : fixed) u += g2g(spc.groups[i], spc.groups[j]); // more todo! } return u; } }; //!< Nonbonded, pair-wise additive energy term template<typename Tspace, typename Tpairpot> class NonbondedCached : public Nonbonded<Tspace,Tpairpot> { private: typedef Nonbonded<Tspace,Tpairpot> base; typedef typename Tspace::Tgroup Tgroup; Eigen::MatrixXf cache; Tspace &spc; double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index=std::vector<int>(), const std::vector<int> &jndex=std::vector<int>()) override { int i = &g1 - &base::spc.groups.front(); int j = &g2 - &base::spc.groups.front(); if (j<i) std::swap(i,j); if (base::key==Energybase::NEW) { // if this is from the trial system, double u = 0; if (!base::cut(g1,g2)) { for (auto &i : g1) for (auto &j : g2) u += base::i2i(i,j); } cache(i,j) = u; } return cache(i,j); // return (cached) value } public: NonbondedCached(const json &j, Tspace &spc) : base(j,spc), spc(spc) { base::name += "EM"; init(); } void init() override { cache.resize( spc.groups.size(), spc.groups.size() ); cache.setZero(); for ( auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i ) { for ( auto j=i; ++j != base::spc.groups.end(); ) { int k = &(*i) - &base::spc.groups.front(); int l = &(*j) - &base::spc.groups.front(); if (l<k) std::swap(k,l); double u = 0; if (!base::cut(*i,*j)) { for (auto &k : *i) for (auto &l : *j) u += base::i2i(k,l); } cache(k,l) = u; } } } //!< Cache pair interactions in matrix double energy(Change &change) override { using namespace ranges; double u=0; if (!change.empty()) { if (change.all || change.dV) { #pragma omp parallel for reduction (+:u) schedule (dynamic) for ( auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i ) { for ( auto j=i; ++j != base::spc.groups.end(); ) u += g2g( *i, *j ); } return u; } // if exactly ONE molecule is changed if (change.groups.size()==1) { auto& d = change.groups[0]; auto& g1 = base::spc.groups.at(d.index); for (auto &g2 : base::spc.groups) { if (&g1 != &g2) u += g2g(g1, g2, d.atoms); } return u; } auto moved = change.touchedGroupIndex(); // index of moved groups auto fixed = view::ints( 0, int(base::spc.groups.size()) ) | view::remove_if( [&moved](int i){return std::binary_search(moved.begin(), moved.end(), i);} ); // index of static groups // moved<->moved for ( auto i = moved.begin(); i != moved.end(); ++i ) for ( auto j=i; ++j != moved.end(); ) { u += g2g( base::spc.groups[*i], base::spc.groups[*j] ); } // moved<->static for ( auto i : moved) for ( auto j : fixed) u += g2g(base::spc.groups[i], base::spc.groups[j]); // more todo! } return u; } void sync(Energybase *basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); assert(other); if (change.all || change.dV) cache.triangularView<Eigen::StrictlyUpper>() = (other->cache).template triangularView<Eigen::StrictlyUpper>(); else for (auto &d : change.groups) { for (int i=0; i<d.index; i++) cache(i,d.index) = other->cache(i,d.index); for (size_t i=d.index+1; i<base::spc.groups.size(); i++) cache(d.index,i) = other->cache(d.index,i); } } //!< Copy energy matrix from other }; //!< Nonbonded with cached energies (Energy Matrix) /** * `udelta` is the total change of updating the energy function. If * not handled this will appear as an energy drift (which it is!). To * avoid this, this term is added to the energy but since it's the * same in both the trial and old state energies it will not affect * MC move acceptance. */ template<typename Tspace> class Penalty : public Energybase { protected: typedef typename Tspace::Tparticle Tparticle; typedef typename Tspace::Tgroup Tgroup; typedef typename Tspace::Tpvec Tpvec; typedef typename std::shared_ptr<ReactionCoordinate::ReactionCoordinateBase> Tcoord; Tspace &spc; bool nodrift; bool quiet; size_t dim=0; size_t cnt=0; // number of calls to `sync()` size_t nupdate; // update frequency [steps] size_t samplings; size_t nconv=0; double udelta=0; // total energy change of updating penalty function double scale; // scaling factor for f0 double f0; // penalty increment std::string file, hisfile; std::vector<Tcoord> rcvec; // vector of reaction coordinate functions std::vector<double> coord; // latest reaction coordinate Table<int> histo; Table<double> penalty; public: Penalty(const json &j, Tspace &spc) : spc(spc) { using namespace ReactionCoordinate; name = "penalty"; f0 = j.value("f0", 0.5); scale = j.value("scale", 0.8); quiet = j.value("quiet", true); nupdate = j.value("update", 0); samplings = j.value("samplings", 1); nodrift = j.value("nodrift", true); file = j.at("file").get<std::string>(); hisfile = j.value("histogram", "penalty-histogram.dat"); std::vector<double> binwidth, min, max; if (scale<0 or scale>1) throw std::runtime_error("`scale` must be in the interval [0:1]"); for (auto &i : j.at("coords")) if (i.is_object()) if (i.size()==1) { std::shared_ptr<ReactionCoordinate::ReactionCoordinateBase> rc=nullptr; for (auto it=i.begin(); it!=i.end(); ++it) { if (it.key()=="atom") rc = std::make_shared<AtomProperty>(it.value(), spc); if (it.key()=="system") rc = std::make_shared<SystemProperty>(it.value(), spc); if (it.key()=="cmcm") rc = std::make_shared<MassCenterSeparation>(it.value(), spc); if (it.key()=="angle") rc = std::make_shared<PrincipalAxisAngle>(it.value(), spc); if (rc!=nullptr) { if (rc->min>=rc->max || rc->binwidth<=0) throw std::runtime_error("min<max and binwidth>0 required for '" + it.key() + "'"); rcvec.push_back(rc); binwidth.push_back( rc->binwidth ); min.push_back( rc->min ); max.push_back( rc->max ); } else throw std::runtime_error("unknown coordinate type '" + it.key() + "'"); } } dim = binwidth.size(); if (dim<1 || dim>2) throw std::runtime_error("minimum one maximum two coordinates required"); coord.resize(rcvec.size(), 0); histo.reInitializer(binwidth, min, max); penalty.reInitializer(binwidth, min, max); std::ifstream f(MPI::prefix+file); if (f) { cout << "Loading penalty function '" << MPI::prefix+file << "'" << endl; std::string hash; f >> hash >> f0 >> samplings; for (int row=0; row<penalty.rows(); row++) for (int col=0; col<penalty.cols(); col++) if (not f.eof()) f >> penalty(row,col); else throw std::runtime_error("penalty file dimension mismatch"); } } virtual ~Penalty() { std::ofstream f1(MPI::prefix + file), f2(MPI::prefix + hisfile); if (f1) f1 << "# " << f0 << " " << samplings << "\n" << penalty.array() - penalty.minCoeff() << "\n"; if (f2) f2 << histo << "\n"; // add function to save to numpy-friendly file... } void to_json(json &j) const override { j["file"] = file; j["scale"] = scale; j["update"] = nupdate; j["nodrift"] = nodrift; j["histogram"] = hisfile; j["f0_final"] = f0; auto& _j = j["coords"] = json::array(); for (auto rc : rcvec) { json t; t[rc->name] = *rc; _j.push_back(t); } } double energy(Change &change) override { assert(rcvec.size()<=coord.size()); double u=0; coord.resize( rcvec.size() ); if (!change.empty()) { for (size_t i=0; i<rcvec.size(); i++) { coord.at(i) = rcvec[i]->operator()(); if ( not rcvec[i]->inRange(coord[i]) ) return pc::infty; } penalty.to_index(coord); u = penalty[coord]; } return (nodrift) ? u - udelta : u; } /* * @todo: If this is called before `energy()`, the coord * is never calculated and causes indefined behavior */ virtual void update(const std::vector<double> &c) { if (++cnt % nupdate == 0 and f0>0) { bool b = histo.minCoeff() >= (int)samplings; if (b) { double min = penalty.minCoeff(); penalty = penalty.array() - min; if (not quiet) cout << "Barriers/kT. Penalty=" << penalty.maxCoeff() << " Histogram=" << std::log(double(histo.maxCoeff())/histo.minCoeff()) << endl; f0 = f0 * scale; // reduce penalty energy samplings = std::ceil( samplings / scale ); histo.setZero(); udelta += -min; } } coord = c; histo[coord]++; penalty[coord] += f0; udelta += f0; } void sync(Energybase *basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); assert(other); update(other->coord); // is inside allowed range other->update(other->coord); } // @todo: this doubles the MPI communication }; #ifdef ENABLE_MPI template<typename Tspace, typename Base=Penalty<Tspace>> struct PenaltyMPI : public Base { using Base::samplings; using Base::penalty; using Base::udelta; using Base::scale; using Base::histo; using Base::coord; using Base::cnt; using Base::f0; using Base::file; using Base::hisfile; using Base::nconv; Eigen::VectorXi weights; // array w. mininum histogram counts Eigen::VectorXd buffer; // receive buffer for penalty functions PenaltyMPI(const json &j, Tspace &spc) : Base(j,spc) { weights.resize( MPI::mpi.nproc() ); buffer.resize( penalty.size()*MPI::mpi.nproc() ); } void update(const std::vector<double> &c) override { using namespace Faunus::MPI; double uold = penalty[c]; if (++cnt % this->nupdate == 0 and f0>0) { int min = histo.minCoeff(); MPI_Barrier(mpi.comm); MPI_Allgather(&min, 1, MPI_INT, weights.data(), 1, MPI_INT, mpi.comm); if ( weights.maxCoeff() > samplings ) { MPI_Gather(penalty.data(), penalty.size(), MPI_DOUBLE, buffer.data(), penalty.size(), MPI_DOUBLE, 0, mpi.comm); if (mpi.isMaster()) { penalty.setZero(); for (int i=0; i<mpi.nproc(); i++) penalty += Eigen::Map<Eigen::MatrixXd>( buffer.data()+i*penalty.size(), penalty.rows(), penalty.cols() ); penalty = ( penalty.array() - penalty.minCoeff() ) / double(mpi.nproc()); } MPI_Bcast(penalty.data(), penalty.size(), MPI_DOUBLE, 0, mpi.comm); nconv += 1; std::ofstream f3(MPI::prefix + std::to_string(nconv) + file); if (f3) f3 << "# " << f0 << " " << samplings << "\n" << penalty.array() << endl; std::ofstream f4(MPI::prefix + std::to_string(nconv) + hisfile); if (f4) f4 << histo << endl; if (min>0 && !this->quiet) cout << "Barriers/kT. Penalty=" << penalty.maxCoeff() << " Histogram=" << std::log(double(histo.maxCoeff())/histo.minCoeff()) << endl; histo.setZero(); f0 = f0 * scale; // reduce penalty energy samplings = std::ceil( samplings / scale ); } } coord = c; histo[coord]++; penalty[coord] += f0; udelta += penalty[coord] - uold; } //!< Average penalty function across all nodes }; //!< Penalty function with MPI exchange #endif #ifdef ENABLE_POWERSASA /* * @todo: * - can only a subset of sasa be calculated? Note that it's the * `update_coord()` function that takes up most time. * - delegate to GPU? In the PowerSasa paper this is mentioned */ template<class Tspace> class SASAEnergy : public Energybase { public: std::vector<float> sasa, radii; private: typedef typename Tspace::Tparticle Tparticle; typedef typename Tspace::Tpvec Tpvec; Tspace& spc; double probe; // sasa probe radius (angstrom) double conc=0;// co-solute concentration (mol/l) Average<double> avgArea; // average surface area std::shared_ptr<POWERSASA::PowerSasa<float,Point>> ps=nullptr; void updateSASA(const Tpvec &p) { assert(ps != nullptr); radii.resize(p.size()); std::transform(p.begin(), p.end(), radii.begin(), [this](auto &a){ return atoms<Tparticle>[a.id].sigma*0.5 + this->probe;}); ps->update_coords(spc.positions(), radii); // slowest step! for (size_t i=0; i<p.size(); i++) { auto &a = atoms<Tparticle>[p[i].id]; if (std::fabs(a.tfe)>1e-9 || std::fabs(a.tension)>1e-9) ps->calc_sasa_single(i); } sasa = ps->getSasa(); assert(sasa.size()==p.size()); } void to_json(json &j) const override { using namespace u8; j["molarity"] = conc / 1.0_molar; j["radius"] = probe / 1.0_angstrom; j[bracket("SASA")+"/"+angstrom+squared] = avgArea.avg() / 1.0_angstrom; _roundjson(j,5); } /* * @note * This is not enough as the PowerSasa object contains data * that also need syncing. It works due to the `update` (expensive!) * call in `energy`. */ void sync(Energybase *basePtr, Change &c) override { auto other = dynamic_cast<decltype(this)>(basePtr); if (other) { if (c.all || c.dV) { radii = other->radii; sasa = other->sasa; } else { for (auto &d : c.groups) { int offset = std::distance(spc.p.begin(), spc.groups.at(d.index).begin()); for (int j : d.atoms) { int i = j + offset; radii[i] = other->radii[i]; sasa[i] = other->sasa[i]; } } } } } public: SASAEnergy(const json &j, Tspace &spc) : spc(spc) { name = "sasa"; cite = "doi:10.1002/jcc.21844"; probe = j.value("radius", 1.4) * 1.0_angstrom; conc = j.at("molarity").get<double>() * 1.0_molar; init(); } void init() override { radii.resize( spc.p.size() ); std::transform( spc.p.begin(), spc.p.end(), radii.begin(), [this](auto &a){ return atoms<Tparticle>[a.id].sigma*0.5 + this->probe;} ); if (ps==nullptr) ps = std::make_shared<POWERSASA::PowerSasa<float,Point>>(spc.positions(),radii); updateSASA(spc.p); } double energy(Change &change) override { double u=0, A=0; /* * ideally we want to call `update` only if `key==NEW` but * syncronising the PowerSasa object is difficult since it's * non-copyable. */ updateSASA(spc.p); // ideally we want for (size_t i=0; i<spc.p.size(); ++i) { auto &a = atoms<Tparticle>[ spc.p[i].id ]; u += sasa[i] * (a.tension + conc * a.tfe); A += sasa[i]; } avgArea+=A; // sample average area for accepted confs. only return u; } }; //!< SASA energy from transfer free energies #endif struct Example2D : public Energybase { Point& i; // reference to 1st particle in the system template<typename Tspace> Example2D(const json &j, Tspace &spc): i(spc.p.at(0).pos) { name = "Example2D"; } double energy(Change &change) override; }; template<typename Tspace> class Hamiltonian : public Energybase, public BasePointerVector<Energybase> { protected: double maxenergy=pc::infty; //!< Maximum allowed energy change typedef typename Tspace::Tparticle Tparticle; void to_json(json &j) const override { for (auto i : this->vec) j.push_back(*i); } void addEwald(const json &j, Tspace &spc) { if (j.count("coulomb")==1) if (j["coulomb"].at("type")=="ewald") push_back<Energy::Ewald<Tspace>>(j["coulomb"], spc); } //!< Adds an instance of reciprocal space Ewald energies (if appropriate) public: Hamiltonian(Tspace &spc, const json &j) { using namespace Potential; typedef CombinedPairPotential<CoulombGalore,LennardJones<Tparticle>> CoulombLJ; typedef CombinedPairPotential<CoulombGalore,HardSphere<Tparticle>> CoulombHS; typedef CombinedPairPotential<CoulombGalore,WeeksChandlerAndersen<Tparticle>> CoulombWCA; typedef CombinedPairPotential<Coulomb,WeeksChandlerAndersen<Tparticle>> PrimitiveModelWCA; Energybase::name="hamiltonian"; for (auto &m : j.at("energy")) {// loop over move list size_t oldsize = vec.size(); for (auto it=m.begin(); it!=m.end(); ++it) { try { if (it.key()=="nonbonded_coulomblj") push_back<Energy::Nonbonded<Tspace,CoulombLJ>>(it.value(), spc); if (it.key()=="nonbonded") push_back<Energy::Nonbonded<Tspace,FunctorPotential<typename Tspace::Tparticle>>>(it.value(), spc); if (it.key()=="nonbonded_coulombhs") push_back<Energy::Nonbonded<Tspace,CoulombHS>>(it.value(), spc); if (it.key()=="nonbonded_coulombwca") push_back<Energy::Nonbonded<Tspace,CoulombWCA>>(it.value(), spc); if (it.key()=="nonbonded_pmwca") push_back<Energy::Nonbonded<Tspace,PrimitiveModelWCA>>(it.value(), spc); if (it.key()=="nonbonded_deserno") push_back<Energy::NonbondedCached<Tspace,DesernoMembrane<typename Tspace::Tparticle>>>(it.value(), spc); if (it.key()=="nonbonded_desernoAA") push_back<Energy::NonbondedCached<Tspace,DesernoMembraneAA<typename Tspace::Tparticle>>>(it.value(), spc); if (it.key()=="bonded") push_back<Energy::Bonded<Tspace>>(it.value(), spc); if (it.key()=="confine") push_back<Energy::Confine<Tspace>>(it.value(), spc); if (it.key()=="example2d") push_back<Energy::Example2D>(it.value(), spc); if (it.key()=="isobaric") push_back<Energy::Isobaric<Tspace>>(it.value(), spc); if (it.key()=="penalty") #ifdef ENABLE_MPI push_back<Energy::PenaltyMPI<Tspace>>(it.value(), spc); #else push_back<Energy::Penalty<Tspace>>(it.value(), spc); #endif #ifdef ENABLE_POWERSASA if (it.key()=="sasa") push_back<Energy::SASAEnergy<Tspace>>(it.value(), spc); #endif // additional energies go here... addEwald(it.value(), spc); // add reciprocal Ewald terms if appropriate if (it.key()=="maxenergy") { maxenergy = it.value().get<double>(); continue; } if (vec.size()==oldsize) throw std::runtime_error("unknown term"); } catch (std::exception &e) { throw std::runtime_error("Error adding energy '" + it.key() + "': " + e.what()); } } } } double energy(Change &change) override { double du=0; for (auto i : this->vec) { i->key=key; du += i->energy(change); if (du>maxenergy) break; // stop summing energies } return du; } //!< Energy due to changes void init() override { for (auto i : this->vec) i->init(); } void sync(Energybase* basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); if (other) if (other->size()==size()) { for (size_t i=0; i<size(); i++) this->vec[i]->sync( other->vec[i].get(), change ); return; } throw std::runtime_error("hamiltonian mismatch"); } }; //!< Aggregates and sum energy terms }//namespace }//namespace
integrator_sei.c
/** * @file integrator_sei.c * @brief Symplectic Epicycle Integrator (SEI). * @author Hanno Rein <hanno@hanno-rein.de> * @details This file implements the Symplectic Epicycle Integrator * (SEI). The integrator is described in detail in Rein & Tremaine 2011. * It solves epicyclic motion exactly and is therefore exact up to machine * precision in the limit of no perturbing forces. When perturbing-forces * are of order eps, then the error of the scheme is O(eps dt^3). It also * makes use of two shear operators instead of a rotation to minimize * systematic numerical round-off errors. * * @section LICENSE * Copyright (c) 2011 Hanno Rein, Shangfei Liu * * This file is part of rebound. * * rebound 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. * * rebound 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 rebound. If not, see <http://www.gnu.org/licenses/>. * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include <time.h> #include "rebound.h" #include "particle.h" #include "gravity.h" #include "boundary.h" #include "integrator.h" #include "integrator_sei.h" static void operator_H012(double dt, const struct reb_simulation_integrator_sei ri_sei, struct reb_particle* p); static void operator_phi1(double dt, struct reb_particle* p); void reb_integrator_sei_init(struct reb_simulation* const r){ /** * Pre-calculates sin() and tan() needed for SEI. */ r->ri_sei.sindt = sin(r->ri_sei.OMEGA*(-r->dt/2.)); r->ri_sei.tandt = tan(r->ri_sei.OMEGA*(-r->dt/4.)); r->ri_sei.sindtz = sin(r->ri_sei.OMEGAZ*(-r->dt/2.)); r->ri_sei.tandtz = tan(r->ri_sei.OMEGAZ*(-r->dt/4.)); r->ri_sei.lastdt = r->dt; } void reb_integrator_sei_part1(struct reb_simulation* const r){ r->gravity_ignore_terms = 0; const int N = r->N; struct reb_particle* const particles = r->particles; if (r->ri_sei.OMEGAZ==-1){ r->ri_sei.OMEGAZ=r->ri_sei.OMEGA; } if (r->ri_sei.lastdt!=r->dt){ reb_integrator_sei_init(r); } const struct reb_simulation_integrator_sei ri_sei = r->ri_sei; #pragma omp parallel for schedule(guided) for (int i=0;i<N;i++){ operator_H012(r->dt, ri_sei, &(particles[i])); } r->t+=r->dt/2.; } void reb_integrator_sei_part2(struct reb_simulation* r){ const int N = r->N; struct reb_particle* const particles = r->particles; const struct reb_simulation_integrator_sei ri_sei = r->ri_sei; #pragma omp parallel for schedule(guided) for (int i=0;i<N;i++){ operator_phi1(r->dt, &(particles[i])); operator_H012(r->dt, ri_sei, &(particles[i])); } r->t+=r->dt/2.; r->dt_last_done = r->dt; } void reb_integrator_sei_synchronize(struct reb_simulation* r){ // Do nothing. } void reb_integrator_sei_reset(struct reb_simulation* r){ r->ri_sei.lastdt = 0; } /** * @brief This function evolves a particle under the unperturbed * Hamiltonian H0 exactly up to machine precission. * @param p reb_particle to evolve. * @param dt Timestep * @param ri_sei Integrator struct */ static void operator_H012(double dt, const struct reb_simulation_integrator_sei ri_sei, struct reb_particle* p){ // Integrate vertical motion const double zx = p->z * ri_sei.OMEGAZ; const double zy = p->vz; // Rotation implemeted as 3 shear operators // to avoid round-off errors const double zt1 = zx - ri_sei.tandtz*zy; const double zyt = ri_sei.sindtz*zt1 + zy; const double zxt = zt1 - ri_sei.tandtz*zyt; p->z = zxt/ri_sei.OMEGAZ; p->vz = zyt; // Integrate motion in xy directions const double aO = 2.*p->vy + 4.*p->x*ri_sei.OMEGA; // Center of epicyclic motion const double bO = p->y*ri_sei.OMEGA - 2.*p->vx; const double ys = (p->y*ri_sei.OMEGA-bO)/2.; // Epicycle vector const double xs = (p->x*ri_sei.OMEGA-aO); // Rotation implemeted as 3 shear operators // to avoid round-off errors const double xst1 = xs - ri_sei.tandt*ys; const double yst = ri_sei.sindt*xst1 + ys; const double xst = xst1 - ri_sei.tandt*yst; p->x = (xst+aO) /ri_sei.OMEGA; p->y = (yst*2.+bO) /ri_sei.OMEGA - 3./4.*aO*dt; p->vx = yst; p->vy = -xst*2. -3./2.*aO; } /** * @brief This function applies the acceleration due to the PHI1 term. * @details It is only exact if the forces are velocity independet (i.e. gravity). * If the forces are velocity dependent, it breaks the symmetry of the scheme, * making it firsr-order and non-symplectic. As long as these forces are small, * this should not be visible. However, it is worth keeping in mind. * @param p reb_particle to evolve. * @param dt Timestep */ static void operator_phi1(double dt, struct reb_particle* p){ // The force used here is for test cases 2 and 3 // in Rein & Tremaine 2011. p->vx += p->ax * dt; p->vy += p->ay * dt; p->vz += p->az * dt; }
rabin_karp_1.h
#pragma once #include "core_types.h" #include "utils.h" #include "string_matcher.h" #include <vector> #include <string> class RabinKarp1 : StringMatcher { private: uint32 k; std::vector<uint32> patHash; std::vector<uint32> textHash; std::vector<uint32> firstPower; std::vector<uint32> p; uint32 M = 1024; uint32 base = 2; public: explicit RabinKarp1(const std::string& pat, uint32 k = 10) : k(k), StringMatcher(pat), patHash(k), textHash(k), p(k), firstPower(k) { } void preprocess(const std::string& text) { for (uint32 i = 0; i < k; i++) { patHash[i] = 0; textHash[i] = 0; } for (uint32 i = 0; i < k; i++) { firstPower[i] = 1; for (uint32 _ = 0; _ < patLength - 1; _++) { firstPower[i] = (base * firstPower[i]) % p[i]; } } // Could be easily computed in parallel //#pragma omp parallel for schedule(static) for (uint32 i = 0; i < k ; i++) { for (uint32 j = 0; j < patLength; j++) { patHash[i] = (base * patHash[i] + pat[j]) % p[i]; textHash[i] = (base * textHash[i] + text[j]) % p[i]; } } } void updateTextHash(uint32 i, const std::string& text) { // Could be easily computed in parallel //#pragma omp parallel for schedule(static) for (uint32 j = 0; j < k; j++) { textHash[j] = (textHash[j] + p[j] - (text[i] * firstPower[j]) % p[j]) % p[j]; textHash[j] = (textHash[j] * base + text[i + patLength]) % p[j]; } } bool searchIn(const std::string& text, uint32* offset) override { for (uint32 i = 0; i < k; i++) { p[i] = generatePrime(); } preprocess(text); uint32 textLength = text.length(); for (uint32 i = 0; i <= textLength - patLength; i++) { bool match = true; for (uint32 j = 0; j < k; j++) { if (patHash[j] != textHash[j]) { match = false; } } if (match) { *offset = i; return true; } if (i < textLength - patLength) { updateTextHash(i, text); } } return false; } uint32 generatePrime() { uint32 random = 1 + rand() % M; while (!isPrime(random)) { random = 1 + rand() % M; } return random; } };
newton-bisection.c
#include "header.h" /** Numerically calculates the derivative of the function pointed to by fun_ptr using central difference. **/ double derive(double (*fun_ptr)(double), double x) { const double dx = 1e-6; return 1.0/(2.0*dx) * ((*fun_ptr)(x+dx) - (*fun_ptr)(x-dx)); } /** Finds all zeros in the interval [a, b]. This procedure divides the interval [a, b] into N smaller subintervals and then uses Newton-bisection on each of the subintervals. **/ array *find_all_zeros_NR(double (*fun_ptr)(double), double a, double b, int N, int T) { array *zeros = malloc(sizeof(array)); zeros->ptr = malloc(N*sizeof(double)); zeros->size = 0; double dn = (b-a)/((double) N); double xl, xu; int chunk = ceil(N/(double)T); #pragma omp parallel for num_threads(T) schedule(static, chunk) private(xl, xu) for (int i = 0; i < N; i++) { xl = a + dn*i; xu = a + dn*(i+1); zeros->ptr[i] = find_zero_NR(fun_ptr, xl, xu); } /* collect the found zeros */ for (int i = 0; i < N; i++) { if (zeros->ptr[i] != -1) { zeros->ptr[zeros->size] = zeros->ptr[i]; zeros->size++; } } zeros->ptr = realloc(zeros->ptr, zeros->size*sizeof(double)); return zeros; } /** Finds a zero, using Newton-bisection, in the interval [a, b] of the function pointed to by fun_ptr. If no zero is found, the function returns -1.0. **/ double find_zero_NR(double (*fun_ptr)(double), double a, double b) { const int max_iter = 50; // maxium number of iterations const double tol = 1e-8; // tolerance int i = 0; // iteration counter double c = a + (b-a)*0.5; // mid-point double x_new = c; // x_k+1 double x_old; // x_k /* perform Newton-bisection while |x_k+1 - x_k| > tol, or while |b-a| < tol, or the maximum number of iterations has not been reached */ do { x_old = x_new; x_new = x_old - (*fun_ptr)(x_old)/derive(fun_ptr, x_old); if (x_new < a || x_new >= b) { // check if outside the interval if ((*fun_ptr)(a) * (*fun_ptr)(c) > 0) { // check sign a = c; } else { b = c; } c = a + (b-a)*0.5; x_old = c; x_new = x_old - (*fun_ptr)(x_old)/derive(fun_ptr, x_old); } i++; } while (b-a > tol && fabs(x_new - x_old) > tol && i < max_iter); if (fabs(x_new - x_old) <= tol && (x_new >= a && x_new < b)) { if (x_new == -1.0) { // add small perturbation if x_new == -1.0 x_new += 1e-12; } return x_new; } else if (b-a <= tol && (*fun_ptr)(a) * (*fun_ptr)(b) < 0) { if (x_new == -1.0) { // add small perturbation if c == -1.0 c += 1e-12; } return c; } else { return -1.0; } }
configurator.c
/* Simple tool to create config.h. * Would be much easier with ccan modules, but deliberately standalone. * * Copyright 2011 Rusty Russell <rusty@rustcorp.com.au>. MIT license. * * c12r_err, c12r_errx functions copied from ccan/err/err.c * Copyright Rusty Russell <rusty@rustcorp.com.au>. CC0 (Public domain) License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #define _POSIX_C_SOURCE 200809L /* For pclose, popen, strdup */ #include <errno.h> #include <stdio.h> #include <stdarg.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif #ifdef _MSC_VER #define DEFAULT_COMPILER "cl" /* Note: Dash options avoid POSIX path conversion when used under msys bash * and are therefore preferred to slash (e.g. -nologo over /nologo) * Note: Disable Warning 4200 "nonstandard extension used : zero-sized array * in struct/union" for flexible array members. */ #define DEFAULT_FLAGS "-nologo -Zi -W4 -wd4200 " \ "-D_CRT_NONSTDC_NO_WARNINGS -D_CRT_SECURE_NO_WARNINGS" #define DEFAULT_OUTPUT_EXE_FLAG "-Fe:" #else #define DEFAULT_COMPILER "cc" #define DEFAULT_FLAGS "-g3 -ggdb -Wall -Wundef -Wmissing-prototypes -Wmissing-declarations -Wstrict-prototypes -Wold-style-definition" #define DEFAULT_OUTPUT_EXE_FLAG "-o" #endif #define OUTPUT_FILE "configurator.out" #define INPUT_FILE "configuratortest.c" #ifdef _WIN32 #define DIR_SEP "\\" #else #define DIR_SEP "/" #endif static const char *progname = ""; static int verbose; enum test_style { OUTSIDE_MAIN = 0x1, DEFINES_FUNC = 0x2, INSIDE_MAIN = 0x4, DEFINES_EVERYTHING = 0x8, MAY_NOT_COMPILE = 0x10, EXECUTE = 0x8000 }; struct test { const char *name; enum test_style style; const char *depends; const char *link; const char *fragment; const char *flags; const char *overrides; /* On success, force this to '1' */ bool done; bool answer; }; static struct test tests[] = { { "HAVE_32BIT_OFF_T", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#include <sys/types.h>\n" "int main(void) {\n" " return sizeof(off_t) == 4 ? 0 : 1;\n" "}\n" }, { "HAVE_ALIGNOF", INSIDE_MAIN, NULL, NULL, "return __alignof__(double) > 0 ? 0 : 1;" }, { "HAVE_ASPRINTF", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <stdio.h>\n" "static char *func(int x) {" " char *p;\n" " if (asprintf(&p, \"%u\", x) == -1) p = NULL;" " return p;\n" "}" }, { "HAVE_ATTRIBUTE_COLD", DEFINES_FUNC, NULL, NULL, "static int __attribute__((cold)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_CONST", DEFINES_FUNC, NULL, NULL, "static int __attribute__((const)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_PURE", DEFINES_FUNC, NULL, NULL, "static int __attribute__((pure)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_MAY_ALIAS", OUTSIDE_MAIN, NULL, NULL, "typedef short __attribute__((__may_alias__)) short_a;" }, { "HAVE_ATTRIBUTE_NORETURN", DEFINES_FUNC, NULL, NULL, "#include <stdlib.h>\n" "static void __attribute__((noreturn)) func(int x) { exit(x); }" }, { "HAVE_ATTRIBUTE_PRINTF", DEFINES_FUNC, NULL, NULL, "static void __attribute__((format(__printf__, 1, 2))) func(const char *fmt, ...) { (void)fmt; }" }, { "HAVE_ATTRIBUTE_UNUSED", OUTSIDE_MAIN, NULL, NULL, "static int __attribute__((unused)) func(int x) { return x; }" }, { "HAVE_ATTRIBUTE_USED", OUTSIDE_MAIN, NULL, NULL, "static int __attribute__((used)) func(int x) { return x; }" }, { "HAVE_BACKTRACE", DEFINES_FUNC, NULL, NULL, "#include <execinfo.h>\n" "static int func(int x) {" " void *bt[10];\n" " return backtrace(bt, 10) < x;\n" "}" }, { "HAVE_BIG_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL, "union { int i; char c[sizeof(int)]; } u;\n" "u.i = 0x01020304;\n" "return u.c[0] == 0x01 && u.c[1] == 0x02 && u.c[2] == 0x03 && u.c[3] == 0x04 ? 0 : 1;" }, { "HAVE_BSWAP_64", DEFINES_FUNC, "HAVE_BYTESWAP_H", NULL, "#include <byteswap.h>\n" "static int func(int x) { return bswap_64(x); }" }, { "HAVE_BUILTIN_CHOOSE_EXPR", INSIDE_MAIN, NULL, NULL, "return __builtin_choose_expr(1, 0, \"garbage\");" }, { "HAVE_BUILTIN_CLZ", INSIDE_MAIN, NULL, NULL, "return __builtin_clz(1) == (sizeof(int)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CLZL", INSIDE_MAIN, NULL, NULL, "return __builtin_clzl(1) == (sizeof(long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CLZLL", INSIDE_MAIN, NULL, NULL, "return __builtin_clzll(1) == (sizeof(long long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZ", INSIDE_MAIN, NULL, NULL, "return __builtin_ctz(1 << (sizeof(int)*8 - 1)) == (sizeof(int)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZL", INSIDE_MAIN, NULL, NULL, "return __builtin_ctzl(1UL << (sizeof(long)*8 - 1)) == (sizeof(long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CTZLL", INSIDE_MAIN, NULL, NULL, "return __builtin_ctzll(1ULL << (sizeof(long long)*8 - 1)) == (sizeof(long long)*8 - 1) ? 0 : 1;" }, { "HAVE_BUILTIN_CONSTANT_P", INSIDE_MAIN, NULL, NULL, "return __builtin_constant_p(1) ? 0 : 1;" }, { "HAVE_BUILTIN_EXPECT", INSIDE_MAIN, NULL, NULL, "return __builtin_expect(argc == 1, 1) ? 0 : 1;" }, { "HAVE_BUILTIN_FFS", INSIDE_MAIN, NULL, NULL, "return __builtin_ffs(0) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_FFSL", INSIDE_MAIN, NULL, NULL, "return __builtin_ffsl(0L) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_FFSLL", INSIDE_MAIN, NULL, NULL, "return __builtin_ffsll(0LL) == 0 ? 0 : 1;" }, { "HAVE_BUILTIN_POPCOUNT", INSIDE_MAIN, NULL, NULL, "return __builtin_popcount(255) == 8 ? 0 : 1;" }, { "HAVE_BUILTIN_POPCOUNTL", INSIDE_MAIN, NULL, NULL, "return __builtin_popcountl(255L) == 8 ? 0 : 1;" }, { "HAVE_BUILTIN_POPCOUNTLL", INSIDE_MAIN, NULL, NULL, "return __builtin_popcountll(255LL) == 8 ? 0 : 1;" }, { "HAVE_BUILTIN_TYPES_COMPATIBLE_P", INSIDE_MAIN, NULL, NULL, "return __builtin_types_compatible_p(char *, int) ? 1 : 0;" }, { "HAVE_ICCARM_INTRINSICS", DEFINES_FUNC, NULL, NULL, "#include <intrinsics.h>\n" "int func(int v) {\n" " return __CLZ(__RBIT(v));\n" "}" }, { "HAVE_BYTESWAP_H", OUTSIDE_MAIN, NULL, NULL, "#include <byteswap.h>\n" }, { "HAVE_CLOCK_GETTIME", DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC", NULL, "#include <time.h>\n" "static struct timespec func(void) {\n" " struct timespec ts;\n" " clock_gettime(CLOCK_REALTIME, &ts);\n" " return ts;\n" "}\n" }, { "HAVE_CLOCK_GETTIME_IN_LIBRT", DEFINES_FUNC, "HAVE_STRUCT_TIMESPEC !HAVE_CLOCK_GETTIME", "-lrt", "#include <time.h>\n" "static struct timespec func(void) {\n" " struct timespec ts;\n" " clock_gettime(CLOCK_REALTIME, &ts);\n" " return ts;\n" "}\n", /* This means HAVE_CLOCK_GETTIME, too */ "HAVE_CLOCK_GETTIME" }, { "HAVE_COMPOUND_LITERALS", INSIDE_MAIN, NULL, NULL, "int *foo = (int[]) { 1, 2, 3, 4 };\n" "return foo[0] ? 0 : 1;" }, { "HAVE_FCHDIR", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#include <sys/types.h>\n" "#include <sys/stat.h>\n" "#include <fcntl.h>\n" "#include <unistd.h>\n" "int main(void) {\n" " int fd = open(\"..\", O_RDONLY);\n" " return fchdir(fd) == 0 ? 0 : 1;\n" "}\n" }, { "HAVE_ERR_H", DEFINES_FUNC, NULL, NULL, "#include <err.h>\n" "static void func(int arg) {\n" " if (arg == 0)\n" " err(1, \"err %u\", arg);\n" " if (arg == 1)\n" " errx(1, \"err %u\", arg);\n" " if (arg == 3)\n" " warn(\"warn %u\", arg);\n" " if (arg == 4)\n" " warnx(\"warn %u\", arg);\n" "}\n" }, { "HAVE_FILE_OFFSET_BITS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, "HAVE_32BIT_OFF_T", NULL, "#define _FILE_OFFSET_BITS 64\n" "#include <sys/types.h>\n" "int main(void) {\n" " return sizeof(off_t) == 8 ? 0 : 1;\n" "}\n" }, { "HAVE_FOR_LOOP_DECLARATION", INSIDE_MAIN, NULL, NULL, "int ret = 1;\n" "for (int i = 0; i < argc; i++) { ret = 0; };\n" "return ret;" }, { "HAVE_FLEXIBLE_ARRAY_MEMBER", OUTSIDE_MAIN, NULL, NULL, "struct foo { unsigned int x; int arr[]; };" }, { "HAVE_GETPAGESIZE", DEFINES_FUNC, NULL, NULL, "#include <unistd.h>\n" "static int func(void) { return getpagesize(); }" }, { "HAVE_ISBLANK", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <ctype.h>\n" "static int func(void) { return isblank(' '); }" }, { "HAVE_LITTLE_ENDIAN", INSIDE_MAIN|EXECUTE, NULL, NULL, "union { int i; char c[sizeof(int)]; } u;\n" "u.i = 0x01020304;\n" "return u.c[0] == 0x04 && u.c[1] == 0x03 && u.c[2] == 0x02 && u.c[3] == 0x01 ? 0 : 1;" }, { "HAVE_MEMMEM", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <string.h>\n" "static void *func(void *h, size_t hl, void *n, size_t nl) {\n" "return memmem(h, hl, n, nl);" "}\n", }, { "HAVE_MEMRCHR", DEFINES_FUNC, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <string.h>\n" "static void *func(void *s, int c, size_t n) {\n" "return memrchr(s, c, n);" "}\n", }, { "HAVE_MMAP", DEFINES_FUNC, NULL, NULL, "#include <sys/mman.h>\n" "static void *func(int fd) {\n" " return mmap(0, 65536, PROT_READ, MAP_SHARED, fd, 0);\n" "}" }, { "HAVE_PROC_SELF_MAPS", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#include <sys/types.h>\n" "#include <sys/stat.h>\n" "#include <fcntl.h>\n" "int main(void) {\n" " return open(\"/proc/self/maps\", O_RDONLY) != -1 ? 0 : 1;\n" "}\n" }, { "HAVE_QSORT_R_PRIVATE_LAST", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#ifndef _GNU_SOURCE\n" "#define _GNU_SOURCE\n" "#endif\n" "#include <stdlib.h>\n" "static int cmp(const void *lp, const void *rp, void *priv) {\n" " *(unsigned int *)priv = 1;\n" " return *(const int *)lp - *(const int *)rp; }\n" "int main(void) {\n" " int array[] = { 9, 2, 5 };\n" " unsigned int called = 0;\n" " qsort_r(array, 3, sizeof(int), cmp, &called);\n" " return called && array[0] == 2 && array[1] == 5 && array[2] == 9 ? 0 : 1;\n" "}\n" }, { "HAVE_STRUCT_TIMESPEC", DEFINES_FUNC, NULL, NULL, "#include <time.h>\n" "static void func(void) {\n" " struct timespec ts;\n" " ts.tv_sec = ts.tv_nsec = 1;\n" "}\n" }, { "HAVE_SECTION_START_STOP", DEFINES_FUNC, NULL, NULL, "static void *__attribute__((__section__(\"mysec\"))) p = &p;\n" "static int func(void) {\n" " extern void *__start_mysec[], *__stop_mysec[];\n" " return __stop_mysec - __start_mysec;\n" "}\n" }, { "HAVE_STACK_GROWS_UPWARDS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <stddef.h>\n" "static ptrdiff_t nest(const void *base, unsigned int i)\n" "{\n" " if (i == 0)\n" " return (const char *)&i - (const char *)base;\n" " return nest(base, i-1);\n" "}\n" "int main(int argc, char *argv[]) {\n" " (void)argv;\n" " return (nest(&argc, argc) > 0) ? 0 : 1;\n" "}\n" }, { "HAVE_STATEMENT_EXPR", INSIDE_MAIN, NULL, NULL, "return ({ int x = argc; x == argc ? 0 : 1; });" }, { "HAVE_SYS_FILIO_H", OUTSIDE_MAIN, NULL, NULL, /* Solaris needs this for FIONREAD */ "#include <sys/filio.h>\n" }, { "HAVE_SYS_TERMIOS_H", OUTSIDE_MAIN, NULL, NULL, "#include <sys/termios.h>\n" }, { "HAVE_SYS_UNISTD_H", OUTSIDE_MAIN, NULL, NULL, "#include <sys/unistd.h>\n" }, { "HAVE_TYPEOF", INSIDE_MAIN, NULL, NULL, "__typeof__(argc) i; i = argc; return i == argc ? 0 : 1;" }, { "HAVE_UNALIGNED_ACCESS", DEFINES_EVERYTHING|EXECUTE, NULL, NULL, "#include <string.h>\n" "int main(int argc, char *argv[]) {\n" " (void)argc;\n" " char pad[sizeof(int *) * 1];\n" " strncpy(pad, argv[0], sizeof(pad));\n" " int *x = (int *)pad, *y = (int *)(pad + 1);\n" " return *x == *y;\n" "}\n" }, { "HAVE_UTIME", DEFINES_FUNC, NULL, NULL, "#include <sys/types.h>\n" "#include <utime.h>\n" "static int func(const char *filename) {\n" " struct utimbuf times = { 0 };\n" " return utime(filename, &times);\n" "}" }, { "HAVE_WARN_UNUSED_RESULT", DEFINES_FUNC, NULL, NULL, "#include <sys/types.h>\n" "#include <utime.h>\n" "static __attribute__((warn_unused_result)) int func(int i) {\n" " return i + 1;\n" "}" }, { "HAVE_OPENMP", INSIDE_MAIN, NULL, NULL, "int i;\n" "#pragma omp parallel for\n" "for(i = 0; i < 0; i++) {};\n" "return 0;\n", "-Werror -fopenmp" }, { "HAVE_VALGRIND_MEMCHECK_H", OUTSIDE_MAIN, NULL, NULL, "#include <valgrind/memcheck.h>\n" }, { "HAVE_UCONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, NULL, NULL, "#include <ucontext.h>\n" "static int x = 0;\n" "static char stack[2048];\n" "static ucontext_t a, b;\n" "static void fn(void) {\n" " x |= 2;\n" " setcontext(&b);\n" " x |= 4;\n" "}\n" "int main(void) {\n" " x |= 1;\n" " getcontext(&a);\n" " a.uc_stack.ss_sp = stack;\n" " a.uc_stack.ss_size = sizeof(stack);\n" " makecontext(&a, fn, 0);\n" " swapcontext(&b, &a);\n" " return (x == 3) ? 0 : 1;\n" "}\n" }, { "HAVE_POINTER_SAFE_MAKECONTEXT", DEFINES_EVERYTHING|EXECUTE|MAY_NOT_COMPILE, "HAVE_UCONTEXT", NULL, "#include <stddef.h>\n" "#include <ucontext.h>\n" "static int worked = 0;\n" "static char stack[1024];\n" "static ucontext_t a, b;\n" "static void fn(void *p, void *q) {\n" " void *cp = &worked;\n" " void *cq = (void *)(~((ptrdiff_t)cp));\n" " if ((p == cp) && (q == cq))\n" " worked = 1;\n" " setcontext(&b);\n" "}\n" "int main(void) {\n" " void *ap = &worked;\n" " void *aq = (void *)(~((ptrdiff_t)ap));\n" " getcontext(&a);\n" " a.uc_stack.ss_sp = stack;\n" " a.uc_stack.ss_size = sizeof(stack);\n" " makecontext(&a, (void (*)(void))fn, 2, ap, aq);\n" " swapcontext(&b, &a);\n" " return worked ? 0 : 1;\n" "}\n" }, }; static void c12r_err(int eval, const char *fmt, ...) { int err_errno = errno; va_list ap; fprintf(stderr, "%s: ", progname); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, ": %s\n", strerror(err_errno)); exit(eval); } static void c12r_errx(int eval, const char *fmt, ...) { va_list ap; fprintf(stderr, "%s: ", progname); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); exit(eval); } static size_t fcopy(FILE *fsrc, FILE *fdst) { char buffer[BUFSIZ]; size_t rsize, wsize; size_t copied = 0; while ((rsize = fread(buffer, 1, BUFSIZ, fsrc)) > 0) { wsize = fwrite(buffer, 1, rsize, fdst); copied += wsize; if (wsize != rsize) break; } return copied; } static char *grab_stream(FILE *file) { size_t max, ret, size = 0; char *buffer; max = BUFSIZ; buffer = malloc(max); while ((ret = fread(buffer+size, 1, max - size, file)) == max - size) { size += ret; buffer = realloc(buffer, max *= 2); } size += ret; if (ferror(file)) c12r_err(1, "reading from command"); buffer[size] = '\0'; return buffer; } static char *run(const char *cmd, int *exitstatus) { static const char redir[] = " 2>&1"; size_t cmdlen; char *cmdredir; FILE *cmdout; char *ret; cmdlen = strlen(cmd); cmdredir = malloc(cmdlen + sizeof(redir)); memcpy(cmdredir, cmd, cmdlen); memcpy(cmdredir + cmdlen, redir, sizeof(redir)); cmdout = popen(cmdredir, "r"); if (!cmdout) c12r_err(1, "popen \"%s\"", cmdredir); free(cmdredir); ret = grab_stream(cmdout); *exitstatus = pclose(cmdout); return ret; } static char *connect_args(const char *argv[], const char *outflag, const char *files) { unsigned int i; char *ret; size_t len = strlen(outflag) + strlen(files) + 1; for (i = 1; argv[i]; i++) len += 1 + strlen(argv[i]); ret = malloc(len); len = 0; for (i = 1; argv[i]; i++) { strcpy(ret + len, argv[i]); len += strlen(argv[i]); if (argv[i+1] || *outflag) ret[len++] = ' '; } strcpy(ret + len, outflag); len += strlen(outflag); strcpy(ret + len, files); return ret; } static struct test *find_test(const char *name) { unsigned int i; for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) { if (strcmp(tests[i].name, name) == 0) return &tests[i]; } abort(); } #define PRE_BOILERPLATE "/* Test program generated by configurator. */\n" #define MAIN_START_BOILERPLATE \ "int main(int argc, char *argv[]) {\n" \ " (void)argc;\n" \ " (void)argv;\n" #define USE_FUNC_BOILERPLATE "(void)func;\n" #define MAIN_BODY_BOILERPLATE "return 0;\n" #define MAIN_END_BOILERPLATE "}\n" static bool run_test(const char *cmd, struct test *test) { char *output, *newcmd; FILE *outf; int status; if (test->done) return test->answer; if (test->depends) { size_t len; const char *deps = test->depends; char *dep; /* Space-separated dependencies, could be ! for inverse. */ while ((len = strcspn(deps, " ")) != 0) { bool positive = true; if (deps[len]) { dep = strdup(deps); dep[len] = '\0'; } else { dep = (char *)deps; } if (dep[0] == '!') { dep++; positive = false; } if (run_test(cmd, find_test(dep)) != positive) { test->answer = false; test->done = true; return test->answer; } if (deps[len]) free(dep); deps += len; deps += strspn(deps, " "); } } outf = fopen(INPUT_FILE, verbose > 1 ? "w+" : "w"); if (!outf) c12r_err(1, "creating %s", INPUT_FILE); fprintf(outf, "%s", PRE_BOILERPLATE); switch (test->style & ~(EXECUTE|MAY_NOT_COMPILE)) { case INSIDE_MAIN: fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case OUTSIDE_MAIN: fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", MAIN_BODY_BOILERPLATE); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case DEFINES_FUNC: fprintf(outf, "%s", test->fragment); fprintf(outf, "%s", MAIN_START_BOILERPLATE); fprintf(outf, "%s", USE_FUNC_BOILERPLATE); fprintf(outf, "%s", MAIN_BODY_BOILERPLATE); fprintf(outf, "%s", MAIN_END_BOILERPLATE); break; case DEFINES_EVERYTHING: fprintf(outf, "%s", test->fragment); break; default: abort(); } if (verbose > 1) { fseek(outf, 0, SEEK_SET); fcopy(outf, stdout); } fclose(outf); newcmd = strdup(cmd); if (test->flags) { newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ") + strlen(test->flags) + 1); strcat(newcmd, " "); strcat(newcmd, test->flags); if (verbose > 1) printf("Extra flags line: %s", newcmd); } if (test->link) { newcmd = realloc(newcmd, strlen(newcmd) + strlen(" ") + strlen(test->link) + 1); strcat(newcmd, " "); strcat(newcmd, test->link); if (verbose > 1) printf("Extra link line: %s", newcmd); } output = run(newcmd, &status); free(newcmd); if (status != 0 || strstr(output, "warning")) { if (verbose) printf("Compile %s for %s, status %i: %s\n", status ? "fail" : "warning", test->name, status, output); if ((test->style & EXECUTE) && !(test->style & MAY_NOT_COMPILE)) c12r_errx(1, "Test for %s did not compile:\n%s", test->name, output); test->answer = false; free(output); } else { /* Compile succeeded. */ free(output); /* We run INSIDE_MAIN tests for sanity checking. */ if ((test->style & EXECUTE) || (test->style & INSIDE_MAIN)) { output = run("." DIR_SEP OUTPUT_FILE, &status); if (!(test->style & EXECUTE) && status != 0) c12r_errx(1, "Test for %s failed with %i:\n%s", test->name, status, output); if (verbose && status) printf("%s exited %i\n", test->name, status); free(output); } test->answer = (status == 0); } test->done = true; if (test->answer && test->overrides) { struct test *override = find_test(test->overrides); override->done = true; override->answer = true; } return test->answer; } int main(int argc, const char *argv[]) { char *cmd; unsigned int i; const char *default_args[] = { "", DEFAULT_COMPILER, DEFAULT_FLAGS, NULL }; const char *outflag = DEFAULT_OUTPUT_EXE_FLAG; const char *configurator_cc = NULL; const char *orig_cc; if (argc > 0) progname = argv[0]; while (argc > 1) { if (strcmp(argv[1], "--help") == 0) { printf("Usage: configurator [-v] [-O<outflag>] [--configurator-cc=<compiler-for-tests>] [<compiler> <flags>...]\n" " <compiler> <flags> will have \"<outflag> <outfile> <infile.c>\" appended\n" "Default: %s %s %s\n", DEFAULT_COMPILER, DEFAULT_FLAGS, DEFAULT_OUTPUT_EXE_FLAG); exit(0); } if (strncmp(argv[1], "-O", 2) == 0) { argc--; argv++; outflag = argv[1] + 2; if (!*outflag) { fprintf(stderr, "%s: option requires an argument -- O\n", argv[0]); exit(1); } } else if (strcmp(argv[1], "-v") == 0) { argc--; argv++; verbose++; } else if (strcmp(argv[1], "-vv") == 0) { argc--; argv++; verbose += 2; } else if (strncmp(argv[1], "--configurator-cc=", 18) == 0) { configurator_cc = argv[1] + 18; argc--; argv++; } else { break; } } if (argc == 1) argv = default_args; orig_cc = argv[1]; if (configurator_cc) argv[1] = configurator_cc; cmd = connect_args(argv, outflag, OUTPUT_FILE " " INPUT_FILE); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) run_test(cmd, &tests[i]); free(cmd); remove(OUTPUT_FILE); remove(INPUT_FILE); printf("/* Generated by CCAN configurator */\n" "#ifndef CCAN_CONFIG_H\n" "#define CCAN_CONFIG_H\n"); printf("#ifndef _GNU_SOURCE\n"); printf("#define _GNU_SOURCE /* Always use GNU extensions. */\n"); printf("#endif\n"); printf("#define CCAN_COMPILER \"%s\"\n", orig_cc); cmd = connect_args(argv + 1, "", ""); printf("#define CCAN_CFLAGS \"%s\"\n", cmd); free(cmd); printf("#define CCAN_OUTPUT_EXE_CFLAG \"%s\"\n\n", outflag); /* This one implies "#include <ccan/..." works, eg. for tdb2.h */ printf("#define HAVE_CCAN 1\n"); for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) printf("#define %s %u\n", tests[i].name, tests[i].answer); printf("#endif /* CCAN_CONFIG_H */\n"); return 0; }
sparselu-task-dep.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ #include <stdint.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include "sparselu.h" void sparselu_par_call(float **BENCH, int matrix_size, int submatrix_size) { int ii, jj, kk; #pragma omp parallel private(kk,ii,jj) shared(BENCH) #pragma omp single /* nowait */ { /*#pragma omp task untied*/ for (kk=0; kk<matrix_size; kk++) { #pragma omp task firstprivate(kk) shared(BENCH) depend(inout: BENCH[kk*matrix_size+kk:submatrix_size*submatrix_size]) lu0(BENCH[kk*matrix_size+kk], submatrix_size); for (jj=kk+1; jj<matrix_size; jj++) if (BENCH[kk*matrix_size+jj] != NULL) { #pragma omp task firstprivate(kk, jj) shared(BENCH) depend(in: BENCH[kk*matrix_size+kk:submatrix_size*submatrix_size]) depend(inout: BENCH[kk*matrix_size+jj:submatrix_size*submatrix_size]) fwd(BENCH[kk*matrix_size+kk], BENCH[kk*matrix_size+jj], submatrix_size); } for (ii=kk+1; ii<matrix_size; ii++) if (BENCH[ii*matrix_size+kk] != NULL) { #pragma omp task firstprivate(kk, ii) shared(BENCH) depend(in: BENCH[kk*matrix_size+kk:submatrix_size*submatrix_size]) depend(inout: BENCH[ii*matrix_size+kk:submatrix_size*submatrix_size]) bdiv (BENCH[kk*matrix_size+kk], BENCH[ii*matrix_size+kk], submatrix_size); } for (ii=kk+1; ii<matrix_size; ii++) if (BENCH[ii*matrix_size+kk] != NULL) for (jj=kk+1; jj<matrix_size; jj++) if (BENCH[kk*matrix_size+jj] != NULL) { if (BENCH[ii*matrix_size+jj]==NULL) BENCH[ii*matrix_size+jj] = allocate_clean_block(submatrix_size); #pragma omp task firstprivate(kk, jj, ii) shared(BENCH) \ depend(in: BENCH[ii*matrix_size+kk:submatrix_size*submatrix_size], BENCH[kk*matrix_size+jj:submatrix_size*submatrix_size]) \ depend(inout: BENCH[ii*matrix_size+jj:submatrix_size*submatrix_size]) bmod(BENCH[ii*matrix_size+kk], BENCH[kk*matrix_size+jj], BENCH[ii*matrix_size+jj], submatrix_size); } } #pragma omp taskwait } }
pooling_layer.h
//Tencent is pleased to support the open source community by making FeatherCNN available. //Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. //Licensed under the BSD 3-Clause License (the "License"); you may not use this file except //in compliance with the License. You may obtain a copy of the License at // //https://opensource.org/licenses/BSD-3-Clause // //Unless required by applicable law or agreed to in writing, software distributed //under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR //CONDITIONS OF ANY KIND, either express or implied. See the License for the //specific language governing permissions and limitations under the License. #pragma once #include "../feather_generated.h" #include "../layer.h" #include <math.h> #include <limits> #define MAX(a,b) ((a)>(b))?(a):(b) #define MIN(a,b) ((a)<(b))?(a):(b) namespace feather { void ave_pool_inner_kernel(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w) { float total = 0.0; for (size_t m = 0; m != kernel_h; ++m) { for (size_t n = 0; n != kernel_w; ++n) { size_t pos = m * ldin + n; total += in[pos]; } } *out = total / kernel_h / kernel_w; } void max_pool_inner_kernel(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w) { float max = 0.0; for (size_t m = 0; m != kernel_h; ++m) { for (size_t n = 0; n != kernel_w; ++n) { size_t pos = m * ldin + n; max = (in[pos] > max) ? in[pos] : max; } } *out = max; } class PoolingLayer : public Layer<float> { public: PoolingLayer(const LayerParameter *layer_param, RuntimeParameter<float>* rt_param) : stride_height(1), stride_width(1), Layer<float>(layer_param, rt_param) { const PoolingParameter *pooling_param = layer_param->pooling_param(); kernel_height = pooling_param->kernel_h(); kernel_width = pooling_param->kernel_w(); pad_height = pooling_param->pad_h(); pad_width = pooling_param->pad_w(); stride_height = pooling_param->stride_h(); stride_width = pooling_param->stride_w(); stride_height = (stride_height <= 0) ? 1 : stride_height; stride_width = (stride_width <= 0) ? 1 : stride_width; global_pooling = pooling_param->global_pooling(); this->method = pooling_param->pool(); switch (this->method) { case PoolingParameter_::PoolMethod_MAX_: _pool_inner_kernel = max_pool_inner_kernel; break; case PoolingParameter_::PoolMethod_AVE: _pool_inner_kernel = ave_pool_inner_kernel; break; default: fprintf(stderr, "Unsupported pool method\n"); } //printf("kernel (%ld %ld) pad (%ld %ld) stride (%ld %ld) global_pooling %d\n", // kernel_height, kernel_width, pad_height, pad_width, stride_height, stride_width, global_pooling); } int Forward() { // fprintf(stderr, "Pooling layer %s\ninput shape %ld %ld %ld kernel shape %ld %ld stride %ld %ld\n", this->name().c_str(), input_channels, input_height, input_width, kernel_height, kernel_width, stride_height, stride_width); // fprintf(stderr, "output (%d %d)\n", output_height, output_width); const float *input = _bottom_blobs[_bottom[0]]->data(); float *output = _top_blobs[_top[0]]->data(); float *p = output; int slot = input_channels * output_height; #pragma omp parallel for schedule(static) num_threads(num_threads) // for (int u=0;u<slot;u++) // { for (int i = 0; i < input_channels; ++i) { for (int j = 0; j < output_height; j ++) { // int i=slot/output_height, j=slot%output_height; float *p = output + i * output_height * output_width + j * output_width; for (int l = 0; l < output_width; l++) p[l] = (this->method != PoolingParameter_::PoolMethod_MAX_ ? 0 : -1 * std::numeric_limits<float>::max()) ; int tmp_pos = j * (int)stride_height - (int)pad_height; int x_min = MAX(tmp_pos, 0); int x_max = MIN((int)(tmp_pos + kernel_height), (int) input_height); for (int k = 0; k < output_width; k ++) { int counter = 0; float total = (this->method != PoolingParameter_::PoolMethod_MAX_ ? 0 : -1 * std::numeric_limits<float>::max()); for (int x = x_min; x < x_max; ++x) { int xpos = i * input_height * input_width + x * input_width; int local_pos = k * (int)stride_width - (int)pad_width; int y_min = MAX(local_pos, 0); int y_max = MIN((int)(local_pos + kernel_width), (int) input_width); for (int y = y_min; y < y_max; ++y) { float value = input[xpos + y]; if (this->method != PoolingParameter_::PoolMethod_MAX_) total += value, counter++; else total = total > value ? total : value; } } if (this->method != PoolingParameter_::PoolMethod_MAX_) p[k] += total / (counter); else p[k] = (p[k] > total) ? p[k] : total; } } } return 0; } int ForwardReshape() { const Blob<float> *bottom_blob = _bottom_blobs[_bottom[0]]; input_height = bottom_blob->height(); input_width = bottom_blob->width(); input_channels = bottom_blob->channels(); //printf("layer %s\n", _name.c_str()); //printf("input %lu %lu %lu\n", input_channels, input_height, input_width); if (global_pooling) { kernel_height = input_height; kernel_width = input_width; output_height = 1; output_width = 1; output_channels = input_channels; } else { //General pooling. output_channels = input_channels; output_height = static_cast<int>(ceil(static_cast<float>(input_height + 2 * pad_height - kernel_height) / stride_height)) + 1; output_width = static_cast<int>(ceil(static_cast<float>(input_width + 2 * pad_width - kernel_width) / stride_width)) + 1; } _top_blobs[_top[0]]->ReshapeWithRealloc(1, output_channels, output_height, output_width); return Forward(); } int GenerateTopBlobs() { //Only accept a single bottom blob. const Blob<float> *bottom_blob = _bottom_blobs[_bottom[0]]; input_height = bottom_blob->height(); input_width = bottom_blob->width(); input_channels = bottom_blob->channels(); //printf("layer %s\n", _name.c_str()); //printf("input %lu %lu %lu\n", input_channels, input_height, input_width); if (global_pooling) { kernel_height = input_height; kernel_width = input_width; output_height = 1; output_width = 1; output_channels = input_channels; } else { //General pooling. output_channels = input_channels; output_height = static_cast<int>(ceil(static_cast<float>(input_height + 2 * pad_height - kernel_height) / stride_height)) + 1; output_width = static_cast<int>(ceil(static_cast<float>(input_width + 2 * pad_width - kernel_width) / stride_width)) + 1; } _top_blobs[_top[0]] = new Blob<float>(1, output_channels, output_height, output_width); _top_blobs[_top[0]]->Alloc(); //_top_blobs[_top[0]]->PrintBlobInfo(); return 0; } private: size_t input_height; size_t input_width; size_t input_channels; size_t output_height; size_t output_width; size_t output_channels; size_t pad_height; size_t pad_width; size_t kernel_height; size_t kernel_width; size_t stride_height; size_t stride_width; bool global_pooling; PoolingParameter_::PoolMethod method; void (*_pool_inner_kernel)(float* out, const float* in, const size_t ldin, const size_t kernel_h, const size_t kernel_w); }; };
GB_unaryop__lnot_uint64_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_uint64_uint64 // op(A') function: GB_tran__lnot_uint64_uint64 // C type: uint64_t // A type: uint64_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint64_uint64 ( uint64_t *Cx, // Cx and Ax may be aliased uint64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_uint64_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
target_parallel_for_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -verify %s -Wuninitialized // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target parallel for'}} #pragma omp target parallel for // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target parallel for'}} #pragma omp target parallel for foo void test_no_clause() { int i; #pragma omp target parallel for for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target parallel for' must be a for loop}} #pragma omp target parallel for ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target parallel for for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target parallel for' are ignored}} #pragma omp target parallel for foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target parallel for' are ignored}} #pragma omp target parallel for; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target parallel for' are ignored}} #pragma omp target parallel for private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target parallel for' are ignored}} #pragma omp target parallel for, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target parallel for collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target parallel for collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target parallel for collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target parallel for collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target parallel for' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target parallel for collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} #pragma omp target parallel for collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target parallel for collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target parallel for', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target parallel for collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target parallel for collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target parallel for collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target parallel for collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target parallel for collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-note@+1 {{defined as firstprivate}} #pragma omp target parallel for collapse(2) firstprivate(i) for (i = 0; i < 16; ++i) // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}} for (int j = 0; j < 16; ++j) // expected-error@+2 2 {{reduction variable must be shared}} // expected-error@+1 {{region cannot be closely nested inside 'target parallel for' region; perhaps you forget to enclose 'omp for' directive into a parallel region?}} #pragma omp for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target parallel for private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target parallel for private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target parallel for private(x) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target parallel for lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target parallel for lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target parallel for lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target parallel for firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target parallel for firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target parallel for firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target parallel for firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target parallel for lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target parallel for lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target parallel for for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target parallel for for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } }
MTARI.c
/* MTARI 0.2 - A Fast Multithreaded Bitwise Arithmetic Compressor Copyright (C) 2013 David Catt */ #define _CRT_SECURE_NO_WARNINGS #define BUFSIZE 0x400000 #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef _WIN32 #include <io.h> #include <fcntl.h> #endif #include "FastAri.h" /* ============BLOCK FUNCTIONS============ */ int enc_blk(char* bin, char* bout, size_t ilen, size_t* olen, int par) { return !fa_compress(bin, bout, ilen, olen); } int dec_blk(char* bin, char* bout, size_t ilen, size_t* olen) { return !fa_decompress(bin, bout, ilen, olen); } /* ======================================= */ /* ==============DRIVER CORE============== */ void fwritesize(size_t v, FILE* f) { int s = 8; while(s) { fputc(v & 0xff, f); v >>= 8; --s; } } int freadsize(size_t* v, FILE* f) { int s = 0; int c; *v = 0; while(s < 64) { if((c = fgetc(f)) == EOF) { *v = 0; return 0; } *v |= c << s; s += 8; } return 1; } int encode(FILE* fin, FILE* fout, int tcnt, size_t bsz, int par) { /* Declare variables */ char** ibufs; char** obufs; size_t* ilens; size_t* olens; int mp, pi, rc; /* Validate parameters */ if(!fin) return 0; if(!fout) return 0; if(bsz < 1) return 0; /* Setup thread count */ if(tcnt < 1) { #ifdef _OPENMP tcnt = omp_get_num_procs(); #else tcnt = 1; #endif } #ifdef _OPENMP if(tcnt > omp_get_num_procs()) tcnt = omp_get_num_procs(); omp_set_num_threads(tcnt); #else tcnt = 1; #endif /* Allocate arrays */ if(!(ibufs = calloc(tcnt, sizeof(char*)))) return 0; if(!(obufs = calloc(tcnt, sizeof(char*)))) { free(ibufs); return 0; } if(!(ilens = calloc(tcnt, sizeof(size_t)))) { free(ibufs); free(obufs); return 0; } if(!(olens = calloc(tcnt, sizeof(size_t)))) { free(ibufs); free(obufs); free(ilens); return 0; } /* Allocate buffers */ for(pi = 0; pi < tcnt; ++pi) { if(!(ibufs[pi] = malloc(bsz * sizeof(char))) || !(obufs[pi] = malloc(((bsz + (bsz / 10)) * sizeof(char)) + 1024))) { if (ibufs[pi]) free(ibufs[pi]); for (mp = 0; mp < pi; ++mp) { free(ibufs[mp]); free(obufs[mp]); } free(ibufs); free(obufs); free(ilens); free(olens); return 0; } } /* Process input */ while(1) { /* Read input */ for(mp = 0; mp < tcnt; ++mp) { if((ilens[mp] = fread(ibufs[mp], sizeof(char), bsz, fin)) < 1) break; } if(!mp) break; /* Process input */ rc = 0; #pragma omp parallel for for(pi = 0; pi < mp; ++pi) { if(ilens[pi] > 0) { rc += !enc_blk(ibufs[pi], obufs[pi], ilens[pi], &(olens[pi]), par); } } /* Check for processing errors */ if(rc) { for (pi = 0; pi < tcnt; ++pi) { free(ibufs[pi]); free(obufs[pi]); } free(ibufs); free(obufs); free(ilens); free(olens); return 0; } /* Write output */ for(pi = 0; pi < mp; ++pi) { fwritesize(ilens[pi], fout); fwritesize(olens[pi], fout); fwrite(obufs[pi], sizeof(char), olens[pi], fout); } } /* Flush output */ fwritesize(0, fout); fwritesize(0, fout); fflush(fout); /* Free memory */ for (pi = 0; pi < tcnt; ++pi) { free(ibufs[pi]); free(obufs[pi]); } free(ibufs); free(obufs); free(ilens); free(olens); /* Return success */ return 1; } int decode(FILE* fin, FILE* fout, int tcnt) { /* Declare variables */ char** ibufs; char** obufs; size_t* ilens; size_t* olens; int mp, pi, rc, es = 0; /* Validate parameters */ if(!fin) return 0; if(!fout) return 0; /* Setup thread count */ if(tcnt < 1) { #ifdef _OPENMP tcnt = omp_get_num_procs(); #else tcnt = 1; #endif } #ifdef _OPENMP if(tcnt > omp_get_num_procs()) tcnt = omp_get_num_procs(); omp_set_num_threads(tcnt); #else tcnt = 1; #endif /* Allocate arrays */ if(!(ibufs = calloc(tcnt, sizeof(char*)))) return 0; if(!(obufs = calloc(tcnt, sizeof(char*)))) { free(ibufs); return 0; } if(!(ilens = calloc(tcnt, sizeof(size_t)))) { free(ibufs); free(obufs); return 0; } if(!(olens = calloc(tcnt, sizeof(size_t)))) { free(ibufs); free(obufs); free(ilens); return 0; } /* Process input */ while(1) { /* Read input */ rc = 0; for(mp = 0; mp < tcnt; ++mp) { if(!freadsize(&(olens[mp]), fin)) { es = 1; break; } if(!freadsize(&(ilens[mp]), fin)) { free(ibufs[mp]); rc = 1; break; } if(!ilens[mp] || !olens[mp]) { es = 1; break; } if(!(ibufs[mp] = malloc(ilens[mp]))) { rc = 1; break; } if(!(obufs[mp] = malloc(olens[mp]))) { free(ibufs[mp]); rc = 1; break; } if(fread(ibufs[mp], sizeof(char), ilens[mp], fin) < ilens[mp]) { free(ibufs[mp]); free(obufs[mp]); rc = 1; break; } } if(rc) { for(pi = 0; pi < mp; ++pi) { free(ibufs[pi]); free(obufs[pi]); } free(ibufs); free(obufs); free(ilens); free(olens); return 0; } /* Process input */ #pragma omp parallel for for(pi = 0; pi < mp; ++pi) { if(ilens[pi] > 0) { rc += !dec_blk(ibufs[pi], obufs[pi], ilens[pi], &(olens[pi])); } } /* Check for processing errors */ if(rc) { for(pi = 0; pi < mp; ++pi) { free(ibufs[pi]); free(obufs[pi]); } free(ibufs); free(obufs); free(ilens); free(olens); return 0; } /* Write output */ rc = 0; for(pi = 0; pi < mp; ++pi) { free(ibufs[pi]); fwrite(obufs[pi], sizeof(char), olens[pi], fout); free(obufs[pi]); } if (es) break; } /* Flush output */ fflush(fout); /* Free memory */ free(ibufs); free(obufs); free(ilens); free(olens); /* Return success */ return 1; } /* ======================================= */ int main(int argc, char** argv) { FILE *fin, *fout; int tcnt = 0, rc; if(((argc == 4) || (argc == 5)) && ((argv[1][0] == 'c') || (argv[1][0] == 'd'))) { if(argv[1][0] == 'c') { if(argc == 5) tcnt = atoi(argv[4]); if(strcmp(argv[2], ":")) { if(!(fin = fopen(argv[2], "rb"))) { fprintf(stderr, "ERROR: Could not open input file.\n"); return 1; } } else { #ifdef _WIN32 _setmode(_fileno(stdin), O_BINARY); fin = stdin; #else fin = freopen(NULL, "rb", stdin); #endif } if(strcmp(argv[3], ":")) { if(!(fout = fopen(argv[3], "wb"))) { fclose(fin); fprintf(stderr, "ERROR: Could not open output file.\n"); return 1; } } else { #ifdef _WIN32 _setmode(_fileno(stdout), O_BINARY); fout = stdout; #else fout = freopen(NULL, "wb", stdout); #endif } rc = encode(fin, fout, tcnt, BUFSIZE, 0); fflush(fout); fclose(fin); fclose(fout); if(!rc) fprintf(stderr, "ERROR: Compress failed.\n"); return rc; } else if(argv[1][0] == 'd') { if(argc == 5) tcnt = atoi(argv[4]); if(strcmp(argv[2], ":")) { if(!(fin = fopen(argv[2], "rb"))) { fprintf(stderr, "ERROR: Could not open input file.\n"); return 1; } } else { #ifdef _WIN32 _setmode(_fileno(stdin), O_BINARY); fin = stdin; #else fin = freopen(NULL, "rb", stdin); #endif } if(strcmp(argv[3], ":")) { if(!(fout = fopen(argv[3], "wb"))) { fclose(fin); fprintf(stderr, "ERROR: Could not open output file.\n"); return 1; } } else { #ifdef _WIN32 _setmode(_fileno(stdout), O_BINARY); fout = stdout; #else fout = freopen(NULL, "wb", stdout); #endif } rc = decode(fin, fout, tcnt); fflush(fout); fclose(fin); fclose(fout); if(!rc) fprintf(stderr, "ERROR: Decompress failed.\n"); return rc; } } else { printf("MTARI v0.2 (c) 2013 by David Catt\n\n"); printf("usage: MTARI [c|d] [infile] [outfile] <threads>\n\n"); printf("modes:\n"); printf(" c - Compress infile to outfile\n"); printf(" d - Decompress infile to outfile\n\n"); printf("note: If the number of threads is not specified, uses all cores\n"); return 1; } }
crop_and_resize.c
#include <TH/TH.h> #include <stdio.h> #include <math.h> void CropAndResizePerBox( const float * image_data, const int batch_size, const int depth, const int image_height, const int image_width, const float * boxes_data, const int * box_index_data, const int start_box, const int limit_box, float * corps_data, const int crop_height, const int crop_width, const float extrapolation_value ) { const int image_channel_elements = image_height * image_width; const int image_elements = depth * image_channel_elements; const int channel_elements = crop_height * crop_width; const int crop_elements = depth * channel_elements; int b; #pragma omp parallel for for (b = start_box; b < limit_box; ++b) { const float * box = boxes_data + b * 4; const float y1 = box[0]; const float x1 = box[1]; const float y2 = box[2]; const float x2 = box[3]; const int b_in = box_index_data[b]; if (b_in < 0 || b_in >= batch_size) { printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size); exit(-1); } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; for (int y = 0; y < crop_height; ++y) { const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { for (int x = 0; x < crop_width; ++x) { for (int d = 0; d < depth; ++d) { // crops(b, y, x, d) = extrapolation_value; corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = extrapolation_value; } } continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; for (int x = 0; x < crop_width; ++x) { const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { for (int d = 0; d < depth; ++d) { corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = extrapolation_value; } continue; } const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; for (int d = 0; d < depth; ++d) { const float *pimage = image_data + b_in * image_elements + d * image_channel_elements; const float top_left = pimage[top_y_index * image_width + left_x_index]; const float top_right = pimage[top_y_index * image_width + right_x_index]; const float bottom_left = pimage[bottom_y_index * image_width + left_x_index]; const float bottom_right = pimage[bottom_y_index * image_width + right_x_index]; const float top = top_left + (top_right - top_left) * x_lerp; const float bottom = bottom_left + (bottom_right - bottom_left) * x_lerp; corps_data[crop_elements * b + channel_elements * d + y * crop_width + x] = top + (bottom - top) * y_lerp; } } // end for x } // end for y } // end for b } void crop_and_resize_forward( THFloatTensor * image, THFloatTensor * boxes, // [y1, x1, y2, x2] THIntTensor * box_index, // range in [0, batch_size) const float extrapolation_value, const int crop_height, const int crop_width, THFloatTensor * crops ) { const int batch_size = image->size[0]; const int depth = image->size[1]; const int image_height = image->size[2]; const int image_width = image->size[3]; const int num_boxes = boxes->size[0]; // init output space THFloatTensor_resize4d(crops, num_boxes, depth, crop_height, crop_width); THFloatTensor_zero(crops); // crop_and_resize for each box CropAndResizePerBox( THFloatTensor_data(image), batch_size, depth, image_height, image_width, THFloatTensor_data(boxes), THIntTensor_data(box_index), 0, num_boxes, THFloatTensor_data(crops), crop_height, crop_width, extrapolation_value ); } void crop_and_resize_backward( THFloatTensor * grads, THFloatTensor * boxes, // [y1, x1, y2, x2] THIntTensor * box_index, // range in [0, batch_size) THFloatTensor * grads_image // resize to [bsize, c, hc, wc] ) { // shape const int batch_size = grads_image->size[0]; const int depth = grads_image->size[1]; const int image_height = grads_image->size[2]; const int image_width = grads_image->size[3]; const int num_boxes = grads->size[0]; const int crop_height = grads->size[2]; const int crop_width = grads->size[3]; // n_elements const int image_channel_elements = image_height * image_width; const int image_elements = depth * image_channel_elements; const int channel_elements = crop_height * crop_width; const int crop_elements = depth * channel_elements; // init output space THFloatTensor_zero(grads_image); // data pointer const float * grads_data = THFloatTensor_data(grads); const float * boxes_data = THFloatTensor_data(boxes); const int * box_index_data = THIntTensor_data(box_index); float * grads_image_data = THFloatTensor_data(grads_image); for (int b = 0; b < num_boxes; ++b) { const float * box = boxes_data + b * 4; const float y1 = box[0]; const float x1 = box[1]; const float y2 = box[2]; const float x2 = box[3]; const int b_in = box_index_data[b]; if (b_in < 0 || b_in >= batch_size) { printf("Error: batch_index %d out of range [0, %d)\n", b_in, batch_size); exit(-1); } const float height_scale = (crop_height > 1) ? (y2 - y1) * (image_height - 1) / (crop_height - 1) : 0; const float width_scale = (crop_width > 1) ? (x2 - x1) * (image_width - 1) / (crop_width - 1) : 0; for (int y = 0; y < crop_height; ++y) { const float in_y = (crop_height > 1) ? y1 * (image_height - 1) + y * height_scale : 0.5 * (y1 + y2) * (image_height - 1); if (in_y < 0 || in_y > image_height - 1) { continue; } const int top_y_index = floorf(in_y); const int bottom_y_index = ceilf(in_y); const float y_lerp = in_y - top_y_index; for (int x = 0; x < crop_width; ++x) { const float in_x = (crop_width > 1) ? x1 * (image_width - 1) + x * width_scale : 0.5 * (x1 + x2) * (image_width - 1); if (in_x < 0 || in_x > image_width - 1) { continue; } const int left_x_index = floorf(in_x); const int right_x_index = ceilf(in_x); const float x_lerp = in_x - left_x_index; for (int d = 0; d < depth; ++d) { float *pimage = grads_image_data + b_in * image_elements + d * image_channel_elements; const float grad_val = grads_data[crop_elements * b + channel_elements * d + y * crop_width + x]; const float dtop = (1 - y_lerp) * grad_val; pimage[top_y_index * image_width + left_x_index] += (1 - x_lerp) * dtop; pimage[top_y_index * image_width + right_x_index] += x_lerp * dtop; const float dbottom = y_lerp * grad_val; pimage[bottom_y_index * image_width + left_x_index] += (1 - x_lerp) * dbottom; pimage[bottom_y_index * image_width + right_x_index] += x_lerp * dbottom; } // end d } // end x } // end y } // end b }
initialize-brisbane.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-brisbane.h" //--------------------------------------------------------------------- // This subroutine initializes the field variable u using // tri-linear transfinite interpolation of the boundary values //--------------------------------------------------------------------- void initialize() { int i, j, k, m, ix, iy, iz; double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; //--------------------------------------------------------------------- // Later (in compute_rhs) we compute 1/u for every element. A few of // the corner elements are not used, but it convenient (and faster) // to compute the whole thing with a simple loop. Make sure those // values are nonzero by initializing the whole thing here. //--------------------------------------------------------------------- for (k = 0; k <= grid_points[2]-1; k++) { for (j = 0; j <= grid_points[1]-1; j++) { for (i = 0; i <= grid_points[0]-1; i++) { for (m = 0; m < 5; m++) { u[k][j][i][m] = 1.0; } } } } //--------------------------------------------------------------------- // first store the "interpolated" values everywhere on the grid //--------------------------------------------------------------------- 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; for (ix = 0; ix < 2; ix++) { exact_solution((double)ix, eta, zeta, &Pface[ix][0][0]); } for (iy = 0; iy < 2; iy++) { exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]); } for (iz = 0; iz < 2; iz++) { exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]); } for (m = 0; m < 5; m++) { Pxi = xi * Pface[1][0][m] + (1.0-xi) * Pface[0][0][m]; Peta = eta * Pface[1][1][m] + (1.0-eta) * Pface[0][1][m]; Pzeta = zeta * Pface[1][2][m] + (1.0-zeta) * Pface[0][2][m]; u[k][j][i][m] = Pxi + Peta + Pzeta - Pxi*Peta - Pxi*Pzeta - Peta*Pzeta + Pxi*Peta*Pzeta; } } } } //--------------------------------------------------------------------- // now store the exact values on the boundaries //--------------------------------------------------------------------- //--------------------------------------------------------------------- // west face //--------------------------------------------------------------------- i = 0; xi = 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; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } //--------------------------------------------------------------------- // east face //--------------------------------------------------------------------- i = grid_points[0]-1; xi = 1.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; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } //--------------------------------------------------------------------- // south face //--------------------------------------------------------------------- j = 0; eta = 0.0; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)(k) * dnzm1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)(i) * dnxm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } //--------------------------------------------------------------------- // north face //--------------------------------------------------------------------- j = grid_points[1]-1; eta = 1.0; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)(k) * dnzm1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)(i) * dnxm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } //--------------------------------------------------------------------- // bottom face //--------------------------------------------------------------------- k = 0; zeta = 0.0; 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, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } //--------------------------------------------------------------------- // top face //--------------------------------------------------------------------- k = grid_points[2]-1; zeta = 1.0; 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, temp); for (m = 0; m < 5; m++) { u[k][j][i][m] = temp[m]; } } } #pragma omp target update to(u) brisbane_task task0; brisbane_task_create(&task0); brisbane_task_h2d_full(task0, mem_u, u); brisbane_task_submit(task0, brisbane_cpu, NULL, true); } void lhsinit(double lhs[][3][5][5], int size) { int i, m, n; i = size; //--------------------------------------------------------------------- // zero the whole left hand side for starters //--------------------------------------------------------------------- for (n = 0; n < 5; n++) { for (m = 0; m < 5; m++) { lhs[0][0][n][m] = 0.0; lhs[0][1][n][m] = 0.0; lhs[0][2][n][m] = 0.0; lhs[i][0][n][m] = 0.0; lhs[i][1][n][m] = 0.0; lhs[i][2][n][m] = 0.0; } } //--------------------------------------------------------------------- // next, set all diagonal values to 1. This is overkill, but convenient //--------------------------------------------------------------------- for (m = 0; m < 5; m++) { lhs[0][1][m][m] = 1.0; lhs[i][1][m][m] = 1.0; } }
imginputfileconn.h
/** * DeepDetect * Copyright (c) 2014 Emmanuel Benazera * Author: Emmanuel Benazera <beniz@droidnik.fr> * * This file is part of deepdetect. * * deepdetect 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. * * deepdetect 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 deepdetect. If not, see <http://www.gnu.org/licenses/>. */ #ifndef IMGINPUTFILECONN_H #define IMGINPUTFILECONN_H #include "inputconnectorstrategy.h" #include <opencv2/opencv.hpp> #ifdef USE_CUDA_CV #include <opencv2/cudaimgproc.hpp> #endif #if CV_VERSION_MAJOR >= 3 #define CV_LOAD_IMAGE_COLOR cv::IMREAD_COLOR #define CV_LOAD_IMAGE_GRAYSCALE cv::IMREAD_GRAYSCALE #define CV_LOAD_IMAGE_UNCHANGED cv::IMREAD_UNCHANGED #define CV_BGR2RGB cv::COLOR_BGR2RGB #define CV_BGR2GRAY cv::COLOR_BGR2GRAY #define CV_GRAY2RGB cv::COLOR_GRAY2RGB #define CV_YCrCb2RGB cv::COLOR_YCrCb2RGB #define CV_YCrCb2BGR cv::COLOR_YCrCb2BGR #define CV_BGR2YCrCb cv::COLOR_BGR2YCrCb #define CV_INTER_CUBIC cv::INTER_CUBIC #endif #include "ext/base64/base64.h" #include "utils/apitools.h" #include <random> namespace dd { class DDImg { public: DDImg() { } ~DDImg() { } // base64 detection bool is_within_base64_range(char c) const { if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || (c == '+' || c == '/' || c == '=')) return true; else return false; } bool possibly_base64(const std::string &s) const { bool ism = is_multiple_four(s); if (!ism) return false; for (char c : s) { bool within_64 = is_within_base64_range(c); if (!within_64) return false; } return true; } bool is_multiple_four(const std::string &s) const { if (s.length() % 4 == 0) return true; else return false; } void resize(const cv::Mat &src, cv::Mat &dst, const cv::Size &cvsize, const double &fx, const double &fy) const { #ifdef USE_CUDA_CV if (_cuda) { cv::cuda::GpuMat d_src; d_src.upload(src); cv::cuda::GpuMat d_dst; cv::cuda::resize(d_src, d_dst, cvsize, fx, fy, select_cv_interp()); if (_histogram_equalization) { if (_bw) { cv::cuda::equalizeHist(d_dst, d_dst); if (_rgb) cv::cuda::cvtColor(d_dst, d_dst, CV_GRAY2RGB); } else { // We don't apply equalizeHist on each BGR channels to keep // the color balance of the image. equalizeHist(V) of HSV can // works too, the result is almost the same cv::cuda::cvtColor(d_dst, d_dst, CV_BGR2YCrCb); std::vector<cv::cuda::GpuMat> vec_channels; cv::cuda::split(d_dst, vec_channels); cv::cuda::equalizeHist(vec_channels[0], vec_channels[0]); cv::cuda::merge(vec_channels, d_dst); if (_rgb) cv::cuda::cvtColor(d_dst, d_dst, CV_YCrCb2RGB); else cv::cuda::cvtColor(d_dst, d_dst, CV_YCrCb2BGR); } } else if (_rgb) { if (_bw) cv::cuda::cvtColor(d_dst, d_dst, CV_GRAY2RGB); else: cv::cuda::cvtColor(d_dst, d_dst, CV_BGR2RGB); } d_dst.download(dst); } else #endif { cv::resize(src, dst, cvsize, fx, fy, select_cv_interp()); if (_histogram_equalization) { if (_bw) { cv::equalizeHist(dst, dst); if (_rgb) cv::cvtColor(dst, dst, CV_GRAY2RGB); } else { // We don't apply equalizeHist on each BGR channels to keep // the color balance of the image. equalizeHist(V) of HSV can // works too, the result is almost the same cv::cvtColor(dst, dst, CV_BGR2YCrCb); std::vector<cv::Mat> vec_channels; cv::split(dst, vec_channels); cv::equalizeHist(vec_channels[0], vec_channels[0]); cv::merge(vec_channels, dst); if (_rgb) cv::cvtColor(dst, dst, CV_YCrCb2RGB); else cv::cvtColor(dst, dst, CV_YCrCb2BGR); } } else if (_rgb) { if (_bw) cv::cvtColor(dst, dst, CV_GRAY2RGB); else cv::cvtColor(dst, dst, CV_BGR2RGB); } } } void scale(const cv::Mat &src, cv::Mat &dst) const { float coef = std::min( static_cast<float>(_scale_max) / std::max(src.rows, src.cols), static_cast<float>(_scale_min) / std::min(src.rows, src.cols)); resize(src, dst, cv::Size(), coef, coef); } /// Apply preprocessing to image and add it to the list of images /// img_name: name of the image as displayed in error messages int add_image(const cv::Mat &img, const std::string &img_name) { if (_keep_orig) _orig_imgs.push_back(img); if (img.empty()) { _logger->error("empty image {}", img_name); return -1; } _imgs_size.push_back(std::pair<int, int>(img.rows, img.cols)); cv::Mat rimg; try { if (_scaled) scale(img, rimg); else if (_width == 0 || _height == 0) { if (_width == 0 && _height == 0) { // Do nothing and keep native resolution. May cause issues if // batched images are different resolutions rimg = img; } else { // Resize so that the larger dimension is set to whichever // (width or height) is non-zero, maintaining aspect ratio // XXX - This may cause issues if batch images are different // resolutions size_t currMaxDim = std::max(img.rows, img.cols); double scale = static_cast<double>(std::max(_width, _height)) / static_cast<double>(currMaxDim); resize(img, rimg, cv::Size(), scale, scale); } } else { // Resize normally to the specified width and height resize(img, rimg, cv::Size(_width, _height), 0, 0); } } catch (...) { throw InputConnectorBadParamException("failed resizing image " + img_name); } if (_crop_width != 0 && _crop_height != 0) { int widthBorder = (_width - _crop_width) / 2; int heightBorder = (_height - _crop_height) / 2; try { rimg = rimg(cv::Rect(widthBorder, heightBorder, _crop_width, _crop_height)); } catch (...) { throw InputConnectorBadParamException("failed cropping image " + img_name); } } _imgs.push_back(std::move(rimg)); return 0; } // decode image void decode(const std::string &str) { std::vector<unsigned char> vdat(str.begin(), str.end()); cv::Mat img = cv::Mat(cv::imdecode( cv::Mat(vdat, false), _unchanged_data ? CV_LOAD_IMAGE_UNCHANGED : (_bw ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_COLOR))); add_image(img, "base64 image"); } // deserialize image, independent of format void deserialize(std::stringstream &input) { size_t size = 0; input.seekg(0, input.end); size = input.tellg(); input.seekg(0, input.beg); char *data = new char[size]; input.read(data, size); std::string str(data, data + size); delete[] data; decode(str); } // data acquisition int read_file(const std::string &fname) { cv::Mat img = cv::imread(fname, _unchanged_data ? CV_LOAD_IMAGE_UNCHANGED : (_bw ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_COLOR)); return add_image(img, fname); } int read_db(const std::string &fname) { _db_fname = fname; return 0; } int read_mem(const std::string &content) { _in_mem = true; cv::Mat timg; _b64 = possibly_base64(content); if (_b64) { std::string ccontent; Base64::Decode(content, &ccontent); std::stringstream sstr; sstr << ccontent; deserialize(sstr); } else { decode(content); } if (_imgs.at(0).empty()) return -1; return 0; } int read_dir(const std::string &dir) { // list directories in dir std::unordered_set<std::string> subdirs; if (fileops::list_directory(dir, false, true, false, subdirs)) throw InputConnectorBadParamException( "failed reading text subdirectories in data directory " + dir); _logger->info("imginputfileconn: list subdirs size={}", subdirs.size()); // list files and classes std::vector<std::pair<std::string, int>> lfiles; // labeled files std::unordered_map<int, std::string> hcorresp; // correspondence class number / class name if (!subdirs.empty()) { int cl = 0; auto uit = subdirs.begin(); while (uit != subdirs.end()) { std::unordered_set<std::string> subdir_files; if (fileops::list_directory((*uit), true, false, true, subdir_files)) throw InputConnectorBadParamException( "failed reading image data sub-directory " + (*uit)); auto fit = subdir_files.begin(); while (fit != subdir_files.end()) // XXX: re-iterating the file // is not optimal { lfiles.push_back(std::pair<std::string, int>((*fit), cl)); ++fit; } ++cl; ++uit; } } else { std::unordered_set<std::string> test_files; fileops::list_directory(dir, true, false, false, test_files); auto fit = test_files.begin(); while (fit != test_files.end()) { lfiles.push_back( std::pair<std::string, int>((*fit), -1)); // -1 for no class ++fit; } } // read images _imgs.reserve(lfiles.size()); _img_files.reserve(lfiles.size()); _labels.reserve(lfiles.size()); for (std::pair<std::string, int> &p : lfiles) { cv::Mat img = cv::imread( p.first, _unchanged_data ? CV_LOAD_IMAGE_UNCHANGED : (_bw ? CV_LOAD_IMAGE_GRAYSCALE : CV_LOAD_IMAGE_COLOR)); add_image(img, p.first); _img_files.push_back(p.first); if (p.second >= 0) _labels.push_back(p.second); if (_imgs.size() % 1000 == 0) _logger->info("read {} images", _imgs.size()); } return 0; } int select_cv_interp() const { if (_interp == "nearest") return cv::INTER_NEAREST; else if (_interp == "linear") return cv::INTER_LINEAR; else if (_interp == "area") return cv::INTER_AREA; else if (_interp == "lanczos4") return cv::INTER_LANCZOS4; else /* if (_interp == "cubic") */ return cv::INTER_CUBIC; // default } std::vector<cv::Mat> _imgs; std::vector<cv::Mat> _orig_imgs; std::vector<std::string> _img_files; std::vector<std::pair<int, int>> _imgs_size; bool _bw = false; bool _rgb = false; bool _histogram_equalization = false; bool _in_mem = false; bool _unchanged_data = false; std::vector<int> _labels; int _width = 224; int _height = 224; int _crop_width = 0; int _crop_height = 0; float _scale = 1.0; bool _scaled = false; int _scale_min = 600; int _scale_max = 1000; bool _keep_orig = false; bool _b64 = false; std::string _interp = "cubic"; #ifdef USE_CUDA_CV bool _cuda = false; #endif std::string _db_fname; std::shared_ptr<spdlog::logger> _logger; }; class ImgInputFileConn : public InputConnectorStrategy { public: ImgInputFileConn() : InputConnectorStrategy() { } ImgInputFileConn(const ImgInputFileConn &i) : InputConnectorStrategy(i), _width(i._width), _height(i._height), _crop_width(i._crop_width), _crop_height(i._crop_height), _bw(i._bw), _rgb(i._rgb), _unchanged_data(i._unchanged_data), _test_split(i._test_split), _mean(i._mean), _has_mean_scalar(i._has_mean_scalar), _scale(i._scale), _scaled(i._scaled), _scale_min(i._scale_min), _scale_max(i._scale_max), _keep_orig(i._keep_orig), _interp(i._interp) #ifdef USE_CUDA_CV , _cuda(i._cuda) #endif { } ~ImgInputFileConn() { } void init(const APIData &ad) { fillup_parameters(ad); } void fillup_parameters(const APIData &ad) { // optional parameters. if (ad.has("width")) _width = ad.get("width").get<int>(); if (ad.has("height")) _height = ad.get("height").get<int>(); if (ad.has("crop_width")) { _crop_width = ad.get("crop_width").get<int>(); if (_crop_width > _width) { _logger->error("Crop width must be less than or equal to width"); throw InputConnectorBadParamException( "Crop width must be less than or equal to width"); } } if (ad.has("crop_height")) { _crop_height = ad.get("crop_height").get<int>(); if (_crop_height > _height) { _logger->error( "Crop height must be less than or equal to height"); throw InputConnectorBadParamException( "Crop height must be less than or equal to height"); } } if (ad.has("bw")) _bw = ad.get("bw").get<bool>(); if (ad.has("rgb")) _rgb = ad.get("rgb").get<bool>(); if (ad.has("histogram_equalization")) _histogram_equalization = ad.get("histogram_equalization").get<bool>(); if (ad.has("unchanged_data")) _unchanged_data = ad.get("unchanged_data").get<bool>(); if (ad.has("shuffle")) _shuffle = ad.get("shuffle").get<bool>(); if (ad.has("seed")) _seed = ad.get("seed").get<int>(); if (ad.has("test_split")) _test_split = ad.get("test_split").get<double>(); if (ad.has("mean")) { apitools::get_floats(ad, "mean", _mean); _has_mean_scalar = true; } if (ad.has("std")) { apitools::get_floats(ad, "std", _std); } // Variable size if (ad.has("scale")) _scale = ad.get("scale").get<double>(); if (ad.has("scaled") || ad.has("scale_min") || ad.has("scale_max")) _scaled = true; if (ad.has("scale_min")) _scale_min = ad.get("scale_min").get<int>(); if (ad.has("scale_max")) _scale_max = ad.get("scale_max").get<int>(); // whether to keep original image (for chained ops, e.g. cropping) if (ad.has("keep_orig")) _keep_orig = ad.get("keep_orig").get<bool>(); // image interpolation method if (ad.has("interp")) _interp = ad.get("interp").get<std::string>(); // timeout this->set_timeout(ad); #ifdef USE_CUDA_CV // image resizing on GPU if (ad.has("cuda")) _cuda = ad.get("cuda").get<bool>(); #endif } void copy_parameters_to(DDImg &dimg) const { dimg._bw = _bw; dimg._rgb = _rgb; dimg._histogram_equalization = _histogram_equalization; dimg._unchanged_data = _unchanged_data; dimg._width = _width; dimg._height = _height; dimg._crop_width = _crop_width; dimg._crop_height = _crop_height; dimg._scale = _scale; dimg._scaled = _scaled; dimg._scale_min = _scale_min; dimg._scale_max = _scale_max; dimg._keep_orig = _keep_orig; dimg._interp = _interp; #ifdef USE_CUDA_CV dimg._cuda = _cuda; #endif } int feature_size() const { if (_bw || _unchanged_data) { // XXX: only valid for single channels if (_crop_width != 0 && _crop_height != 0) return _crop_width * _crop_height; else return _width * _height; } else { // RGB if (_crop_width != 0 && _crop_height != 0) return _crop_width * _crop_height * 3; else return _width * _height * 3; } } int batch_size() const { return _images.size(); } int test_batch_size() const { return _test_images.size(); } void get_data(const APIData &ad) { // check for raw cv::Mat if (ad.has("data_raw_img")) { if (ad.has("ids")) _ids = ad.get("ids").get<std::vector<std::string>>(); if (ad.has("meta_uris")) _meta_uris = ad.get("meta_uris").get<std::vector<std::string>>(); if (ad.has("index_uris")) _index_uris = ad.get("index_uris").get<std::vector<std::string>>(); _images = ad.get("data_raw_img").get<std::vector<cv::Mat>>(); std::vector<cv::Mat> rimgs; std::vector<std::string> uris; int i = 0; for (auto img : _images) { cv::Mat rimg; resize(img, rimg, cv::Size(_width, _height), 0, 0); if (_bw && rimg.channels() > 1) { cv::Mat bwimg; cv::cvtColor(rimg, bwimg, CV_BGR2GRAY); rimg = bwimg; } _images_size.push_back(std::pair<int, int>(img.rows, img.cols)); if (_keep_orig) _orig_images.push_back(std::move(img)); if (!_ids.empty()) uris.push_back(_ids.at(i)); else { _ids.push_back(std::to_string(i)); uris.push_back(_ids.back()); } rimgs.push_back(std::move(rimg)); ++i; } _images = rimgs; if (!uris.empty()) _uris = uris; } else InputConnectorStrategy::get_data(ad); } void transform(const APIData &ad) { if (ad.has( "parameters")) // hotplug of parameters, overriding the defaults { APIData ad_param = ad.getobj("parameters"); if (ad_param.has("input")) { fillup_parameters(ad_param.getobj("input")); } } get_data(ad); if (!_images.empty()) // got ready raw images { return; } int catch_read = 0; std::string catch_msg; std::vector<std::string> uris; std::vector<std::string> meta_uris; std::vector<std::string> index_uris; std::vector<std::string> failed_uris; #pragma omp parallel for for (size_t i = 0; i < _uris.size(); i++) { bool no_img = false; std::string u = _uris.at(i); DataEl<DDImg> dimg(this->_input_timeout); copy_parameters_to(dimg._ctype); try { if (dimg.read_element(u, this->_logger)) { _logger->error("no data for image {}", u); no_img = true; } if (!dimg._ctype._db_fname.empty()) _db_fname = dimg._ctype._db_fname; } catch (std::exception &e) { #pragma omp critical { ++catch_read; catch_msg = e.what(); failed_uris.push_back(u); no_img = true; } } if (no_img) continue; if (!_db_fname.empty()) continue; #pragma omp critical { _images.insert(_images.end(), std::make_move_iterator(dimg._ctype._imgs.begin()), std::make_move_iterator(dimg._ctype._imgs.end())); if (_keep_orig) _orig_images.insert( _orig_images.end(), std::make_move_iterator(dimg._ctype._orig_imgs.begin()), std::make_move_iterator(dimg._ctype._orig_imgs.end())); _images_size.insert( _images_size.end(), std::make_move_iterator(dimg._ctype._imgs_size.begin()), std::make_move_iterator(dimg._ctype._imgs_size.end())); if (!dimg._ctype._labels.empty()) _test_labels.insert( _test_labels.end(), std::make_move_iterator(dimg._ctype._labels.begin()), std::make_move_iterator(dimg._ctype._labels.end())); if (!_ids.empty()) uris.push_back(_ids.at(i)); else if (!dimg._ctype._b64 && dimg._ctype._imgs.size() == 1) uris.push_back(u); else if (!dimg._ctype._img_files.empty()) uris.insert( uris.end(), std::make_move_iterator(dimg._ctype._img_files.begin()), std::make_move_iterator(dimg._ctype._img_files.end())); else uris.push_back(std::to_string(i)); if (!_meta_uris.empty()) meta_uris.push_back(_meta_uris.at(i)); if (!_index_uris.empty()) index_uris.push_back(_index_uris.at(i)); } } if (catch_read) { for (auto s : failed_uris) _logger->error("failed reading image {}", s); throw InputConnectorBadParamException(catch_msg); } _uris = uris; _ids = _uris; // since uris may be in different order than before // transform _meta_uris = meta_uris; _index_uris = index_uris; if (!_db_fname.empty()) return; // db filename is passed to backend // shuffle before possible split if (_shuffle) { std::mt19937 g; if (_seed >= 0) g = std::mt19937(_seed); else { std::random_device rd; g = std::mt19937(rd()); } std::shuffle(_images.begin(), _images.end(), g); // XXX beware: labels are not shuffled, i.e. let's // not shuffle while testing } // split as required if (_test_split > 0) { int split_size = std::floor(_images.size() * (1.0 - _test_split)); auto chit = _images.begin(); auto dchit = chit; int cpos = 0; while (chit != _images.end()) { if (cpos == split_size) { if (dchit == _images.begin()) dchit = chit; _test_images.push_back((*chit)); } else ++cpos; ++chit; } _images.erase(dchit, _images.end()); _logger->info("data split test size={} / remaining data size={}", _test_images.size(), _images.size()); } if (_images.empty()) throw InputConnectorBadParamException("no image could be found"); } // data std::vector<cv::Mat> _images; std::vector<cv::Mat> _orig_images; /**< stored upon request. */ std::vector<cv::Mat> _test_images; std::vector<int> _test_labels; std::vector<std::pair<int, int>> _images_size; // image parameters int _width = 224; int _height = 224; int _crop_width = 0; int _crop_height = 0; bool _bw = false; /**< whether to convert to black & white. */ bool _rgb = false; /**< whether to convert to rgb. */ bool _histogram_equalization = false; /**< whether to apply histogram equalizer. */ bool _unchanged_data = false; /**< IMREAD_UNCHANGED flag. */ double _test_split = 0.0; /**< auto-split of the dataset. */ int _seed = -1; /**< shuffling seed. */ std::vector<float> _mean; /**< mean image pixels, to be subtracted from images. */ std::vector<float> _std; /**< std, to divide image values. */ bool _has_mean_scalar = false; /**< whether scalar is set. */ std::string _db_fname; double _scale = 1.0; bool _scaled = false; int _scale_min = 600; int _scale_max = 1000; bool _keep_orig = false; std::string _interp = "cubic"; #ifdef USE_CUDA_CV bool _cuda = false; #endif }; } #ifdef USE_CAFFE #include "caffeinputconns.h" #endif #ifdef USE_TF #include "backends/tf/tfinputconns.h" #endif #ifdef USE_DLIB #include "backends/dlib/dlibinputconns.h" #endif #ifdef USE_NCNN #include "backends/ncnn/ncnninputconns.h" #endif #ifdef USE_CAFFE2 #include "backends/caffe2/caffe2inputconns.h" #endif #ifdef USE_TENSORRT #include "backends/tensorrt/tensorrtinputconns.h" #endif #ifdef USE_TORCH #include "backends/torch/torchinputconns.h" #endif #endif
GB_dense_subassign_21.c
//------------------------------------------------------------------------------ // GB_dense_subassign_21: C(:,:) = x where x is a scalar //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // C(:,:) = x where C is a matrix and x is a scalar #include "GB_dense.h" #include "GB_select.h" #include "GB_Pending.h" GrB_Info GB_dense_subassign_21 // C(:,:) = x; C is a matrix and x a scalar ( GrB_Matrix C, // input/output matrix const GB_void *scalar, // input scalar const GrB_Type atype, // type of the input scalar GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT_MATRIX_OK (C, "C for C(:,:)=x", GB0) ; ASSERT (scalar != NULL) ; // any prior pending tuples are discarded, and all zombies will be killed ASSERT (GB_PENDING_OK (C)) ; ASSERT (GB_ZOMBIES_OK (C)) ; ASSERT_TYPE_OK (atype, "atype for C(:,:)=x", GB0) ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- int64_t cvdim = C->vdim ; int64_t cvlen = C->vlen ; GrB_Index cnzmax ; bool ok = GB_Index_multiply (&cnzmax, cvlen, cvdim) ; if (!ok) { // problem too large return (GB_OUT_OF_MEMORY) ; } GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (cnzmax, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // typecast the scalar into the same type as C //-------------------------------------------------------------------------- int64_t csize = C->type->size ; GB_cast_function cast_A_to_C = GB_cast_factory (C->type->code, atype->code) ; GB_void cwork [GB_VLA(csize)] ; cast_A_to_C (cwork, scalar, atype->size) ; //-------------------------------------------------------------------------- // create the pattern, and allocate space for values, if needed //-------------------------------------------------------------------------- // discard any prior pending tuples GB_Pending_free (&(C->Pending)) ; int64_t pC ; if (GB_NNZ (C) < cnzmax || C->x_shallow || C->i_shallow || C->is_hyper || GB_ZOMBIES (C)) { //---------------------------------------------------------------------- // C is not yet dense: create pattern and allocate values //---------------------------------------------------------------------- // clear all prior content and recreate it; use exising header for C. // do not malloc C->x if the scalar is zero; calloc it later. bool scalar_is_nonzero = GB_is_nonzero (cwork, csize) ; GB_PHIX_FREE (C) ; GB_CREATE (&C, C->type, cvlen, cvdim, GB_Ap_malloc, C->is_csc, GB_FORCE_NONHYPER, C->hyper_ratio, C->vdim, cnzmax, scalar_is_nonzero, Context) ; if (info != GrB_SUCCESS) { // out of memory return (GB_OUT_OF_MEMORY) ; } int64_t *GB_RESTRICT Cp = C->p ; int64_t *GB_RESTRICT Ci = C->i ; int nth = GB_nthreads (cvdim, chunk, nthreads_max) ; // FUTURE:: dense data structure, where Cp and Ci will be implicit int64_t k ; #pragma omp parallel for num_threads(nth) schedule(static) for (k = 0 ; k <= cvdim ; k++) { Cp [k] = k * cvlen ; } C->magic = GB_MAGIC ; C->nvec_nonempty = (cvlen == 0) ? 0 : cvdim ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (pC = 0 ; pC < cnzmax ; pC++) { Ci [pC] = pC % cvlen ; } if (!scalar_is_nonzero) { GBBURBLE ("calloc ") ; GB_CALLOC_MEMORY (C->x, cnzmax, csize) ; } if (C->x == NULL) { // out of memory GB_PHIX_FREE (C) ; return (GB_OUT_OF_MEMORY) ; } if (!scalar_is_nonzero) { // quick return if the scalar is zero ASSERT_MATRIX_OK (C, "C(:,:)=0 output", GB0) ; return (GrB_SUCCESS) ; } } //-------------------------------------------------------------------------- // define the worker for the switch factory //-------------------------------------------------------------------------- // worker for built-in types #define GB_WORKER(ctype) \ { \ ctype *GB_RESTRICT Cx = C->x ; \ ctype x = (*(ctype *) cwork) ; \ GB_PRAGMA (omp parallel for num_threads(nthreads) schedule(static)) \ for (pC = 0 ; pC < cnzmax ; pC++) \ { \ Cx [pC] = x ; \ } \ } \ break ; //-------------------------------------------------------------------------- // launch the switch factory //-------------------------------------------------------------------------- switch (C->type->code) { case GB_BOOL_code : GB_WORKER (bool) ; case GB_INT8_code : GB_WORKER (int8_t) ; case GB_INT16_code : GB_WORKER (int16_t) ; case GB_INT32_code : GB_WORKER (int32_t) ; case GB_INT64_code : GB_WORKER (int64_t) ; case GB_UINT8_code : GB_WORKER (uint8_t) ; case GB_UINT16_code : GB_WORKER (uint16_t) ; case GB_UINT32_code : GB_WORKER (uint32_t) ; case GB_UINT64_code : GB_WORKER (uint64_t) ; case GB_FP32_code : GB_WORKER (float) ; case GB_FP64_code : GB_WORKER (double) ; default: { // worker for all user-defined types GB_BURBLE_N (cnzmax, "generic ") ; GB_void *GB_RESTRICT Cx = C->x ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (pC = 0 ; pC < cnzmax ; pC++) { memcpy (Cx +((pC)*csize), cwork, csize) ; } } break ; } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- ASSERT_MATRIX_OK (C, "C(:,:)=x output", GB0) ; return (GrB_SUCCESS) ; }
clean.h
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2004-2016 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ #ifndef __VCGLIB_CLEAN #define __VCGLIB_CLEAN #include <unordered_set> // VCG headers #include <vcg/complex/complex.h> #include <vcg/complex/algorithms/closest.h> #include <vcg/space/index/grid_static_ptr.h> #include <vcg/space/index/spatial_hashing.h> #include <vcg/complex/algorithms/update/normal.h> #include <vcg/space/triangle3.h> #include <vcg/complex/append.h> namespace vcg { namespace tri{ template <class ConnectedEdgeMeshType> class EdgeConnectedComponentIterator { public: typedef ConnectedEdgeMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::EdgeType EdgeType; typedef typename MeshType::EdgePointer EdgePointer; typedef typename MeshType::EdgeIterator EdgeIterator; typedef typename MeshType::ConstEdgeIterator ConstEdgeIterator; typedef typename MeshType::EdgeContainer EdgeContainer; public: void operator ++() { EdgePointer ep = se.top(); se.pop(); for(int i = 0; i < 2; ++i) { edge::VEIterator<EdgeType> vei(ep->V(i)); while (!vei.End()) { if (!tri::IsMarked(*mp, vei.E())) { tri::Mark(*mp, vei.E()); se.push(vei.E()); } ++vei; } } } void start(MeshType &m, EdgePointer e) { tri::RequirePerEdgeMark(m); mp=&m; while(!se.empty()) se.pop(); UnMarkAll(m); tri::Mark(m, e); se.push(e); } bool completed() { return se.empty(); } EdgePointer operator *() { return se.top(); } private: std::stack<EdgePointer> se; MeshType *mp; }; template <class ConnectedMeshType> class ConnectedComponentIterator { public: typedef ConnectedMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; public: void operator ++() { FacePointer fpt=sf.top(); sf.pop(); for(int j=0; j<fpt->VN(); ++j) if( !face::IsBorder(*fpt,j) ) { FacePointer l=fpt->FFp(j); if( !tri::IsMarked(*mp,l) ) { tri::Mark(*mp,l); sf.push(l); } } } void start(MeshType &m, FacePointer p) { tri::RequirePerFaceMark(m); mp=&m; while(!sf.empty()) sf.pop(); UnMarkAll(m); tri::Mark(m,p); sf.push(p); } bool completed() { return sf.empty(); } FacePointer operator *() { return sf.top(); } private: std::stack<FacePointer> sf; MeshType *mp; }; /// /** \addtogroup trimesh */ /*@{*/ /// Class of static functions to clean//restore meshs. template <class CleanMeshType> class Clean { public: typedef CleanMeshType MeshType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::VertexPointer VertexPointer; typedef typename MeshType::ConstVertexPointer ConstVertexPointer; typedef typename MeshType::VertexIterator VertexIterator; typedef typename MeshType::ConstVertexIterator ConstVertexIterator; typedef typename MeshType::EdgeIterator EdgeIterator; typedef typename MeshType::EdgePointer EdgePointer; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; typedef typename MeshType::ConstFaceIterator ConstFaceIterator; typedef typename MeshType::FaceContainer FaceContainer; typedef typename MeshType::TetraType TetraType; typedef typename MeshType::TetraPointer TetraPointer; typedef typename MeshType::TetraIterator TetraIterator; typedef typename MeshType::ConstTetraIterator ConstTetraIterator; typedef typename vcg::Box3<ScalarType> Box3Type; typedef GridStaticPtr<FaceType, ScalarType > TriMeshGrid; /* classe di confronto per l'algoritmo di eliminazione vertici duplicati*/ class RemoveDuplicateVert_Compare{ public: inline bool operator()(VertexPointer const &a, VertexPointer const &b) { return ((*a).cP() == (*b).cP()) ? (a<b): ((*a).cP() < (*b).cP()); } }; /** This function removes all duplicate vertices of the mesh by looking only at their spatial positions. * Note that it does not update any topology relation that could be affected by this like the VT or TT relation. * the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateVertex( MeshType & m, bool RemoveDegenerateFlag=true) // V1.0 { if(m.vert.size()==0 || m.vn==0) return 0; std::map<VertexPointer, VertexPointer> mp; size_t i,j; VertexIterator vi; int deleted=0; int k=0; size_t num_vert = m.vert.size(); std::vector<VertexPointer> perm(num_vert); for(vi=m.vert.begin(); vi!=m.vert.end(); ++vi, ++k) perm[k] = &(*vi); RemoveDuplicateVert_Compare c_obj; std::sort(perm.begin(),perm.end(),c_obj); j = 0; i = j; mp[perm[i]] = perm[j]; ++i; for(;i!=num_vert;) { if( (! (*perm[i]).IsD()) && (! (*perm[j]).IsD()) && (*perm[i]).P() == (*perm[j]).cP() ) { VertexPointer t = perm[i]; mp[perm[i]] = perm[j]; ++i; Allocator<MeshType>::DeleteVertex(m,*t); deleted++; } else { j = i; ++i; } } for(FaceIterator fi = m.face.begin(); fi!=m.face.end(); ++fi) if( !(*fi).IsD() ) for(k = 0; k < (*fi).VN(); ++k) if( mp.find( (typename MeshType::VertexPointer)(*fi).V(k) ) != mp.end() ) { (*fi).V(k) = &*mp[ (*fi).V(k) ]; } for(EdgeIterator ei = m.edge.begin(); ei!=m.edge.end(); ++ei) if( !(*ei).IsD() ) for(k = 0; k < 2; ++k) if( mp.find( (typename MeshType::VertexPointer)(*ei).V(k) ) != mp.end() ) { (*ei).V(k) = &*mp[ (*ei).V(k) ]; } for (TetraIterator ti = m.tetra.begin(); ti != m.tetra.end(); ++ti) if (!(*ti).IsD()) for (k = 0; k < 4; ++k) if (mp.find((typename MeshType::VertexPointer)(*ti).V(k)) != mp.end()) (*ti).V(k) = &*mp[ (*ti).V(k) ]; if(RemoveDegenerateFlag) RemoveDegenerateFace(m); if(RemoveDegenerateFlag && m.en>0) { RemoveDegenerateEdge(m); RemoveDuplicateEdge(m); } return deleted; } class SortedPair { public: SortedPair() {} SortedPair(unsigned int v0, unsigned int v1, EdgePointer _fp) { v[0]=v0;v[1]=v1; fp=_fp; if(v[0]>v[1]) std::swap(v[0],v[1]); } bool operator < (const SortedPair &p) const { return (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedPair &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) ) return true; return false; } unsigned int v[2]; EdgePointer fp; }; class SortedTriple { public: SortedTriple() {} SortedTriple(unsigned int v0, unsigned int v1, unsigned int v2,FacePointer _fp) { v[0]=v0;v[1]=v1;v[2]=v2; fp=_fp; std::sort(v,v+3); } bool operator < (const SortedTriple &p) const { return (v[2]!=p.v[2])?(v[2]<p.v[2]): (v[1]!=p.v[1])?(v[1]<p.v[1]): (v[0]<p.v[0]); } bool operator == (const SortedTriple &s) const { if( (v[0]==s.v[0]) && (v[1]==s.v[1]) && (v[2]==s.v[2]) ) return true; return false; } unsigned int v[3]; FacePointer fp; }; /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateFace( MeshType & m) // V1.0 { std::vector<SortedTriple> fvec; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { fvec.push_back(SortedTriple( tri::Index(m,(*fi).V(0)), tri::Index(m,(*fi).V(1)), tri::Index(m,(*fi).V(2)), &*fi)); } std::sort(fvec.begin(),fvec.end()); int total=0; for(int i=0;i<int(fvec.size())-1;++i) { if(fvec[i]==fvec[i+1]) { total++; tri::Allocator<MeshType>::DeleteFace(m, *(fvec[i].fp) ); } } return total; } /** This function removes all duplicate faces of the mesh by looking only at their vertex reference. So it should be called after unification of vertices. Note that it does not update any topology relation that could be affected by this like the VT or TT relation. the reason this function is usually performed BEFORE building any topology information. */ static int RemoveDuplicateEdge( MeshType & m) // V1.0 { if (m.en==0) return 0; std::vector<SortedPair> eVec; for(EdgeIterator ei=m.edge.begin();ei!=m.edge.end();++ei) if(!(*ei).IsD()) { eVec.push_back(SortedPair( tri::Index(m,(*ei).V(0)), tri::Index(m,(*ei).V(1)), &*ei)); } std::sort(eVec.begin(),eVec.end()); int total=0; for(int i=0;i<int(eVec.size())-1;++i) { if(eVec[i]==eVec[i+1]) { total++; tri::Allocator<MeshType>::DeleteEdge(m, *(eVec[i].fp) ); } } return total; } static int CountUnreferencedVertex( MeshType& m) { return RemoveUnreferencedVertex(m,false); } /** This function removes vertices that are not referenced by any face or by any edge. @param m The mesh @param DeleteVertexFlag if false prevent the vertex deletion and just count it. @return The number of removed vertices */ static int RemoveUnreferencedVertex( MeshType& m, bool DeleteVertexFlag=true) // V1.0 { tri::RequirePerVertexFlags(m); std::vector<bool> referredVec(m.vert.size(),false); int deleted = 0; for(auto fi = m.face.begin(); fi != m.face.end(); ++fi) if( !(*fi).IsD() ) for(auto j=0; j < (*fi).VN(); ++j) referredVec[tri::Index(m, (*fi).V(j))]=true; for(auto ei=m.edge.begin();ei!=m.edge.end();++ei) if( !(*ei).IsD() ){ referredVec[tri::Index(m, (*ei).V(0))]=true; referredVec[tri::Index(m, (*ei).V(1))]=true; } for(auto ti=m.tetra.begin(); ti!=m.tetra.end();++ti) if( !(*ti).IsD() ){ referredVec[tri::Index(m, (*ti).V(0))]=true; referredVec[tri::Index(m, (*ti).V(1))]=true; referredVec[tri::Index(m, (*ti).V(2))]=true; referredVec[tri::Index(m, (*ti).V(3))]=true; } if(!DeleteVertexFlag) return std::count(referredVec.begin(),referredVec.end(),false); for(auto vi=m.vert.begin();vi!=m.vert.end();++vi) if( (!(*vi).IsD()) && (!referredVec[tri::Index(m,*vi)]) ) { Allocator<MeshType>::DeleteVertex(m,*vi); ++deleted; } return deleted; } /** Degenerate vertices are vertices that have coords with invalid floating point values, All the faces incident on deleted vertices are also deleted */ static int RemoveDegenerateVertex(MeshType& m) { VertexIterator vi; int count_vd = 0; for(vi=m.vert.begin(); vi!=m.vert.end();++vi) if(math::IsNAN( (*vi).P()[0]) || math::IsNAN( (*vi).P()[1]) || math::IsNAN( (*vi).P()[2]) ) { count_vd++; Allocator<MeshType>::DeleteVertex(m,*vi); } FaceIterator fi; int count_fd = 0; for(fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) if( (*fi).V(0)->IsD() || (*fi).V(1)->IsD() || (*fi).V(2)->IsD() ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } return count_vd; } /** Degenerate faces are faces that are Topologically degenerate, i.e. have two or more vertex reference that link the same vertex (and not only two vertexes with the same coordinates). All Degenerate faces are zero area faces BUT not all zero area faces are degenerate. We do not take care of topology because when we have degenerate faces the topology calculation functions crash. */ static int RemoveDegenerateFace(MeshType& m) { int count_fd = 0; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD()) { if((*fi).V(0) == (*fi).V(1) || (*fi).V(0) == (*fi).V(2) || (*fi).V(1) == (*fi).V(2) ) { count_fd++; Allocator<MeshType>::DeleteFace(m,*fi); } } return count_fd; } static int RemoveDegenerateEdge(MeshType& m) { int count_ed = 0; for(EdgeIterator ei=m.edge.begin(); ei!=m.edge.end();++ei) if(!(*ei).IsD()) { if((*ei).V(0) == (*ei).V(1) ) { count_ed++; Allocator<MeshType>::DeleteEdge(m,*ei); } } return count_ed; } static int RemoveNonManifoldVertex(MeshType& m) { CountNonManifoldVertexFF(m,true); tri::UpdateSelection<MeshType>::FaceFromVertexLoose(m); int count_removed = 0; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!(*fi).IsD() && (*fi).IsS()) Allocator<MeshType>::DeleteFace(m,*fi); for(VertexIterator vi=m.vert.begin(); vi!=m.vert.end();++vi) if(!(*vi).IsD() && (*vi).IsS()) { ++count_removed; Allocator<MeshType>::DeleteVertex(m,*vi); } return count_removed; } static int SplitSelectedVertexOnEdgeMesh(MeshType& m) { tri::RequireCompactness(m); // count selected vertices references std::unordered_map<size_t,size_t> refCount; // selected vertex index -> reference count size_t countSplit = 0; for (size_t i=0; i<m.edge.size(); ++i) { for (int j=0; j<2; ++j) { const VertexPointer vp = m.edge[i].V(j); if (vp->IsS()) { const size_t refs = ++refCount[Index(m, m.edge[i].V(j))]; if (refs > 1) { countSplit++; } } } } // actual split if (countSplit > 0) { auto newVertIt = tri::Allocator<MeshType>::AddVertices(m, countSplit); for (size_t i=0; i<m.edge.size(); ++i) { for (int j=0; j<2; ++j) { const VertexPointer vp = m.edge[i].V(j); const size_t vIdx = Index(m, vp); if (vp->IsS()) { if (--refCount[vIdx] > 0) { newVertIt->ImportData(*vp); m.edge[i].V(j) = &*(newVertIt++); } } } } } return int(countSplit); } static void SelectNonManifoldVertexOnEdgeMesh(MeshType &m) { tri::RequireCompactness(m); tri::UpdateSelection<MeshType>::VertexClear(m); std::vector<int> cnt(m.vn,0); for(size_t i=0;i<m.edge.size();++i) { cnt[tri::Index(m,m.edge[i].V(0))]++; cnt[tri::Index(m,m.edge[i].V(1))]++; } for(size_t i=0;i<m.vert.size();++i) if(cnt[i]>2) m.vert[i].SetS(); } static void SelectCreaseVertexOnEdgeMesh(MeshType &m, ScalarType AngleRadThr) { tri::RequireCompactness(m); tri::RequireVEAdjacency(m); tri::UpdateTopology<MeshType>::VertexEdge(m); tri::UpdateSelection<MeshType>::VertexClear(m); for(size_t i=0;i<m.vert.size();++i) { std::vector<VertexPointer> VVStarVec; edge::VVStarVE(&(m.vert[i]),VVStarVec); if(VVStarVec.size()==2) { CoordType v0 = m.vert[i].P() - VVStarVec[0]->P(); CoordType v1 = m.vert[i].P() - VVStarVec[1]->P(); float angle = M_PI-vcg::Angle(v0,v1); if(angle > AngleRadThr) m.vert[i].SetS(); } } } /// Removal of faces that were incident on a non manifold edge. // Given a mesh with FF adjacency // it search for non manifold vertices and duplicate them. // Duplicated vertices are moved apart according to the move threshold param. // that is a percentage of the average vector from the non manifold vertex to the barycenter of the incident faces. static int SplitNonManifoldVertex(MeshType& m, ScalarType moveThreshold) { RequireFFAdjacency(m); typedef std::pair<FacePointer,int> FaceInt; // a face and the index of the vertex that we have to change // std::vector<std::pair<VertexPointer, std::vector<FaceInt> > >ToSplitVec; SelectionStack<MeshType> ss(m); ss.push(); CountNonManifoldVertexFF(m,true); UpdateFlags<MeshType>::VertexClearV(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for (int i=0; i<fi->VN(); i++) if ((*fi).V(i)->IsS() && !(*fi).V(i)->IsV()) { (*fi).V(i)->SetV(); face::Pos<FaceType> startPos(&*fi,i); face::Pos<FaceType> curPos = startPos; std::set<FaceInt> faceSet; do { faceSet.insert(std::make_pair(curPos.F(),curPos.VInd())); curPos.FlipE(); curPos.NextF(); } while (curPos != startPos); ToSplitVec.push_back(make_pair((*fi).V(i),std::vector<FaceInt>())); typename std::set<FaceInt>::const_iterator iii; for(iii=faceSet.begin();iii!=faceSet.end();++iii) ToSplitVec.back().second.push_back(*iii); } } ss.pop(); // Second step actually add new vertices and split them. typename tri::Allocator<MeshType>::template PointerUpdater<VertexPointer> pu; VertexIterator firstVp = tri::Allocator<MeshType>::AddVertices(m,ToSplitVec.size(),pu); for(size_t i =0;i<ToSplitVec.size();++i) { // qDebug("Splitting Vertex %i",ToSplitVec[i].first-&*m.vert.begin()); VertexPointer np=ToSplitVec[i].first; pu.Update(np); firstVp->ImportData(*np); // loop on the face to be changed, and also compute the movement vector; CoordType delta(0,0,0); for(size_t j=0;j<ToSplitVec[i].second.size();++j) { FaceInt ff=ToSplitVec[i].second[j]; ff.first->V(ff.second)=&*firstVp; delta+=Barycenter(*(ff.first))-np->cP(); } delta /= ToSplitVec[i].second.size(); firstVp->P() = firstVp->P() + delta * moveThreshold; firstVp++; } return int(ToSplitVec.size()); } /// \brief This function expand current selection to cover the whole connected component. static size_t SplitManifoldComponents(MeshType &m, const ScalarType moveThreshold = 0) { typedef typename MeshType::FacePointer FacePointer; typedef typename MeshType::FaceIterator FaceIterator; // it also assumes that the FF adjacency is well computed. RequireFFAdjacency(m); UpdateFlags<MeshType>::FaceClearV(m); UpdateFlags<MeshType>::FaceClearS(m); MeshType tmpMesh; tmpMesh.vert.EnableVFAdjacency(); tmpMesh.face.EnableVFAdjacency(); if (m.face.IsWedgeTexCoordEnabled()) tmpMesh.face.EnableWedgeTexCoord(); size_t selCnt=0; for(FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if( !(*fi).IsD() && !(*fi).IsV() && !(*fi).IsS()) { UpdateFlags<MeshType>::FaceClearS(m); std::deque<FacePointer> visitStack; visitStack.push_back(&*fi); (*fi).SetS(); (*fi).SetV(); while(!visitStack.empty()) { FacePointer fp = visitStack.front(); visitStack.pop_front(); for(int i=0;i<fp->VN();++i) { FacePointer ff = fp->FFp(i); if(face::IsManifold(*fp, i) && !ff->IsS() && !ff->IsV()) { ff->SetS(); ff->SetV(); visitStack.push_back(ff); } } } Append<MeshType, MeshType>::Mesh(tmpMesh, m, true); ++selCnt; } vcg::tri::UpdateTopology<MeshType>::VertexFace(tmpMesh); vcg::tri::UpdateFlags<MeshType>::VertexBorderFromNone(tmpMesh); for (size_t i = 0; i < size_t(tmpMesh.VN()); ++i) { VertexType & v = tmpMesh.vert[i]; if (v.IsB()) { std::vector<FacePointer> faceVec; std::vector<int> idxVec; vcg::face::VFStarVF(&v, faceVec, idxVec); CoordType delta(0, 0, 0); for (auto fp : faceVec) { delta += vcg::Barycenter(*fp) - v.cP(); } delta /= faceVec.size(); v.P() += delta * moveThreshold; } } UpdateSelection<MeshType>::Clear(tmpMesh); Append<MeshType, MeshType>::MeshCopy(m, tmpMesh); return selCnt; } // Auxiliary function for sorting the non manifold faces according to their area. Used in RemoveNonManifoldFace struct CompareAreaFP { bool operator ()(FacePointer const& f1, FacePointer const& f2) const { return DoubleArea(*f1) < DoubleArea(*f2); } }; /// Removal of faces that were incident on a non manifold edge. static int RemoveNonManifoldFace(MeshType& m) { FaceIterator fi; int count_fd = 0; std::vector<FacePointer> ToDelVec; for(fi=m.face.begin(); fi!=m.face.end();++fi) if (!fi->IsD()) { if ((!IsManifold(*fi,0))|| (!IsManifold(*fi,1))|| (!IsManifold(*fi,2))) ToDelVec.push_back(&*fi); } std::sort(ToDelVec.begin(),ToDelVec.end(),CompareAreaFP()); for(size_t i=0;i<ToDelVec.size();++i) { if(!ToDelVec[i]->IsD()) { FaceType &ff= *ToDelVec[i]; if ((!IsManifold(ff,0))|| (!IsManifold(ff,1))|| (!IsManifold(ff,2))) { for(int j=0;j<3;++j) if(!face::IsBorder<FaceType>(ff,j)) vcg::face::FFDetach<FaceType>(ff,j); Allocator<MeshType>::DeleteFace(m,ff); count_fd++; } } } return count_fd; } /* Remove the faces that are out of a given range of area */ static int RemoveFaceOutOfRangeArea(MeshType& m, ScalarType MinAreaThr=0, ScalarType MaxAreaThr=(std::numeric_limits<ScalarType>::max)(), bool OnlyOnSelected=false) { int count_fd = 0; MinAreaThr*=2; MaxAreaThr*=2; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi){ if(!(*fi).IsD()) if(!OnlyOnSelected || (*fi).IsS()) { const ScalarType doubleArea=DoubleArea<FaceType>(*fi); if((doubleArea<=MinAreaThr) || (doubleArea>=MaxAreaThr) ) { Allocator<MeshType>::DeleteFace(m,*fi); count_fd++; } } } return count_fd; } static int RemoveZeroAreaFace(MeshType& m) { return RemoveFaceOutOfRangeArea(m,0);} /** * Is the mesh only composed by quadrilaterals? */ static bool IsBitQuadOnly(const MeshType &m) { typedef typename MeshType::FaceType F; tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->Flags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp != F::FAUX0 && tmp != F::FAUX1 && tmp != F::FAUX2) return false; } return true; } static bool IsFaceFauxConsistent(MeshType &m) { RequirePerFaceFlags(m); RequireFFAdjacency(m); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { for(int z=0;z<(*fi).VN();++z) { FacePointer fp = fi->FFp(z); int zp = fi->FFi(z); if(fi->IsF(z) != fp->IsF(zp)) return false; } } return true; } /** * Is the mesh only composed by triangles? (non polygonal faces) */ static bool IsBitTriOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if ( !fi->IsD() && fi->IsAnyF() ) return false; } return true; } static bool IsBitPolygonal(const MeshType &m){ return !IsBitTriOnly(m); } /** * Is the mesh only composed by quadrilaterals and triangles? (no pentas, etc) * It assumes that the bits are consistent. In that case there can be only a single faux edge. */ static bool IsBitTriQuadOnly(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp!=F::FAUX0 && tmp!=F::FAUX1 && tmp!=F::FAUX2 && tmp!=0 ) return false; } return true; } /** * How many quadrilaterals? * It assumes that the bits are consistent. In that case we count the tris with a single faux edge and divide by two. */ static int CountBitQuads(const MeshType &m) { tri::RequirePerFaceFlags(m); typedef typename MeshType::FaceType F; int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { unsigned int tmp = fi->cFlags()&(F::FAUX0|F::FAUX1|F::FAUX2); if ( tmp==F::FAUX0 || tmp==F::FAUX1 || tmp==F::FAUX2) count++; } return count / 2; } /** * How many triangles? (non polygonal faces) */ static int CountBitTris(const MeshType &m) { tri::RequirePerFaceFlags(m); int count=0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (!(fi->IsAnyF())) count++; } return count; } /** * How many polygons of any kind? (including triangles) * it assumes that there are no faux vertexes (e.g vertices completely surrounded by faux edges) */ static int CountBitPolygons(const MeshType &m) { tri::RequirePerFaceFlags(m); int count = 0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { if (fi->IsF(0)) count++; if (fi->IsF(1)) count++; if (fi->IsF(2)) count++; } return m.fn - count/2; } /** * The number of polygonal faces is * FN - EN_f (each faux edge hides exactly one triangular face or in other words a polygon of n edges has n-3 faux edges.) * In the general case where a The number of polygonal faces is * FN - EN_f + VN_f * where: * EN_f is the number of faux edges. * VN_f is the number of faux vertices (e.g vertices completely surrounded by faux edges) * as a intuitive proof think to a internal vertex that is collapsed onto a border of a polygon: * it deletes 2 faces, 1 faux edges and 1 vertex so to keep the balance you have to add back the removed vertex. */ static int CountBitLargePolygons(const MeshType &m) { //note - using unordered_map to set visited vertices because //the mesh is const (before, the function used vertex flags...). //could be used std::vector<bool> if the vertex has the Index() //member function... std::unordered_map<ConstVertexPointer, bool> vertVisited; for (ConstVertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD()) vertVisited[&(*vi)] = true; // First loop Clear all referenced vertices for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i){ vertVisited[fi->V(i)] = false; } // Second Loop, count (twice) faux edges and mark all vertices touched by non faux edges // (e.g vertexes on the boundary of a polygon) int countE = 0; for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0;i<3;++i) { if (fi->IsF(i)) countE++; else { vertVisited[fi->V0(i)] = true; vertVisited[fi->V1(i)] = true; } } } // Third Loop, count the number of referenced vertexes that are completely surrounded by faux edges. int countV = 0; for (ConstVertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD() && !(vertVisited[&(*vi)])) countV++; return m.fn - countE/2 + countV ; } /** * Checks that the mesh has consistent per-face faux edges * (the ones that merges triangles into larger polygons). * A border edge should never be faux, and faux edges should always be * reciprocated by another faux edges. * It requires FF adjacency. */ static bool HasConsistentPerFaceFauxFlag(const MeshType &m) { RequireFFAdjacency(m); RequirePerFaceFlags(m); for (ConstFaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) for (int k=0; k<3; k++) if( ( fi->IsF(k) != fi->cFFp(k)->IsF(fi->cFFi(k)) ) || ( fi->IsF(k) && face::IsBorder(*fi,k)) ) { return false; } return true; } /** * Count the number of non manifold edges in a polylinemesh, e.g. the edges where there are more than 2 incident faces. * */ static int CountNonManifoldEdgeEE( MeshType & m, bool SelectFlag=false) { MeshAssert<MeshType>::OnlyEdgeMesh(m); RequireEEAdjacency(m); tri::UpdateTopology<MeshType>::EdgeEdge(m); if(SelectFlag) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. EdgeIterator ei; for (ei = m.edge.begin(); ei != m.edge.end(); ++ei) if (!ei->IsD()) { TD[(*ei).V(0)]++; TD[(*ei).V(1)]++; } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop, Check that each vertex have been seen 1 or 2 times. for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if (!vi->IsD()) { if( TD[vi] >2 ) { if(SelectFlag) (*vi).SetS(); nonManifoldCnt++; } } return nonManifoldCnt; } /** * Count the number of non manifold edges in a mesh, e.g. the edges where there are more than 2 incident faces. * * Note that this test is not enough to say that a mesh is two manifold, * you have to count also the non manifold vertexes. */ static int CountNonManifoldEdgeFF( MeshType & m, bool SelectFlag=false) { RequireFFAdjacency(m); int nmfBit[3]; nmfBit[0]= FaceType::NewBitFlag(); nmfBit[1]= FaceType::NewBitFlag(); nmfBit[2]= FaceType::NewBitFlag(); UpdateFlags<MeshType>::FaceClear(m,nmfBit[0]+nmfBit[1]+nmfBit[2]); if(SelectFlag){ UpdateSelection<MeshType>::VertexClear(m); UpdateSelection<MeshType>::FaceClear(m); } int edgeCnt = 0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD()) { for(int i=0;i<3;++i) if(!IsManifold(*fi,i)) { if(!(*fi).IsUserBit(nmfBit[i])) { ++edgeCnt; if(SelectFlag) { (*fi).V0(i)->SetS(); (*fi).V1(i)->SetS(); } // follow the ring of faces incident on edge i; face::Pos<FaceType> nmf(&*fi,i); do { if(SelectFlag) nmf.F()->SetS(); nmf.F()->SetUserBit(nmfBit[nmf.E()]); nmf.NextF(); } while(nmf.f != &*fi); } } } } return edgeCnt; } /** Count (and eventually select) non 2-Manifold vertexes of a mesh * e.g. the vertices with a non 2-manif. neighbourhood but that do not belong to not 2-manif edges. * typical situation two cones connected by one vertex. */ static int CountNonManifoldVertexFF( MeshType & m, bool selectVert = true, bool clearSelection = true) { RequireFFAdjacency(m); if(selectVert && clearSelection) UpdateSelection<MeshType>::VertexClear(m); int nonManifoldCnt=0; SimpleTempData<typename MeshType::VertContainer, int > TD(m.vert,0); // First Loop, just count how many faces are incident on a vertex and store it in the TemporaryData Counter. FaceIterator fi; for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for (int k=0; k<fi->VN(); k++) { TD[(*fi).V(k)]++; } } tri::UpdateFlags<MeshType>::VertexClearV(m); // Second Loop. // mark out of the game the vertexes that are incident on non manifold edges. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0; i<fi->VN(); ++i) if (!IsManifold(*fi,i)) { (*fi).V0(i)->SetV(); (*fi).V1(i)->SetV(); } } // Third Loop, for safe vertexes, check that the number of faces that you can reach starting // from it and using FF is the same of the previously counted. for (fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) { for(int i=0; i<fi->VN(); i++) if (!(*fi).V(i)->IsV()) { (*fi).V(i)->SetV(); face::Pos<FaceType> pos(&(*fi),i); int starSizeFF = pos.NumberOfIncidentFaces(); if (starSizeFF != TD[(*fi).V(i)]) { if (selectVert) (*fi).V(i)->SetS(); nonManifoldCnt++; } } } return nonManifoldCnt; } /// Very simple test of water tightness. No boundary and no non manifold edges. /// Assume that it is orientable. /// It could be debated if a closed non orientable surface is watertight or not. /// /// The rationale of not testing orientability here is that /// it requires FFAdj while this test do not require any adjacency. /// static bool IsWaterTight(MeshType & m) { int edgeNum=0,edgeBorderNum=0,edgeNonManifNum=0; CountEdgeNum(m, edgeNum, edgeBorderNum,edgeNonManifNum); return (edgeBorderNum==0) && (edgeNonManifNum==0); } static void CountEdgeNum( MeshType & m, int &total_e, int &boundary_e, int &non_manif_e ) { std::vector< typename tri::UpdateTopology<MeshType>::PEdge > edgeVec; tri::UpdateTopology<MeshType>::FillEdgeVector(m,edgeVec,true); sort(edgeVec.begin(), edgeVec.end()); // Lo ordino per vertici total_e=0; boundary_e=0; non_manif_e=0; size_t f_on_cur_edge =1; for(size_t i=0;i<edgeVec.size();++i) { if(( (i+1) == edgeVec.size()) || !(edgeVec[i] == edgeVec[i+1])) { ++total_e; if(f_on_cur_edge==1) ++boundary_e; if(f_on_cur_edge>2) ++non_manif_e; f_on_cur_edge=1; } else { ++f_on_cur_edge; } } // end for } static int CountHoles( MeshType & m) { UpdateFlags<MeshType>::FaceClearV(m); int loopNum=0; for(FaceIterator fi=m.face.begin(); fi!=m.face.end();++fi) if(!fi->IsD()) { for(int j=0;j<3;++j) { if(!fi->IsV() && face::IsBorder(*fi,j)) { face::Pos<FaceType> startPos(&*fi,j); face::Pos<FaceType> curPos=startPos; do { curPos.NextB(); curPos.F()->SetV(); } while(curPos!=startPos); ++loopNum; } } } return loopNum; } /* Compute the set of connected components of a given mesh it fills a vector of pair < int , faceptr > with, for each connecteed component its size and a represnant */ static int CountConnectedComponents(MeshType &m) { std::vector< std::pair<int,FacePointer> > CCV; return ConnectedComponents(m,CCV); } static int ConnectedComponents(MeshType &m, std::vector< std::pair<int,FacePointer> > &CCV) { tri::RequireFFAdjacency(m); CCV.clear(); tri::UpdateFlags<MeshType>::FaceClearV(m); std::stack<FacePointer> sf; FacePointer fpt=&*(m.face.begin()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD()) && !(*fi).IsV()) { (*fi).SetV(); CCV.push_back(std::make_pair(0,&*fi)); sf.push(&*fi); while (!sf.empty()) { fpt=sf.top(); ++CCV.back().first; sf.pop(); for(int j=0; j<fpt->VN(); ++j) { if( !face::IsBorder(*fpt,j) ) { FacePointer l = fpt->FFp(j); if( !(*l).IsV() ) { (*l).SetV(); sf.push(l); } } } } } } return int(CCV.size()); } static int edgeMeshConnectedComponents(MeshType & poly, std::vector<std::pair<int, typename MeshType::EdgePointer> > &eCC) { typedef typename MeshType::EdgePointer EdgePointer; tri::UpdateTopology<MeshType>::VertexEdge(poly); tri::UpdateFlags<MeshType>::EdgeClear(poly); eCC.clear(); std::stack<EdgePointer> stack; for (auto ei = poly.edge.begin(); ei != poly.edge.end(); ++ei) if (!ei->IsD() && !ei->IsV()) { ei->SetV(); std::pair<int, EdgePointer> cc(1, &*ei); stack.push(&*ei); while (!stack.empty()) { EdgePointer ep = stack.top(); stack.pop(); for (int i = 0; i < 2; ++i) { edge::VEIterator<typename MeshType::EdgeType> vei(ep->V(i)); while (!vei.End()) { if (!vei.E()->IsV()) { vei.E()->SetV(); stack.push(vei.E()); cc.first += 1; } ++vei; } } } eCC.push_back(cc); } return int(eCC.size()); } static void ComputeValence( MeshType &m, typename MeshType::PerVertexIntHandle &h) { for(VertexIterator vi=m.vert.begin(); vi!= m.vert.end();++vi) h[vi]=0; for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) { if(!((*fi).IsD())) for(int j=0;j<fi->VN();j++) ++h[tri::Index(m,fi->V(j))]; } } /** GENUS. A topologically invariant property of a surface defined as the largest number of non-intersecting simple closed curves that can be drawn on the surface without separating it. Roughly speaking, it is the number of holes in a surface. The genus g of a closed surface, also called the geometric genus, is related to the Euler characteristic by the relation $chi$ by $chi==2-2g$. The genus of a connected, orientable surface is an integer representing the maximum number of cuttings along closed simple curves without rendering the resultant manifold disconnected. It is equal to the number of handles on it. For general polyhedra the <em>Euler Formula</em> is: V - E + F = 2 - 2G - B where V is the number of vertices, F is the number of faces, E is the number of edges, G is the genus and B is the number of <em>boundary polygons</em>. The above formula is valid for a mesh with one single connected component. By considering multiple connected components the formula becomes: V - E + F = 2C - 2Gs - B -> 2Gs = - ( V-E+F +B -2C) where C is the number of connected components and Gs is the sum of the genus of all connected components. Note that in the case of a mesh with boundaries the intuitive meaning of Genus is less intuitive that it could seem. A closed sphere, a sphere with one hole (e.g. a disk) and a sphere with two holes (e.g. a tube) all of them have Genus == 0 */ static int MeshGenus(int nvert,int nedges,int nfaces, int numholes, int numcomponents) { return -((nvert + nfaces - nedges + numholes - 2 * numcomponents) / 2); } static int MeshGenus(MeshType &m) { int nvert=m.vn; int nfaces=m.fn; int boundary_e,total_e,nonmanif_e; CountEdgeNum(m,total_e,boundary_e,nonmanif_e); int numholes=CountHoles(m); int numcomponents=CountConnectedComponents(m); int G=MeshGenus(nvert,total_e,nfaces,numholes,numcomponents); return G; } /** * Check if the given mesh is regular, semi-regular or irregular. * * Each vertex of a \em regular mesh has valence 6 except for border vertices * which have valence 4. * * A \em semi-regular mesh is derived from an irregular one applying * 1-to-4 subdivision recursively. (not checked for now) * * All other meshes are \em irregular. */ static void IsRegularMesh(MeshType &m, bool &Regular, bool &Semiregular) { RequireVFAdjacency(m); Regular = true; VertexIterator vi; // for each vertex the number of edges are count for (vi = m.vert.begin(); vi != m.vert.end(); ++vi) { if (!vi->IsD()) { face::Pos<FaceType> he((*vi).VFp(), &*vi); face::Pos<FaceType> ht = he; int n=0; bool border=false; do { ++n; ht.NextE(); if (ht.IsBorder()) border=true; } while (ht != he); if (border) n = n/2; if ((n != 6)&&(!border && n != 4)) { Regular = false; break; } } } if (!Regular) Semiregular = false; else { // For now we do not account for semi-regularity Semiregular = false; } } static bool IsCoherentlyOrientedMesh(MeshType &m) { RequireFFAdjacency(m); MeshAssert<MeshType>::FFAdjacencyIsInitialized(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if (!fi->IsD()) for(int i=0;i<3;++i) if(!face::CheckOrientation(*fi,i)) return false; return true; } static void OrientCoherentlyMesh(MeshType &m, bool &_IsOriented, bool &_IsOrientable) { RequireFFAdjacency(m); MeshAssert<MeshType>::FFAdjacencyIsInitialized(m); bool IsOrientable = true; bool IsOriented = true; UpdateFlags<MeshType>::FaceClearV(m); std::stack<FacePointer> faces; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) { if (!fi->IsD() && !fi->IsV()) { // each face put in the stack is selected (and oriented) fi->SetV(); faces.push(&(*fi)); while (!faces.empty()) { FacePointer fp = faces.top(); faces.pop(); // make consistently oriented the adjacent faces for (int j = 0; j < 3; j++) { if (!face::IsBorder(*fp,j) && face::IsManifold<FaceType>(*fp, j)) { FacePointer fpaux = fp->FFp(j); int iaux = fp->FFi(j); if (!CheckOrientation(*fpaux, iaux)) { IsOriented = false; if (!fpaux->IsV()) face::SwapEdge<FaceType,true>(*fpaux, iaux); else { IsOrientable = false; break; } } if (!fpaux->IsV()) { fpaux->SetV(); faces.push(fpaux); } } } } } if (!IsOrientable) break; } _IsOriented = IsOriented; _IsOrientable = IsOrientable; } /// Flip the orientation of the whole mesh flipping all the faces (by swapping the first two vertices) static void FlipMesh(MeshType &m, bool selected=false) { for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) if(!selected || (*fi).IsS()) { face::SwapEdge<FaceType,false>((*fi), 0); if (HasPerWedgeTexCoord(m)) std::swap((*fi).WT(0),(*fi).WT(1)); } } /// Flip a mesh so that its normals are orented outside. /// Just for safety it uses a voting scheme. /// It assumes that /// mesh has already has coherent normals. /// mesh is watertight and signle component. static bool FlipNormalOutside(MeshType &m) { if(m.vert.empty()) return false; tri::UpdateNormal<MeshType>::PerVertexAngleWeighted(m); tri::UpdateNormal<MeshType>::NormalizePerVertex(m); std::vector< VertexPointer > minVertVec; std::vector< VertexPointer > maxVertVec; // The set of directions to be chosen std::vector< CoordType > dirVec; dirVec.push_back(CoordType(1,0,0)); dirVec.push_back(CoordType(0,1,0)); dirVec.push_back(CoordType(0,0,1)); dirVec.push_back(CoordType( 1, 1,1)); dirVec.push_back(CoordType(-1, 1,1)); dirVec.push_back(CoordType(-1,-1,1)); dirVec.push_back(CoordType( 1,-1,1)); for(size_t i=0;i<dirVec.size();++i) { Normalize(dirVec[i]); minVertVec.push_back(&*m.vert.begin()); maxVertVec.push_back(&*m.vert.begin()); } for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if(!(*vi).IsD()) { for(size_t i=0;i<dirVec.size();++i) { if( (*vi).cP().dot(dirVec[i]) < minVertVec[i]->P().dot(dirVec[i])) minVertVec[i] = &*vi; if( (*vi).cP().dot(dirVec[i]) > maxVertVec[i]->P().dot(dirVec[i])) maxVertVec[i] = &*vi; } } int voteCount=0; ScalarType angleThreshold = cos(math::ToRad(85.0)); for(size_t i=0;i<dirVec.size();++i) { // qDebug("Min vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],minVertVec[i]->P()[0],minVertVec[i]->P()[1],minVertVec[i]->P()[2]); // qDebug("Max vert along (%f %f %f) is %f %f %f",dirVec[i][0],dirVec[i][1],dirVec[i][2],maxVertVec[i]->P()[0],maxVertVec[i]->P()[1],maxVertVec[i]->P()[2]); if(minVertVec[i]->N().dot(dirVec[i]) > angleThreshold ) voteCount++; if(maxVertVec[i]->N().dot(dirVec[i]) < -angleThreshold ) voteCount++; } // qDebug("votecount = %i",voteCount); if(voteCount < int(dirVec.size())/2) return false; FlipMesh(m); return true; } // Search and remove small single triangle folds // - a face has normal opposite to all other faces // - choose the edge that brings to the face f1 containing the vertex opposite to that edge. static int RemoveFaceFoldByFlip(MeshType &m, float normalThresholdDeg=175, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; ScalarType NormalThrRad = math::ToRad(normalThresholdDeg); ScalarType eps = ScalarType(0.0001); // this epsilon value is in absolute value. It is a distance from edge in baricentric coords. //detection stage for(FaceIterator fi=m.face.begin();fi!= m.face.end();++fi ) if(!(*fi).IsV()) { Point3<ScalarType> NN = vcg::TriangleNormal((*fi)).Normalize(); if( vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(0)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(1)).Normalize()) > NormalThrRad && vcg::AngleN(NN,TriangleNormal(*(*fi).FFp(2)).Normalize()) > NormalThrRad ) { (*fi).SetS(); //(*fi).C()=Color4b(Color4b::Red); // now search the best edge to flip for(int i=0;i<3;i++) { Point3<ScalarType> &p=(*fi).P2(i); Point3<ScalarType> L; bool ret = vcg::InterpolationParameters((*(*fi).FFp(i)),TriangleNormal(*(*fi).FFp(i)),p,L); if(ret && L[0]>eps && L[1]>eps && L[2]>eps) { (*fi).FFp(i)->SetS(); (*fi).FFp(i)->SetV(); //(*fi).FFp(i)->C()=Color4b(Color4b::Green); if(face::CheckFlipEdge<FaceType>( *fi, i )) { face::FlipEdge<FaceType>( *fi, i ); ++count; ++total; } } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByFlip(MeshType &m, float threshold=40, bool repeat=true) { RequireFFAdjacency(m); RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UpdateTopology<MeshType>::FaceFace(m); tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); // Find largest triangle side int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); if(face::CheckFlipEdge<FaceType>( *f, i )) { // Check if EdgeFlipping improves quality FacePointer g = f->FFp(i); int k = f->FFi(i); Triangle3<ScalarType> t1(f->P(i), f->P1(i), f->P2(i)), t2(g->P(k), g->P1(k), g->P2(k)), t3(f->P(i), g->P2(k), f->P2(i)), t4(g->P(k), f->P2(i), g->P2(k)); if ( std::min( QualityFace(t1), QualityFace(t2) ) < std::min( QualityFace(t3), QualityFace(t4) )) { face::FlipEdge<FaceType>( *f, i ); ++count; ++total; } } } } // tri::UpdateNormal<MeshType>::PerFace(m); } while( repeat && count ); return total; } static int RemoveTVertexByCollapse(MeshType &m, float threshold=40, bool repeat=true) { RequirePerVertexMark(m); //Counters for logging and convergence int count, total = 0; do { tri::UnMarkAll(m); count = 0; //detection stage for(unsigned int index = 0 ; index < m.face.size(); ++index ) { FacePointer f = &(m.face[index]); float sides[3]; CoordType dummy; sides[0] = Distance(f->P(0), f->P(1)); sides[1] = Distance(f->P(1), f->P(2)); sides[2] = Distance(f->P(2), f->P(0)); int i = std::find(sides, sides+3, std::max( std::max(sides[0],sides[1]), sides[2])) - (sides); if( tri::IsMarked(m,f->V2(i) )) continue; if( PSDist(f->P2(i),f->P(i),f->P1(i),dummy)*threshold <= sides[i] ) { tri::Mark(m,f->V2(i)); int j = Distance(dummy,f->P(i))<Distance(dummy,f->P1(i))?i:(i+1)%3; f->P2(i) = f->P(j); tri::Mark(m,f->V(j)); ++count; ++total; } } tri::Clean<MeshType>::RemoveDuplicateVertex(m); tri::Allocator<MeshType>::CompactFaceVector(m); tri::Allocator<MeshType>::CompactVertexVector(m); } while( repeat && count ); return total; } static bool SelfIntersections(MeshType &m, std::vector<FaceType*> &ret) { RequirePerFaceMark(m); ret.clear(); int referredBit = FaceType::NewBitFlag(); tri::UpdateFlags<MeshType>::FaceClear(m,referredBit); TriMeshGrid gM; gM.Set(m.face.begin(),m.face.end()); for(FaceIterator fi=m.face.begin();fi!=m.face.end();++fi) if(!(*fi).IsD()) { (*fi).SetUserBit(referredBit); Box3< ScalarType> bbox; (*fi).GetBBox(bbox); std::vector<FaceType*> inBox; vcg::tri::GetInBoxFace(m, gM, bbox,inBox); bool Intersected=false; typename std::vector<FaceType*>::iterator fib; for(fib=inBox.begin();fib!=inBox.end();++fib) { if(!(*fib)->IsUserBit(referredBit) && (*fib != &*fi) ) if(Clean<MeshType>::TestFaceFaceIntersection(&*fi,*fib)){ ret.push_back(*fib); if(!Intersected) { ret.push_back(&*fi); Intersected=true; } } } inBox.clear(); } FaceType::DeleteBitFlag(referredBit); return (ret.size()>0); } /** This function simply test that the vn and fn counters be consistent with the size of the containers and the number of deleted simplexes. */ static bool IsSizeConsistent(MeshType &m) { int DeletedVertNum=0; for (VertexIterator vi = m.vert.begin(); vi != m.vert.end(); ++vi) if((*vi).IsD()) DeletedVertNum++; int DeletedEdgeNum=0; for (EdgeIterator ei = m.edge.begin(); ei != m.edge.end(); ++ei) if((*ei).IsD()) DeletedEdgeNum++; int DeletedFaceNum=0; for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if((*fi).IsD()) DeletedFaceNum++; if(size_t(m.vn+DeletedVertNum) != m.vert.size()) return false; if(size_t(m.en+DeletedEdgeNum) != m.edge.size()) return false; if(size_t(m.fn+DeletedFaceNum) != m.face.size()) return false; return true; } /** This function simply test that all the faces have a consistent face-face topology relation. useful for checking that a topology modifying algorithm does not mess something. */ static bool IsFFAdjacencyConsistent(MeshType &m) { RequireFFAdjacency(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { for(int i=0;i<3;++i) if(!FFCorrectness(*fi, i)) return false; } return true; } /** This function simply test that a mesh has some reasonable tex coord. */ static bool HasConsistentPerWedgeTexCoord(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { FaceType &f=(*fi); if( ! ( (f.WT(0).N() == f.WT(1).N()) && (f.WT(0).N() == (*fi).WT(2).N()) ) ) return false; // all the vertices must have the same index. if((*fi).WT(0).N() <0) return false; // no undefined texture should be allowed } return true; } /** Simple check that there are no face with all collapsed tex coords. */ static bool HasZeroTexCoordFace(MeshType &m) { tri::RequirePerFaceWedgeTexCoord(m); for (FaceIterator fi = m.face.begin(); fi != m.face.end(); ++fi) if(!(*fi).IsD()) { if( (*fi).WT(0).P() == (*fi).WT(1).P() && (*fi).WT(0).P() == (*fi).WT(2).P() ) return false; } return true; } /** This function test if two triangular faces of a mesh intersect. It assumes that the faces (as storage) are different (e.g different address) If the two faces are different but coincident (same set of vertexes) return true. if the faces share an edge no test is done. if the faces share only a vertex, the opposite edge is tested against the face */ static bool TestFaceFaceIntersection(FaceType *f0,FaceType *f1) { int sv = face::CountSharedVertex(f0,f1); if(sv==3) return true; if(sv==0) return (vcg::IntersectionTriangleTriangle<FaceType>((*f0),(*f1))); // if the faces share only a vertex, the opposite edge (as a segment) is tested against the face // to avoid degenerate cases where the two triangles have the opposite edge on a common plane // we offset the segment to test toward the shared vertex if(sv==1) { int i0,i1; ScalarType a,b; face::FindSharedVertex(f0,f1,i0,i1); CoordType shP = f0->V(i0)->P()*0.5; if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f0).V1(i0)->P()*0.5+shP,(*f0).V2(i0)->P()*0.5+shP), *f1, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } if(vcg::IntersectionSegmentTriangle(Segment3<ScalarType>((*f1).V1(i1)->P()*0.5+shP,(*f1).V2(i1)->P()*0.5+shP), *f0, a, b) ) { // a,b are the param coords of the intersection point of the segment. if(a+b>=1 || a<=EPSIL || b<=EPSIL ) return false; return true; } } return false; } /** This function merge all the vertices that are closer than the given radius */ static int MergeCloseVertex(MeshType &m, const ScalarType radius) { int mergedCnt=0; mergedCnt = ClusterVertex(m,radius); RemoveDuplicateVertex(m,true); return mergedCnt; } static int ClusterVertex(MeshType &m, const ScalarType radius) { if(m.vn==0) return 0; // some spatial indexing structure does not work well with deleted vertices... tri::Allocator<MeshType>::CompactVertexVector(m); typedef vcg::SpatialHashTable<VertexType, ScalarType> SampleSHT; SampleSHT sht; tri::EmptyTMark<MeshType> markerFunctor; std::vector<VertexType*> closests; int mergedCnt=0; sht.Set(m.vert.begin(), m.vert.end()); UpdateFlags<MeshType>::VertexClearV(m); for(VertexIterator viv = m.vert.begin(); viv!= m.vert.end(); ++viv) if(!(*viv).IsD() && !(*viv).IsV()) { (*viv).SetV(); Point3<ScalarType> p = viv->cP(); Box3<ScalarType> bb(p-Point3<ScalarType>(radius,radius,radius),p+Point3<ScalarType>(radius,radius,radius)); GridGetInBox(sht, markerFunctor, bb, closests); // qDebug("Vertex %i has %i closest", &*viv - &*m.vert.begin(),closests.size()); for(size_t i=0; i<closests.size(); ++i) { ScalarType dist = Distance(p,closests[i]->cP()); if(dist < radius && !closests[i]->IsV()) { // printf("%f %f \n",dist,radius); mergedCnt++; closests[i]->SetV(); closests[i]->P()=p; } } } return mergedCnt; } static std::pair<int,int> RemoveSmallConnectedComponentsSize(MeshType &m, int maxCCSize) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { std::vector<typename MeshType::FacePointer> FPV; if(CCV[i].first<maxCCSize) { DeletedCC++; for(ci.start(m,CCV[i].second);!ci.completed();++ci) FPV.push_back(*ci); typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components smaller than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveSmallConnectedComponentsDiameter(MeshType &m, ScalarType maxDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3<ScalarType> bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()<maxDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /// Remove the connected components greater than a given diameter // it returns a pair with the number of connected components and the number of deleted ones. static std::pair<int,int> RemoveHugeConnectedComponentsDiameter(MeshType &m, ScalarType minDiameter) { std::vector< std::pair<int, typename MeshType::FacePointer> > CCV; int TotalCC=ConnectedComponents(m, CCV); int DeletedCC=0; tri::ConnectedComponentIterator<MeshType> ci; for(unsigned int i=0;i<CCV.size();++i) { Box3f bb; std::vector<typename MeshType::FacePointer> FPV; for(ci.start(m,CCV[i].second);!ci.completed();++ci) { FPV.push_back(*ci); bb.Add((*ci)->P(0)); bb.Add((*ci)->P(1)); bb.Add((*ci)->P(2)); } if(bb.Diag()>minDiameter) { DeletedCC++; typename std::vector<typename MeshType::FacePointer>::iterator fpvi; for(fpvi=FPV.begin(); fpvi!=FPV.end(); ++fpvi) tri::Allocator<MeshType>::DeleteFace(m,(**fpvi)); } } return std::make_pair(TotalCC,DeletedCC); } /** Select the folded faces using an angle threshold on the face normal. The face is selected if the dot product between the face normal and the normal of the plane fitted using the vertices of the one ring faces is below the cosThreshold. The cosThreshold requires a negative cosine value (a positive value is clamp to zero). */ static void SelectFoldedFaceFromOneRingFaces(MeshType &m, ScalarType cosThreshold) { typedef std::unordered_set<VertexPointer> VertexSet; tri::RequireVFAdjacency(m); tri::RequirePerFaceNormal(m); tri::RequirePerVertexNormal(m); vcg::tri::UpdateSelection<MeshType>::FaceClear(m); vcg::tri::UpdateNormal<MeshType>::PerFaceNormalized(m); vcg::tri::UpdateNormal<MeshType>::PerVertexNormalized(m); vcg::tri::UpdateTopology<MeshType>::VertexFace(m); if (cosThreshold > 0) cosThreshold = 0; #pragma omp parallel for schedule(dynamic, 10) for (int i = 0; i < m.face.size(); i++) { VertexSet nearVertex; std::vector<CoordType> pointVec; FacePointer f = &m.face[i]; for (int j = 0; j < 3; j++) { std::vector<VertexPointer> temp; vcg::face::VVStarVF<FaceType>(f->V(j), temp); typename std::vector<VertexPointer>::iterator iter = temp.begin(); for (; iter != temp.end(); iter++) { if ((*iter) != f->V1(j) && (*iter) != f->V2(j)) { if (nearVertex.insert((*iter)).second) pointVec.push_back((*iter)->P()); } } nearVertex.insert(f->V(j)); pointVec.push_back(f->P(j)); } if (pointVec.size() > 3) { vcg::Plane3<ScalarType> plane; vcg::FitPlaneToPointSet(pointVec, plane); float avgDot = 0; for (auto nvp : nearVertex) avgDot += plane.Direction().dot(nvp->N()); avgDot /= nearVertex.size(); typename MeshType::VertexType::NormalType normal; if (avgDot < 0) normal = -plane.Direction(); else normal = plane.Direction(); if (normal.dot(f->N()) < cosThreshold) f->SetS(); } } } /** Select the faces on the first mesh that intersect the second mesh. It uses a grid for querying so a face::mark should be added. */ static int SelectIntersectingFaces(MeshType &m1, MeshType &m2) { RequirePerFaceMark(m2); RequireCompactness(m1); RequireCompactness(m2); tri::UpdateSelection<MeshType>::FaceClear(m1); TriMeshGrid gM; gM.Set(m2.face.begin(),m2.face.end()); int selCnt=0; for(auto fi=m1.face.begin();fi!=m1.face.end();++fi) { Box3< ScalarType> bbox; (*fi).GetBBox(bbox); std::vector<FaceType*> inBox; vcg::tri::GetInBoxFace(m2, gM, bbox,inBox); for(auto fib=inBox.begin(); fib!=inBox.end(); ++fib) { if(Clean<MeshType>::TestFaceFaceIntersection(&*fi,*fib)){ fi->SetS(); ++selCnt; } } inBox.clear(); } return selCnt; } }; // end class /*@}*/ } //End Namespace Tri } // End Namespace vcg #endif
integral.c
#include <math.h> float IntegrateMyFunction(int const n, float const a, float const b) { // Running sum of the integral float I = 0.0f; // Integration interval float const dx = (b-a)/float(n); // Loop through the integration range #pragma omp parallel for for (int i = 0; i < n; i++) { // Midpoint of the integration interval float const x = a + dx*(float(i) + 0.5f); // Function value at the midpoint float const f = 1.0f/sqrtf(x); // Incrementing the running sum #pragma omp critical { I += f; } } // Scale according to the integration interval I *= dx; return I; }
GB_binop__bclr_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__bclr_int64 // A.*B function (eWiseMult): GB_AemultB__bclr_int64 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__bclr_int64 // C+=b function (dense accum): GB_Cdense_accumb__bclr_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__bclr_int64 // C=scalar+B GB_bind1st__bclr_int64 // C=scalar+B' GB_bind1st_tran__bclr_int64 // C=A+scalar GB_bind2nd__bclr_int64 // C=A'+scalar GB_bind2nd_tran__bclr_int64 // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = GB_BITCLR (aij, bij, int64_t, 64) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_BITCLR (x, y, int64_t, 64) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BCLR || GxB_NO_INT64 || GxB_NO_BCLR_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (none) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__bclr_int64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__bclr_int64 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__bclr_int64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *GB_RESTRICT Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__bclr_int64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__bclr_int64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__bclr_int64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = Bx [p] ; Cx [p] = GB_BITCLR (x, bij, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__bclr_int64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = Ax [p] ; Cx [p] = GB_BITCLR (aij, y, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITCLR (x, aij, int64_t, 64) ; \ } GrB_Info GB_bind1st_tran__bclr_int64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITCLR (aij, y, int64_t, 64) ; \ } GrB_Info GB_bind2nd_tran__bclr_int64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bli_axpyv_bgq_int.c
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The University of Texas at Austin 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 "blis.h" void bli_daxpyv_bgq_int ( conj_t conjx, dim_t n, double* restrict alpha, double* restrict x, inc_t incx, double* restrict y, inc_t incy, cntx_t* restrict cntx ) { if ( bli_zero_dim1( n ) ) return; // If there is anything that would interfere with our use of aligned // vector loads/stores, call the reference implementation. bool_t use_ref = FALSE; if ( incx != 1 || incy != 1 || bli_is_unaligned_to( ( siz_t )x, 32 ) || bli_is_unaligned_to( ( siz_t )y, 32 ) ) { use_ref = TRUE; } // Call the reference implementation if needed. if ( use_ref == TRUE ) { BLIS_DAXPYV_KERNEL_REF( conjx, n, alpha, x, incx, y, incy, cntx ); return; } dim_t n_run = n / 4; dim_t n_left = n % 4; vector4double xv, yv, zv; vector4double alphav = vec_lds( 0 * sizeof(double), (double*)alpha ); #pragma omp parallel for for ( dim_t i = 0; i < n_run; i++ ) { xv = vec_lda( 0 * sizeof(double), &x[i*4] ); yv = vec_lda( 0 * sizeof(double), &y[i*4] ); zv = vec_madd( alphav, xv, yv ); vec_sta( zv, 0 * sizeof(double), &y[i*4] ); } for ( dim_t i = 0; i < n_left; i++ ) { y[4*n_run + i] += *alpha * x[4*n_run + i]; } }
sampler.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sort.h> #include <gsl/gsl_math.h> // gsl_finite #ifdef _OPENMP #include <omp.h> #endif const size_t N=10000; const size_t T=1000; const size_t K=20; const size_t L=2; const double alpha_k = 0.5; /* * 0: thompson sampling * 1: uniform subset * */ const unsigned int strategy = 0; #include "helpers.h" #include "model.h" #include "set_counter.h" #define to_string(arr, k) \ for (size_t i = 0; i < k-1; i++) { \ printf("%.16lf,", arr[i]); \ } \ printf("%.16lf", arr[k-1]); unsigned int move_gibbs(double *restrict random_numbers, double logth[K], size_t ngames, const size_t games[ngames][L], const size_t game_counts[ngames], const size_t win_counts[K]) { double ll, ll_p; double alpha; double logth_comp_old; double logth_Km1_old; unsigned int accepted = 0; for (size_t comp=0; comp<K-1; comp++) { assert(gsl_fcmp(log_sum_exp(logth, K), 1.0, 1e-15) == 0); ll = fullcond(comp, logth, ngames, games, game_counts, win_counts); /* sample a suitable value for the current component */ logth_comp_old = logth[comp]; logth_Km1_old = logth[K-1]; if (logth_comp_old > logth[K-1]) { logth[comp] = log(*random_numbers++) + logth_comp_old + log1p(exp(logth[K-1] - logth_comp_old)); logth[K-1] = logth_comp_old + log1p(exp(logth_Km1_old - logth_comp_old) - exp(logth[comp] - logth_comp_old)); } else { logth[comp] = log(*random_numbers++) + logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old)); logth[K-1] = logth_Km1_old + log1p(exp(logth_comp_old - logth_Km1_old) - exp(logth[comp] - logth_Km1_old)); } /* compute full conditional density at th_p */ ll_p = fullcond(comp, logth, ngames, games, game_counts, win_counts); alpha = *random_numbers++; if (log(alpha) < ll_p - ll) { /* accept */ accepted = 1; } else { /* reject */ /* reset the proposed component back to its original value */ /* th[K-1] += th[comp] - th_comp_old; */ /* th[comp] = th_comp_old; */ /* assert(th[K-1] >= 0); */ logth[comp] = logth_comp_old; logth[K-1] = logth_Km1_old; } } return accepted; } void resample_move(const gsl_rng *r, double logtheta[N][K], const double w[N], const struct set_counter *games_counter, const size_t wins[K]) { unsigned int cnt[N]; size_t accepted = 0; gsl_ran_multinomial(r, N, N, w, cnt); /* populate particles */ double (*logtheta_new)[K] = malloc(N * sizeof *logtheta_new); size_t n_new = 0; for (size_t n=0; n<N; n++) { for (size_t i=0; i < cnt[n]; i++) { memcpy(logtheta_new[n_new++], logtheta[n], sizeof *logtheta_new); } } /* pre-generate random numbers to avoid thread synchronization */ double (*random_numbers)[2*(K-1)] = malloc(N * sizeof *random_numbers); for (size_t n=0; n<N; n++) { for (size_t k=0; k<2*(K-1); k++) { random_numbers[n][k] = gsl_rng_uniform_pos(r); } } /* extract game counts from the counter */ size_t ngames = games_counter->size; size_t (*games)[L] = malloc(ngames * sizeof *games); size_t *game_counts = malloc(ngames * sizeof *game_counts); set_counter_keys(games_counter, games); set_counter_values(games_counter, game_counts); #pragma omp parallel for reduction(+:accepted) for (size_t n=0; n<N; n++) { accepted += move_gibbs(random_numbers[n], logtheta_new[n], ngames, games, game_counts, wins); } printf("# to_move = %zu\n", N); printf("# accepted = %zu\n", accepted); printf("# acceptance ratio = %lf\n", (double) accepted / N); memcpy(logtheta, logtheta_new, N*K*sizeof(double)); free(logtheta_new); free(random_numbers); free(games); free(game_counts); } void sample_theta_star(const gsl_rng *r, double theta_star[K]) { double a[K]; for (size_t k=0; k<K; k++) { a[k] = alpha_k; } gsl_ran_dirichlet(r, K, a, theta_star); } void read_theta_star(const char *file_name, double theta_star[K]) { char buf[80]; FILE *ts = fopen(file_name, "r"); if (!ts) { fprintf(stderr, "error reading %s\n", file_name); exit(EXIT_FAILURE); } for (size_t k = 0; k<K; k++) { if (!fgets(buf, 80, ts)) { fprintf(stderr, "error reading %s\n", file_name); exit(EXIT_FAILURE); } theta_star[k] = atof(buf); }; fclose(ts); } void sim(const gsl_rng *r, const double theta_star[K]) { double (*logtheta)[K] = malloc(N * sizeof *logtheta); double *w = malloc(N * sizeof(double)); double *logw = malloc(N * sizeof(double)); ones(w, N); zeros(logw, N); size_t *wins = calloc(K, sizeof *wins); struct set_counter *games_counter = set_counter_alloc(); /* general info */ printf("# generator type: %s\n", gsl_rng_name(r)); printf("# seed = %lu\n", gsl_rng_default_seed); printf("\n"); /* sample N particles from the `uniform` prior */ { double alpha[K]; ones(alpha, K); double theta[K]; for (size_t n = 0; n < N; n++) { gsl_ran_dirichlet(r, K, alpha, theta); #pragma omp simd for (size_t k=0; k<K; k++) logtheta[n][k] = log(theta[k]); } } for(size_t t = 0; t < T; t++) { fprintf(stderr, "t = %zu\r", t); /* for progress monitoring */ printf("# iteration = %zu\n", t); size_t players[L]; if (strategy == 0) { /* presentation strategy: thompson sampling */ printf("# strategy: thompson\n"); /* sample a theta from the current posterior */ gsl_ran_discrete_t *g = gsl_ran_discrete_preproc(N, w); size_t theta_sample_idx = gsl_ran_discrete(r, g); gsl_ran_discrete_free(g); printf("# sampled theta: "); to_string(logtheta[theta_sample_idx], K); printf("\n"); /* pick L elements from current sample */ gsl_sort_largest_index(players, L, logtheta[theta_sample_idx], 1, K); } else if (strategy == 1) { /* presentation strategy: uniform subset */ printf("# strategy: uniform subset\n"); size_t idx[K]; for (size_t k=0; k<K; k++) idx[k] = k; gsl_ran_choose(r, players, L, idx, K, sizeof(size_t)); } set_counter_add(games_counter, players); printf("# number of unique subsets so far: %zu\n", games_counter->size); double player_w[L]; printf("# game: "); for (size_t l=0; l<L-1; l++) { printf("%zu,", players[l]); player_w[l] = theta_star[players[l]]; } printf("%zu\n", players[L-1]); player_w[L-1] = theta_star[players[L-1]]; printf("# player weights = "); to_string(player_w, L); printf("\n"); /* determine outcome using theta_star */ size_t winner; { gsl_ran_discrete_t *g = gsl_ran_discrete_preproc(L, player_w); size_t wn = gsl_ran_discrete(r, g); winner = players[wn]; gsl_ran_discrete_free(g); } printf("# winner: %zu\n", winner); wins[winner]++; /* update weights */ #pragma omp parallel for for(size_t n = 0; n < N; n++) { double logtheta_winner = logtheta[n][winner]; double lth_game[L]; for (size_t l=0; l<L; l++) { lth_game[l] = logtheta[n][players[l]]; } logw[n] += logtheta_winner - log_sum_exp(lth_game, L); } /* compute w from logw */ { double lse = log_sum_exp(logw, N); for (size_t n=0; n<N; n++) { w[n] = exp(logw[n] - lse); assert(gsl_finite(w[n]) == 1); } } /* compute ess and perform resampling if necessary */ { double two_logw[N]; for (size_t n=0; n<N; n++) two_logw[n] = 2*logw[n]; double ess = exp(2*log_sum_exp(logw, N) - log_sum_exp(two_logw, N)); printf("# ess = %lf\n", ess); if (ess < .5*N) { printf("# resampling at iteration %zu\n", t); resample_move(r, logtheta, w, games_counter, wins); ones(w, N); zeros(logw, N); } } printf("\n"); } fprintf(stderr, "\n"); /* resample at the end */ printf("# resampling at iteration %zu\n", T); resample_move(r, logtheta, w, games_counter, wins); /* no need to reset the weights at this point but just to be safe... */ ones(w, N); zeros(logw, N); for(size_t n = 0; n < N; n++) { to_string(logtheta[n], K); printf("\n"); } /* cleanup */ free(logtheta); free(w); free(logw); free(wins); set_counter_free(games_counter); } int main(int argc, char *argv[]) { const gsl_rng_type *t; gsl_rng *r; gsl_rng_env_setup(); t = gsl_rng_default; r = gsl_rng_alloc(t); gsl_set_error_handler_off(); double *theta_star = malloc(K * sizeof(double)); /* read theta_star from a file */ if (argc==2) read_theta_star(argv[1], theta_star); else sample_theta_star(r, theta_star); printf("# K = %zu\n", K); printf("# N = %zu\n", N); printf("# T = %zu\n", T); printf("# L = %zu\n", L); printf("# theta_star = "); to_string(theta_star, K); printf("\n"); // perform simulation sim(r, theta_star); // cleanup free(theta_star); gsl_rng_free(r); exit(EXIT_SUCCESS); }
sum.c
#include <assert.h> #include <errno.h> #include <limits.h> #include <math.h> #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <string.h> enum { BASE = 10 }; enum { MSG_SIZE = 64, NUM_STR_SIZE = 24 }; enum { VALID_NUMBER, BAD_ARGC, BAD_NUMBER, TOO_BIG_NUMBER }; int get_n(long *n, int argc, char *argv[]); long get_max_supported(); long max_supported = 0; int main(int argc, char *argv[]) { max_supported = get_max_supported(); long N = 0; int res = get_n(&N, argc, argv); if (res != VALID_NUMBER) { const char *error_message = NULL; switch (res) { case BAD_NUMBER: error_message = "second argument number must be a natural number"; break; case TOO_BIG_NUMBER: { char buf[MSG_SIZE] = "only support numbers up to "; char max_num[NUM_STR_SIZE]; snprintf(max_num, NUM_STR_SIZE - 1, "%ld", max_supported); error_message = strcat(buf, max_num); break; } case BAD_ARGC: error_message = "one argument expected"; break; default: error_message = "unknown error"; break; } fprintf(stderr, "%s: fatal error: %s\n", argv[0], error_message); exit(EXIT_FAILURE); } unsigned long long sum = 0; #pragma omp parallel for reduction(+:sum) //schedule(static, N / omp_get_num_threads()) for (long i = 1; i <= N; i++) { sum += i; } printf("%llu\n", sum); } int get_n(long *n, int argc, char *argv[]) { if (argc == 2) { char *endptr; errno = 0; long num = strtol(argv[1], &endptr, BASE); if (((errno == ERANGE) && (num == LONG_MAX)) || (num > max_supported)) { return TOO_BIG_NUMBER; } if ((*endptr != '\0') || (errno != 0) || (num < 1)) { // natural number expected return BAD_NUMBER; } *n = num; return VALID_NUMBER; } return BAD_ARGC; } long get_max_supported() { unsigned long long max_sum = ULLONG_MAX; // calculate max elem using formula for the sum of arithmetic progression: // by solving equation (n * (n + 1)) / 2 = max_sum // which transforms to n ^ 2 + n - 2 * max_sum = 0 double D = 1 + 4.0 * 2.0 * max_sum; // NOLINT: discriminant formula long max_elem = (-1 + sqrt(D)) / 2.0; // NOLINT: root formula return max_elem; }
variable_utils.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Ruben Zorrilla // Vicente Mataix Ferrandiz // // #if !defined(KRATOS_VARIABLE_UTILS ) #define KRATOS_VARIABLE_UTILS /* System includes */ /* External includes */ /* Project includes */ #include "includes/define.h" #include "includes/model_part.h" #include "includes/checks.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class VariableUtils * @ingroup KratosCore * @brief This class implements a set of auxiliar, already parallelized, methods to * perform some common tasks related with the variable values and fixity. * @details The methods are exported to python in order to add this improvements to the python interface * @author Riccardo Rossi * @author Ruben Zorrilla * @author Vicente Mataix Ferrandiz */ class KRATOS_API(KRATOS_CORE) VariableUtils { public: ///@name Type Definitions ///@{ /// We create the Pointer related to VariableUtils KRATOS_CLASS_POINTER_DEFINITION(VariableUtils); /// The nodes container typedef ModelPart::NodesContainerType NodesContainerType; /// The conditions container typedef ModelPart::ConditionsContainerType ConditionsContainerType; /// The elements container typedef ModelPart::ElementsContainerType ElementsContainerType; /// A definition of the double variable typedef Variable< double > DoubleVarType; /// A definition of the component variable typedef VariableComponent< VectorComponentAdaptor<array_1d<double, 3> > > ComponentVarType; /// A definition of the array variable typedef Variable< array_1d<double, 3 > > ArrayVarType; ///@} ///@name Life Cycle ///@{ /** Constructor. */ /** Destructor. */ ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Copies the nodal value of a variable from an origin model * part nodes to the nodes in a destination model part. It is assumed that * both origin and destination model parts have the same number of nodes. * @param rVariable reference to the variable to be set * @param rOriginModelPart origin model part from where the values are retrieved * @param rDestinationModelPart destination model part to where the values are copied to * @param BuffStep buffer step */ template< class TVarType > void CopyModelPartNodalVar( const TVarType& rVariable, const ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart, const unsigned int BuffStep = 0){ const int n_orig_nodes = rOriginModelPart.NumberOfNodes(); const int n_dest_nodes = rDestinationModelPart.NumberOfNodes(); KRATOS_ERROR_IF_NOT(n_orig_nodes == n_dest_nodes) << "Origin and destination model parts have different number of nodes." << "\n\t- Number of origin nodes: " << n_orig_nodes << "\n\t- Number of destination nodes: " << n_dest_nodes << std::endl; #pragma omp parallel for for(int i_node = 0; i_node < n_orig_nodes; ++i_node){ auto it_dest_node = rDestinationModelPart.NodesBegin() + i_node; const auto &it_orig_node = rOriginModelPart.NodesBegin() + i_node; const auto &r_value = it_orig_node->GetSolutionStepValue(rVariable, BuffStep); it_dest_node->GetSolutionStepValue(rVariable, BuffStep) = r_value; } } /** * @brief Copies the elemental value of a variable from an origin model * part elements to the elements in a destination model part. It is assumed that * both origin and destination model parts have the same number of elements. * @param rVariable reference to the variable to be set * @param rOriginModelPart origin model part from where the values are retrieved * @param rDestinationModelPart destination model part to where the values are copied to * @param BuffStep buffer step */ template< class TVarType > void CopyModelPartElementalVar( const TVarType& rVariable, const ModelPart& rOriginModelPart, ModelPart& rDestinationModelPart){ const int n_orig_elems = rOriginModelPart.NumberOfElements(); const int n_dest_elems = rDestinationModelPart.NumberOfElements(); KRATOS_ERROR_IF_NOT(n_orig_elems == n_dest_elems) << "Origin and destination model parts have different number of elements." << "\n\t- Number of origin elements: " << n_orig_elems << "\n\t- Number of destination elements: " << n_dest_elems << std::endl; #pragma omp parallel for for(int i_elems = 0; i_elems < n_orig_elems; ++i_elems){ auto it_dest_elems = rDestinationModelPart.ElementsBegin() + i_elems; const auto &it_orig_elems = rOriginModelPart.ElementsBegin() + i_elems; const auto &r_value = it_orig_elems->GetValue(rVariable); it_dest_elems->SetValue(rVariable,r_value); } } /** * @brief Sets the nodal value of a scalar variable * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rNodes reference to the objective node set */ template< class TVarType > void SetScalarVar( const TVarType& rVariable, const double Value, NodesContainerType& rNodes ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->FastGetSolutionStepValue(rVariable) = Value; } KRATOS_CATCH("") } /** * @brief Sets the nodal value of a scalar variable (considering flag) * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rNodes reference to the objective node set * @param Flag The flag to be considered in the assignation * @param Check What is checked from the flag */ template< class TVarType > void SetScalarVarForFlag( const TVarType& rVariable, const double Value, NodesContainerType& rNodes, const Flags Flag, const bool Check = true ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; if (it_node->Is(Flag) == Check) it_node->FastGetSolutionStepValue(rVariable) = Value; } KRATOS_CATCH("") } /** * @brief Sets the nodal value of a vector variable * @param rVariable reference to the vector variable to be set * @param Value array containing the Value to be set * @param rNodes reference to the objective node set */ void SetVectorVar( const ArrayVarType& rVariable, const array_1d<double, 3 >& Value, NodesContainerType& rNodes ); /** * @brief Sets the nodal value of a vector variable (considering flag) * @param rVariable reference to the vector variable to be set * @param Value array containing the Value to be set * @param rNodes reference to the objective node set * @param Flag The flag to be considered in the assignation * @param Check What is checked from the flag */ void SetVectorVarForFlag( const ArrayVarType& rVariable, const array_1d<double, 3 >& Value, NodesContainerType& rNodes, const Flags Flag, const bool Check = true ); /** * @brief Sets the nodal value of a scalar variable * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rNodes reference to the objective node set */ template< class TType > void SetVariable( const Variable< TType >& rVariable, const TType& Value, NodesContainerType& rNodes ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->FastGetSolutionStepValue(rVariable) = Value; } KRATOS_CATCH("") } /** * @brief Sets the nodal value of a scalar variable (considering flag) * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rNodes reference to the objective node set * @param Flag The flag to be considered in the assignation * @param Check What is checked from the flag */ template< class TType > void SetVariableForFlag( const Variable< TType >& rVariable, const TType& Value, NodesContainerType& rNodes, const Flags Flag, const bool Check = true ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; if (it_node->Is(Flag) == Check) it_node->FastGetSolutionStepValue(rVariable) = Value; } KRATOS_CATCH("") } /** * @brief Sets the nodal value of a scalar variable non historical * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rNodes reference to the objective node set */ template< class TVarType > KRATOS_DEPRECATED_MESSAGE("Method deprecated, please use SetNonHistoricalVariable") void SetNonHistoricalScalarVar( const TVarType& rVariable, const double Value, NodesContainerType& rNodes ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->SetValue(rVariable, Value); } KRATOS_CATCH("") } /** * @brief Sets the nodal value of a vector non historical variable * @param rVariable reference to the vector variable to be set * @param Value array containing the Value to be set * @param rNodes reference to the objective node set */ KRATOS_DEPRECATED_MESSAGE("Method deprecated, please use SetNonHistoricalVariable") void SetNonHistoricalVectorVar( const ArrayVarType& rVariable, const array_1d<double, 3 >& Value, NodesContainerType& rNodes ); /** * @brief Sets the container value of any type of non historical variable * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rContainer Reference to the objective container */ template< class TType, class TContainerType, class TVarType = Variable< TType >> void SetNonHistoricalVariable( const TVarType& rVariable, const TType& Value, TContainerType& rContainer ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) { auto it_cont = rContainer.begin() + k; it_cont->SetValue(rVariable, Value); } KRATOS_CATCH("") } /** * @brief Sets the container value of any type of non historical variable (considering flag) * @param rVariable reference to the scalar variable to be set * @param Value Value to be set * @param rContainer Reference to the objective container * @param Flag The flag to be considered in the assignation * @param Check What is checked from the flag */ template< class TType, class TContainerType > void SetNonHistoricalVariableForFlag( const Variable< TType >& rVariable, const TType& Value, TContainerType& rContainer, const Flags Flag, const bool Check = true ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) { auto it_cont = rContainer.begin() + k; if (it_cont->Is(Flag) == Check) it_cont->SetValue(rVariable, Value); } KRATOS_CATCH("") } /** * @brief Clears the container data value container * @param rContainer Reference to the objective container */ template< class TContainerType> void ClearNonHistoricalData(TContainerType& rContainer) { KRATOS_TRY const auto it_cont_begin = rContainer.begin(); #pragma omp parallel for for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) { auto it_cont = it_cont_begin + k; it_cont->Data().Clear(); } KRATOS_CATCH("") } /** * @brief Sets a flag according to a given status over a given container * @param rFlag flag to be set * @param rFlagValue flag value to be set * @param rContainer Reference to the objective container */ template< class TContainerType > void SetFlag( const Flags& rFlag, const bool& rFlagValue, TContainerType& rContainer ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) { auto it_cont = rContainer.begin() + k; it_cont->Set(rFlag, rFlagValue); } KRATOS_CATCH("") } /** * @brief Flips a flag over a given container * @param rFlag flag to be set * @param rContainer Reference to the objective container */ template< class TContainerType > void FlipFlag( const Flags& rFlag, TContainerType& rContainer ) { KRATOS_TRY #pragma omp parallel for for (int k = 0; k< static_cast<int> (rContainer.size()); ++k) { auto it_cont = rContainer.begin() + k; it_cont->Flip(rFlag); } KRATOS_CATCH("") } /** * @brief Takes the value of a non-historical vector variable and sets it in other variable * @param OriginVariable reference to the origin vector variable * @param SavedVariable reference to the destination vector variable * @param rNodes reference to the objective node set */ void SaveVectorVar( const ArrayVarType& OriginVariable, const ArrayVarType& SavedVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of a non-historical scalar variable and sets it in other variable * @param OriginVariable reference to the origin scalar variable * @param SavedVariable reference to the destination scalar variable * @param rNodes reference to the objective node set */ void SaveScalarVar( const DoubleVarType& OriginVariable, const DoubleVarType& SavedVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of a non-historical vector variable and sets it in other non-historical variable * @param OriginVariable reference to the origin vector variable * @param SavedVariable reference to the destination vector variable * @param rNodes reference to the objective node set */ void SaveVectorNonHistoricalVar( const ArrayVarType& OriginVariable, const ArrayVarType& SavedVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of a non-historical scalar variable and sets it in other non-historical variable * @param OriginVariable reference to the origin scalar variable * @param SavedVariable reference to the destination scalar variable * @param rNodes reference to the objective node set */ void SaveScalarNonHistoricalVar( const DoubleVarType& OriginVariable, const DoubleVarType& SavedVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of an historical vector variable and sets it in other variable * @param OriginVariable reference to the origin vector variable * @param DestinationVariable reference to the destination vector variable * @param rNodes reference to the objective node set */ void CopyVectorVar( const ArrayVarType& OriginVariable, const ArrayVarType& DestinationVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of an historical component variable and sets it in other variable * @param OriginVariable reference to the origin component variable * @param DestinationVariable reference to the destination component variable * @param rNodes reference to the objective node set */ void CopyComponentVar( const ComponentVarType& OriginVariable, const ComponentVarType& DestinationVariable, NodesContainerType& rNodes ); /** * @brief Takes the value of an historical double variable and sets it in other variable * @param OriginVariable reference to the origin double variable * @param DestinationVariable reference to the destination double variable * @param rNodes reference to the objective node set */ void CopyScalarVar( const DoubleVarType& OriginVariable, const DoubleVarType& DestinationVariable, NodesContainerType& rNodes ); /** * @brief In a node set, sets a vector variable to zero * @param Variable reference to the vector variable to be set to 0 * @param rNodes reference to the objective node set */ void SetToZero_VectorVar( const ArrayVarType& Variable, NodesContainerType& rNodes ); /** * @brief In a node set, sets a double variable to zero * @param Variable reference to the double variable to be set to 0 * @param rNodes reference to the objective node set */ void SetToZero_ScalarVar( const DoubleVarType& Variable, NodesContainerType& rNodes ); /** * @brief Returns a list of nodes filtered using the given double variable and value * @param Variable reference to the double variable to be filtered * @param Value Filtering Value * @param rOriginNodes Reference to the objective node set * @return selected_nodes: List of filtered nodes */ NodesContainerType SelectNodeList( const DoubleVarType& Variable, const double Value, const NodesContainerType& rOriginNodes ); /** * @brief Checks if all the nodes of a node set has the specified variable * @param rVariable reference to a variable to be checked * @param rNodes reference to the nodes set to be checked * @return 0: if succeeds, return 0 */ template<class TVarType> int CheckVariableExists( const TVarType& rVariable, const NodesContainerType& rNodes ) { KRATOS_TRY for (auto& i_node : rNodes) KRATOS_CHECK_VARIABLE_IN_NODAL_DATA(rVariable, i_node); return 0; KRATOS_CATCH(""); } /** * @brief Fixes or frees a variable for all of the nodes in the list * @param rVar reference to the variable to be fixed or freed * @param IsFixed if true fixes, if false frees * @param rNodes reference to the nodes set to be frixed or freed */ template< class TVarType > void ApplyFixity( const TVarType& rVar, const bool IsFixed, NodesContainerType& rNodes ) { KRATOS_TRY if(rNodes.size() != 0) { // First we do a check CheckVariableExists(rVar, rNodes); if(IsFixed == true) { #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->pAddDof(rVar)->FixDof(); } } else { #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->pAddDof(rVar)->FreeDof(); } } } KRATOS_CATCH("") } /** * @brief Loops along a vector data to set its values to the nodes contained in a node set. * @note This function is suitable for scalar historical variables, since each * one of the values in the data vector is set to its correspondent node. Besides, * the values must be sorted as the nodes are (value i corresponds to node i). * @param rVar reference to the variable to be fixed or freed * @param rData rData vector. Note that its lenght must equal the number of nodes * @param rNodes reference to the nodes set to be set */ template< class TVarType > void ApplyVector( const TVarType& rVar, const Vector& rData, NodesContainerType& rNodes ) { KRATOS_TRY if(rNodes.size() != 0 && rNodes.size() == rData.size()) { // First we do a check CheckVariableExists(rVar, rNodes); #pragma omp parallel for for (int k = 0; k< static_cast<int> (rNodes.size()); ++k) { NodesContainerType::iterator it_node = rNodes.begin() + k; it_node->FastGetSolutionStepValue(rVar) = rData[k]; } } else KRATOS_ERROR << "There is a mismatch between the size of data array and the number of nodes "; KRATOS_CATCH("") } /** * @brief Returns the nodal value summation of a non-historical vector variable. * @param rVar reference to the vector variable to summed * @param rModelPart reference to the model part that contains the objective node set * @return sum_value: summation vector result */ array_1d<double, 3> SumNonHistoricalNodeVectorVariable( const ArrayVarType& rVar, const ModelPart& rModelPart ); /** * @brief Returns the nodal value summation of a non-historical scalar variable. * @param rVar reference to the scalar variable to be summed * @param rModelPart reference to the model part that contains the objective node set * @return sum_value: summation result */ template< class TVarType > double SumNonHistoricalNodeScalarVariable( const TVarType& rVar, const ModelPart& rModelPart ) { KRATOS_TRY double sum_value = 0.0; #pragma omp parallel for reduction(+:sum_value) for (int k = 0; k < static_cast<int>(rModelPart.GetCommunicator().LocalMesh().NumberOfNodes()); ++k) { const auto it_node = rModelPart.GetCommunicator().LocalMesh().NodesBegin() + k; sum_value += it_node->GetValue(rVar); } rModelPart.GetCommunicator().SumAll(sum_value); return sum_value; KRATOS_CATCH("") } /** * @brief Returns the nodal value summation of an historical vector variable. * @param rVar reference to the vector variable to summed * @param rModelPart reference to the model part that contains the objective node set * @return sum_value summation vector result */ array_1d<double, 3> SumHistoricalNodeVectorVariable( const ArrayVarType& rVar, const ModelPart& rModelPart, const unsigned int rBuffStep = 0 ); /** * @brief Returns the nodal value summation of an historical scalar variable. * @param rVar reference to the scalar variable to be summed * @param rModelPart reference to the model part that contains the objective node set * @return sum_value: summation result */ template< class TVarType > double SumHistoricalNodeScalarVariable( const TVarType& rVar, const ModelPart& rModelPart, const unsigned int rBuffStep = 0 ) { KRATOS_TRY double sum_value = 0.0; #pragma omp parallel for reduction(+:sum_value) for (int k = 0; k < static_cast<int>(rModelPart.GetCommunicator().LocalMesh().NumberOfNodes()); ++k) { const auto it_node = rModelPart.GetCommunicator().LocalMesh().NodesBegin() + k; sum_value += it_node->GetSolutionStepValue(rVar, rBuffStep); } rModelPart.GetCommunicator().SumAll(sum_value); return sum_value; KRATOS_CATCH("") } /** * @brief Returns the condition value summation of a historical vector variable * @param rVar reference to the vector variable to be summed * @param rModelPart reference to the model part that contains the objective condition set * @return sum_value: summation result */ array_1d<double, 3> SumConditionVectorVariable( const ArrayVarType& rVar, const ModelPart& rModelPart ); /** * @brief Returns the condition value summation of a historical scalar variable * @param rVar reference to the scalar variable to be summed * @param rModelPart reference to the model part that contains the objective condition set * @return sum_value: summation result */ template< class TVarType > double SumConditionScalarVariable( const TVarType& rVar, const ModelPart& rModelPart ) { KRATOS_TRY double sum_value = 0.0; #pragma omp parallel for reduction(+:sum_value) for (int k = 0; k < static_cast<int>(rModelPart.GetCommunicator().LocalMesh().NumberOfConditions()); ++k) { const auto it_cond = rModelPart.GetCommunicator().LocalMesh().ConditionsBegin() + k; sum_value += it_cond->GetValue(rVar); } rModelPart.GetCommunicator().SumAll(sum_value); return sum_value; KRATOS_CATCH("") } /** * @brief Returns the element value summation of a historical vector variable * @param rVar reference to the vector variable to be summed * @param rModelPart reference to the model part that contains the objective element set * @return sum_value: summation result */ array_1d<double, 3> SumElementVectorVariable( const ArrayVarType& rVar, const ModelPart& rModelPart ); /** * @brief Returns the element value summation of a historical scalar variable * @param rVar reference to the scalar variable to be summed * @param rModelPart reference to the model part that contains the objective element set * @return sum_value: summation result */ template< class TVarType > double SumElementScalarVariable( const TVarType& rVar, const ModelPart& rModelPart ) { KRATOS_TRY double sum_value = 0.0; #pragma omp parallel for reduction(+:sum_value) for (int k = 0; k < static_cast<int>(rModelPart.GetCommunicator().LocalMesh().NumberOfElements()); ++k) { const auto it_elem = rModelPart.GetCommunicator().LocalMesh().ElementsBegin() + k; sum_value += it_elem->GetValue(rVar); } rModelPart.GetCommunicator().SumAll(sum_value); return sum_value; KRATOS_CATCH("") } /** * @brief This function add dofs to the nodes in a model part. It is useful since addition is done in parallel * @param rVar The variable to be added as DoF * @param rModelPart reference to the model part that contains the objective element set */ template< class TVarType > void AddDof( const TVarType& rVar, ModelPart& rModelPart ) { KRATOS_TRY // First we do a chek KRATOS_CHECK_VARIABLE_KEY(rVar) if(rModelPart.NumberOfNodes() != 0) KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rVar)) << "ERROR:: Variable : " << rVar << "not included in the Solution step data "; #pragma omp parallel for for (int k = 0; k < static_cast<int>(rModelPart.NumberOfNodes()); ++k) { auto it_node = rModelPart.NodesBegin() + k; it_node->AddDof(rVar); } KRATOS_CATCH("") } /** * @brief This function add dofs to the nodes in a model part. It is useful since addition is done in parallel * @param rVar The variable to be added as DoF * @param rReactionVar The corresponding reaction to the added DoF * @param rModelPart reference to the model part that contains the objective element set */ template< class TVarType > void AddDofWithReaction( const TVarType& rVar, const TVarType& rReactionVar, ModelPart& rModelPart ) { KRATOS_TRY KRATOS_CHECK_VARIABLE_KEY(rVar) KRATOS_CHECK_VARIABLE_KEY(rReactionVar) if(rModelPart.NumberOfNodes() != 0) { KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rVar)) << "ERROR:: DoF Variable : " << rVar << "not included in the Soluttion step data "; KRATOS_ERROR_IF_NOT(rModelPart.NodesBegin()->SolutionStepsDataHas(rReactionVar)) << "ERROR:: Reaction Variable : " << rReactionVar << "not included in the Soluttion step data "; } // If in debug we do a check for all nodes #ifdef KRATOS_DEBUG CheckVariableExists(rVar, rModelPart.Nodes()); CheckVariableExists(rReactionVar, rModelPart.Nodes()); #endif #pragma omp parallel for for (int k = 0; k < static_cast<int>(rModelPart.NumberOfNodes()); ++k) { auto it_node = rModelPart.NodesBegin() + k; it_node->AddDof(rVar,rReactionVar); } KRATOS_CATCH("") } /** * @brief This method checks the variable keys * @return True if all the keys are correct */ bool CheckVariableKeys(); /** * @brief This method checks the dofs * @param rModelPart reference to the model part that contains the objective element set * @return True if all the DoFs are correct */ bool CheckDofs(ModelPart& rModelPart); /** * @brief This method updates the current nodal coordinates back to the initial coordinates * @param rNodes the nodes to be updated */ void UpdateCurrentToInitialConfiguration(const ModelPart::NodesContainerType& rNodes); /** * @brief This method updates the initial nodal coordinates to the current coordinates * @param rNodes the nodes to be updated */ void UpdateInitialToCurrentConfiguration(const ModelPart::NodesContainerType& rNodes); ///@} ///@name Acces ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Friends ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ /** * @brief This is auxiliar method to check the keys * @return True if all the keys are OK */ template< class TVarType > bool CheckVariableKeysHelper() { KRATOS_TRY for (const auto& var : KratosComponents< TVarType >::GetComponents()) { if (var.first == "NONE" || var.first == "") std::cout << " var first is NONE or empty " << var.first << var.second << std::endl; if (var.second->Name() == "NONE" || var.second->Name() == "") std::cout << var.first << var.second << std::endl; if (var.first != var.second->Name()) //name of registration does not correspond to the var name std::cout << "Registration Name = " << var.first << " Variable Name = " << std::endl; KRATOS_ERROR_IF((var.second)->Key() == 0) << (var.second)->Name() << " Key is 0." << std::endl \ << "Check that Kratos variables have been correctly registered and all required applications have been imported." << std::endl; } return true; KRATOS_CATCH("") } ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Acces ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; /* Class VariableUtils */ ///@} ///@name Type Definitions ///@{ ///@} } /* namespace Kratos.*/ #endif /* KRATOS_VARIABLE_UTILS defined */
requantize_relu_pack8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void requantize_relu_pack8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& scale_in_data, const Mat& scale_out_data, const Mat& bias_data, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int size = w * h; int scale_in_data_size = scale_in_data.w; int scale_out_data_size = scale_out_data.w; int bias_data_size = bias_data.w; // int8(relu(v * scale_in) * scale_out) // int8_relu(v * (scale_in * scale_out)) // int8(relu(v * scale_in + bias) * scale_out) // int8_relu(v * (scale_in * scale_out) + (bias * scale_out)) if (bias_data_size == 0) { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const int* intptr = bottom_blob.channel(q); signed char* ptr = top_blob.channel(q); float32x4_t _scale_in0 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8); float32x4_t _scale_in1 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8 + 4); float32x4_t _scale_out0 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8); float32x4_t _scale_out1 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8 + 4); float32x4_t _scale0 = vmulq_f32(_scale_in0, _scale_out0); float32x4_t _scale1 = vmulq_f32(_scale_in1, _scale_out1); int i = 0; #if __aarch64__ for (; i + 3 < size; i += 4) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); float32x4_t _v2 = vcvtq_f32_s32(vld1q_s32(intptr + 8)); float32x4_t _v3 = vcvtq_f32_s32(vld1q_s32(intptr + 12)); float32x4_t _v4 = vcvtq_f32_s32(vld1q_s32(intptr + 16)); float32x4_t _v5 = vcvtq_f32_s32(vld1q_s32(intptr + 20)); float32x4_t _v6 = vcvtq_f32_s32(vld1q_s32(intptr + 24)); float32x4_t _v7 = vcvtq_f32_s32(vld1q_s32(intptr + 28)); _v0 = vmulq_f32(_v0, _scale0); _v1 = vmulq_f32(_v1, _scale1); _v2 = vmulq_f32(_v2, _scale0); _v3 = vmulq_f32(_v3, _scale1); _v4 = vmulq_f32(_v4, _scale0); _v5 = vmulq_f32(_v5, _scale1); _v6 = vmulq_f32(_v6, _scale0); _v7 = vmulq_f32(_v7, _scale1); vst1_s8(ptr, float2int8relu(_v0, _v1)); vst1_s8(ptr + 8, float2int8relu(_v2, _v3)); vst1_s8(ptr + 16, float2int8relu(_v4, _v5)); vst1_s8(ptr + 24, float2int8relu(_v6, _v7)); intptr += 32; ptr += 32; } #endif // __aarch64__ for (; i + 1 < size; i += 2) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); float32x4_t _v2 = vcvtq_f32_s32(vld1q_s32(intptr + 8)); float32x4_t _v3 = vcvtq_f32_s32(vld1q_s32(intptr + 12)); _v0 = vmulq_f32(_v0, _scale0); _v1 = vmulq_f32(_v1, _scale1); _v2 = vmulq_f32(_v2, _scale0); _v3 = vmulq_f32(_v3, _scale1); vst1_s8(ptr, float2int8relu(_v0, _v1)); vst1_s8(ptr + 8, float2int8relu(_v2, _v3)); intptr += 16; ptr += 16; } for (; i < size; i++) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); _v0 = vmulq_f32(_v0, _scale0); _v1 = vmulq_f32(_v1, _scale1); vst1_s8(ptr, float2int8relu(_v0, _v1)); intptr += 8; ptr += 8; } } } else { #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < channels; q++) { const int* intptr = bottom_blob.channel(q); signed char* ptr = top_blob.channel(q); float32x4_t _scale_in0 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8); float32x4_t _scale_in1 = scale_in_data_size == 1 ? vdupq_n_f32(scale_in_data[0]) : vld1q_f32((const float*)scale_in_data + q * 8 + 4); float32x4_t _scale_out0 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8); float32x4_t _scale_out1 = scale_out_data_size == 1 ? vdupq_n_f32(scale_out_data[0]) : vld1q_f32((const float*)scale_out_data + q * 8 + 4); float32x4_t _bias0 = bias_data_size == 1 ? vdupq_n_f32(bias_data[0]) : vld1q_f32((const float*)bias_data + q * 8); float32x4_t _bias1 = bias_data_size == 1 ? vdupq_n_f32(bias_data[0]) : vld1q_f32((const float*)bias_data + q * 8 + 4); float32x4_t _scale0 = vmulq_f32(_scale_in0, _scale_out0); float32x4_t _scale1 = vmulq_f32(_scale_in1, _scale_out1); _bias0 = vmulq_f32(_bias0, _scale_out0); _bias1 = vmulq_f32(_bias1, _scale_out1); int i = 0; #if __aarch64__ for (; i + 3 < size; i += 4) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); float32x4_t _v2 = vcvtq_f32_s32(vld1q_s32(intptr + 8)); float32x4_t _v3 = vcvtq_f32_s32(vld1q_s32(intptr + 12)); float32x4_t _v4 = vcvtq_f32_s32(vld1q_s32(intptr + 16)); float32x4_t _v5 = vcvtq_f32_s32(vld1q_s32(intptr + 20)); float32x4_t _v6 = vcvtq_f32_s32(vld1q_s32(intptr + 24)); float32x4_t _v7 = vcvtq_f32_s32(vld1q_s32(intptr + 28)); _v0 = vfmaq_f32(_bias0, _v0, _scale0); _v1 = vfmaq_f32(_bias1, _v1, _scale1); _v2 = vfmaq_f32(_bias0, _v2, _scale0); _v3 = vfmaq_f32(_bias1, _v3, _scale1); _v4 = vfmaq_f32(_bias0, _v4, _scale0); _v5 = vfmaq_f32(_bias1, _v5, _scale1); _v6 = vfmaq_f32(_bias0, _v6, _scale0); _v7 = vfmaq_f32(_bias1, _v7, _scale1); vst1_s8(ptr, float2int8relu(_v0, _v1)); vst1_s8(ptr + 8, float2int8relu(_v2, _v3)); vst1_s8(ptr + 16, float2int8relu(_v4, _v5)); vst1_s8(ptr + 24, float2int8relu(_v6, _v7)); intptr += 32; ptr += 32; } #endif // __aarch64__ for (; i + 1 < size; i += 2) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); float32x4_t _v2 = vcvtq_f32_s32(vld1q_s32(intptr + 8)); float32x4_t _v3 = vcvtq_f32_s32(vld1q_s32(intptr + 12)); #if __aarch64__ _v0 = vfmaq_f32(_bias0, _v0, _scale0); _v1 = vfmaq_f32(_bias1, _v1, _scale1); _v2 = vfmaq_f32(_bias0, _v2, _scale0); _v3 = vfmaq_f32(_bias1, _v3, _scale1); #else // __aarch64__ _v0 = vmlaq_f32(_bias0, _v0, _scale0); _v1 = vmlaq_f32(_bias1, _v1, _scale1); _v2 = vmlaq_f32(_bias0, _v2, _scale0); _v3 = vmlaq_f32(_bias1, _v3, _scale1); #endif // __aarch64__ vst1_s8(ptr, float2int8relu(_v0, _v1)); vst1_s8(ptr + 8, float2int8relu(_v2, _v3)); intptr += 16; ptr += 16; } for (; i < size; i++) { float32x4_t _v0 = vcvtq_f32_s32(vld1q_s32(intptr)); float32x4_t _v1 = vcvtq_f32_s32(vld1q_s32(intptr + 4)); #if __aarch64__ _v0 = vfmaq_f32(_bias0, _v0, _scale0); _v1 = vfmaq_f32(_bias1, _v1, _scale1); #else // __aarch64__ _v0 = vmlaq_f32(_bias0, _v0, _scale0); _v1 = vmlaq_f32(_bias1, _v1, _scale1); #endif // __aarch64__ vst1_s8(ptr, float2int8relu(_v0, _v1)); intptr += 8; ptr += 8; } } } }
main.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> // Simulation Parameters #define Re 100 // Reynolds number #define N 50 // N #define UMAX 0.1 // lid velocity #define SAVETXT 1 // Controls whether to save a text file output #define THRESH 1E-12 // Defines convergence of dp/dt #define METHOD 1 // 0 = BGK, 1 = TRT #define GAMMA 1.0 // Preconditioning Coefficent. #define DIAG 0 // Simulate diagonally driven lid #define THREADS 16 // Number of threads to use // Global Constants #define MAXITER 1E8 #define NU ((UMAX) * (double) (N+1.0) / (double) (Re)) // Kinematic viscosity #define TAU ((NU) * (3.0 / (double) GAMMA) + 0.5) // Tau #define OMEGA (1.0 / (double) (TAU) ) // Relaxation constant #define MAGIC (0.25) // TRT magic parameter #define OMEGAm (1.0 / (0.5 + (MAGIC / ((1.0 / OMEGA) - 0.5)))) // TRT free parameter omega- #define RHO0 1.0 // Initial density #define N2 ((N) * (N)) #define N3 ((N2) * (N)) #define Q 19 #define NQ ((N3) * (Q)) #define Nm1 ((N) - 1) #define OmOMEGA (1.0 - (OMEGA)) #define w0 (1.0/3.0) #define w1 (1.0/18.0) #define w2 (1.0/36.0) const double w[Q] = {w0,w1,w1,w1,w1,w1,w1,w2,w2,w2,w2,w2,w2,w2,w2,w2,w2,w2,w2}; const int c[Q][3] = {{0,0,0}, {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}, {1,1,0},{-1,-1,0}, {1,0,1},{-1,0,-1},{0,1,1},{0,-1,-1},{1,-1,0},{-1,1,0},{1,0,-1},{-1,0,1},{0,1,-1},{0,-1,1}}; const double gammainv = 1.0 / GAMMA; const double sixth = 1.0 / 6.0; const double third = 1.0 / 3.0; const int skip = 500; // Macros #define P2(x) ((x) * (x)) // x^2 #define LU3(i,j,k) (((k) * (N2)) + ((j) * (N)) + (i)) // Look-up function, 3d, N x N x anything #define LU4(i,j,k,q) (((q) * (N3)) + ((k) * (N2)) + ((j) * (N)) + (i)) // Look-up function, 4d, N x N x N x anything // Function Prototypes double* malloc_vectord (int n1); void free_vectord (double *a); void zeros (double *array, int n); void linspace (double *array, double start, double stop, int num); void datwrite (double *x, double *y, double *z, char name3[], double *value3, char name4[], double *value4,char name5[], double *value5); double diff (double *array1, double *array2, int n); void checkfeq (double feq); void macrovars (double* F); double calcfeq (int c1, int c2, int c3, double w, double u1, double u2, double u3, double rho, double U2); void allocate (void); void initialize (void); void initOMP (void); void freemem (void); void swap (double **a, double **b); void calcvmag (void); void macrocollideandstream (void); void HechtBC (double *fstar); // Global Variables double *fstar,*fp,*u1,*u2,*u3,*rho,*x,*f1,*f2,*vmag; double df,df0,ulid,vlid,wlid; char filename[80]; int main(void) { allocate(); // Allocate Memory initialize(); // Initialize variables printf("Re =\t%d\n", Re); printf("Re_g =\t%.3e\n", 3.0*UMAX / (TAU - 0.5)); printf("U =\t%.3e\n", UMAX); printf("N =\t%d\n", N); printf("tau =\t%.3e\n", TAU); printf("nu =\t%.3e\n", NU); printf("M =\t%.3e\n", UMAX * sqrt(3)); if (GAMMA != 1.0) printf("M* =\t%.3e\n", UMAX * sqrt(3)/sqrt(GAMMA)); // Main Loop double start,stop; // First iteration macrocollideandstream(); HechtBC(f2); df0 = diff(f2, f1, NQ); printf("\nIteration 0:\n"); printf("df:\t%.3e\n",df0); df0 = 1.0 / df0; swap(&f1,&f2); // Rest of iterations start = omp_get_wtime(); for (int t = 1; t < MAXITER; t++) { macrocollideandstream(); // Calculate macro variables, collide, stream HechtBC(f2); // Apply Hecht NEBB boundary condition // Convergence if (t % skip == 0) { df = diff(f2, f1, NQ) * df0; printf("\nIteration %d:\n", t); printf("df/df0:\t%.3e\n", df); stop = omp_get_wtime() - start; printf("Time:\t%.3e s\n", stop); printf("LUPS:\t%.3e s\n", N3 * skip / stop); start = omp_get_wtime(); if (df < THRESH) { break; } } swap(&f1, &f2); } // Output to text file datwrite(x,x,x,"u",u1,"v",u2,"w",u3); // Free Memory freemem(); return 0; } // Allocate Memory void allocate(void){ initOMP(); fstar = malloc_vectord(NQ); fp = malloc_vectord(NQ); f1 = malloc_vectord(NQ); f2 = malloc_vectord(NQ); u1 = malloc_vectord(N3); u2 = malloc_vectord(N3); u3 = malloc_vectord(N3); rho = malloc_vectord(N3); x = malloc_vectord(N); vmag = malloc_vectord(N3); } // Free Memory void freemem(void){ free_vectord(fstar); free_vectord(fp); free_vectord(f1); free_vectord(f2); free_vectord(u1); free_vectord(u2); free_vectord(u3); free_vectord(rho); free_vectord(x); } // Calculate Equilibrium Distribution double calcfeq(int c1, int c2, int c3, double w, double u1, double u2, double u3, double rho, double U2){ double cdotu,feq; cdotu = c1 * u1 + c2 * u2 + c3 * u3; feq = w * rho * (1.0 + 3.0 * cdotu + (4.5 * P2(cdotu) - 1.5 * U2) * gammainv); checkfeq(feq); return feq; } // Initialize Variables void initialize(void){ double feq,U2; sprintf(filename,"Solution_n=%dRe=%d_DIAG=%d_%dRT_M=%.3f.dat",N,Re,DIAG,METHOD+1,MAGIC); linspace(x,0,Nm1,N); zeros(u1,N3); zeros(u2,N3); zeros(u3,N3); for (int i = 0; i < N3; i++){ rho[i] = RHO0; } if (DIAG == 1) { ulid = (double) UMAX / sqrt(2); wlid = ulid; } else { ulid = UMAX; wlid = 0.0; } vlid = 0.0; #pragma omp parallel for private(feq,U2) collapse(3) for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ for (int k = 0; k < N; k++) { U2 = P2(u1[LU3(i, j, k)])+P2(u2[LU3(i, j, k)])+P2(u3[LU3(i, j, k)]); for (int q = 0; q < Q; q++) { feq = calcfeq(c[q][0], c[q][1], c[q][2], w[q], u1[LU3(i, j, k)], u2[LU3(i, j, k)], u3[LU3(i, j, k)], rho[LU3(i, j, k)],U2); fp[LU4(i, j, k, q)] = feq; f1[LU4(i, j, k, q)] = feq; f2[LU4(i, j, k, q)] = feq; } } } } } // Initialize OpenMP void initOMP(void){ printf("Threads used:\t%d\n", THREADS); omp_set_num_threads(THREADS); } // Calculate macro variables, collide, and stream void macrocollideandstream(void){ if (METHOD == 0){ double feq,rhotemp,utemp,vtemp,wtemp,ftemp,U2; int inew,jnew,knew; #pragma omp parallel for private(feq,inew,jnew,knew,rhotemp,utemp,vtemp,wtemp,ftemp,U2) collapse(3) for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ for (int k = 0; k < N; k++){ // Macro variables rhotemp = 0.0; utemp = 0.0; vtemp = 0.0; wtemp = 0.0; for (int q = 0; q < Q; q++) { ftemp = f1[LU4(i, j, k, q)]; rhotemp += ftemp; utemp += c[q][0] * ftemp; vtemp += c[q][1] * ftemp; wtemp += c[q][2] * ftemp; } rho[LU3(i, j, k)] = rhotemp; utemp /= rhotemp; vtemp /= rhotemp; wtemp /= rhotemp; U2 = P2(utemp)+P2(vtemp)+P2(wtemp); for (int q = 0; q < Q; q++) { // Calculate feq feq = calcfeq(c[q][0], c[q][1], c[q][2], w[q], utemp, vtemp, wtemp, rhotemp,U2); // Collision fstar[LU4(i, j, k, q)] = OmOMEGA * f1[LU4(i, j, k, q)] + OMEGA * feq; // Stream inew = i + c[q][0]; jnew = j + c[q][1]; knew = k + c[q][2]; if (inew < N && jnew < N && knew < N && inew >= 0 && jnew >= 0 && knew >= 0) f2[LU4(inew, jnew, knew, q)] = fstar[LU4(i, j, k, q)]; } } } } } if (METHOD == 1){ double fplus,fminus,feqplus,feqminus,rhotemp,rhotempinv,utemp,vtemp,wtemp,U2,fstartemp1,fstartemp2,feq1,feq2; int inew,jnew,knew,oppq; #pragma omp parallel for private(fplus,fminus,feqplus,feqminus,inew,jnew,knew,utemp,vtemp,wtemp,rhotemp,rhotempinv,oppq,U2,fstartemp1,fstartemp2,feq1,feq2) collapse(3) for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ for (int k = 0; k < N; k++){ rhotemp = f1[LU4(i, j, k, 0)] + f1[LU4(i, j, k, 1)] + f1[LU4(i, j, k, 2)] + f1[LU4(i, j, k, 3)] + f1[LU4(i, j, k, 4)] + f1[LU4(i, j, k, 5)] + f1[LU4(i, j, k, 6)] + f1[LU4(i, j, k, 7)] + f1[LU4(i, j, k, 8)] + f1[LU4(i, j, k, 9)] + f1[LU4(i, j, k, 10)] + f1[LU4(i, j, k, 11)] + f1[LU4(i, j, k, 12)] + f1[LU4(i, j, k,13)] + f1[LU4(i, j, k, 14)] + f1[LU4(i, j, k, 15)] + f1[LU4(i, j, k, 16)] + f1[LU4(i, j, k, 17)] + f1[LU4(i, j, k, 18)]; rhotempinv = 1.0 / rhotemp; utemp = (c[1][0]*f1[LU4(i, j, k, 1)] + c[2][0]*f1[LU4(i, j, k, 2)] + c[7][0]*f1[LU4(i, j, k, 7)] + c[8][0]*f1[LU4(i, j, k, 8)] + c[9][0]*f1[LU4(i, j, k, 9)] + c[10][0]*f1[LU4(i, j, k, 10)] + c[13][0]*f1[LU4(i, j, k,13)] + c[14][0]*f1[LU4(i, j, k, 14)] + c[15][0]*f1[LU4(i, j, k, 15)] + c[16][0]*f1[LU4(i, j, k, 16)]) * rhotempinv; vtemp = (c[3][1]*f1[LU4(i, j, k, 3)] + c[4][1]*f1[LU4(i, j, k, 4)] + c[7][1]*f1[LU4(i, j, k, 7)] + c[8][1]*f1[LU4(i, j, k, 8)] + c[11][1]*f1[LU4(i, j, k, 11)] + c[12][1]*f1[LU4(i, j, k, 12)] + c[13][1]*f1[LU4(i, j, k,13)] + c[14][1]*f1[LU4(i, j, k, 14)] + c[17][1]*f1[LU4(i, j, k, 17)] + c[18][1]*f1[LU4(i, j, k, 18)])* rhotempinv; wtemp = (c[5][2]*f1[LU4(i, j, k, 5)] + c[6][2]*f1[LU4(i, j, k, 6)] + c[9][2]*f1[LU4(i, j, k, 9)] + c[10][2]*f1[LU4(i, j, k, 10)] + c[11][2]*f1[LU4(i, j, k, 11)] + c[12][2]*f1[LU4(i, j, k, 12)] + c[15][2]*f1[LU4(i, j, k, 15)] + c[16][2]*f1[LU4(i, j, k, 16)] + c[17][2]*f1[LU4(i, j, k, 17)] + c[18][2]*f1[LU4(i, j, k, 18)])* rhotempinv; // Calculate feq U2 = P2(utemp)+P2(vtemp)+P2(wtemp); // TRT Collide f2[LU4(i, j, k, 0)] = f1[LU4(i, j, k, 0)] - OMEGA * (f1[LU4(i, j, k, 0)] - calcfeq(c[0][0], c[0][1], c[0][2], w[0], utemp, vtemp, wtemp, rhotemp, U2)); for (int q = 1; q < Q; q+=2) { oppq = q+1; feq1 = calcfeq(c[q][0], c[q][1], c[q][2], w[q], utemp, vtemp, wtemp, rhotemp, U2); feq2 = calcfeq(c[oppq][0], c[oppq][1], c[oppq][2], w[oppq], utemp, vtemp, wtemp, rhotemp, U2); fplus = 0.5 * (f1[LU4(i,j,k,q)] + f1[LU4(i,j,k,oppq)]); fminus = 0.5 * (f1[LU4(i,j,k,q)] - f1[LU4(i,j,k,oppq)]); feqplus = 0.5 * (feq1 + feq2); feqminus = 0.5 * (feq1 - feq2); fplus = OMEGA * (fplus - feqplus); fminus = OMEGAm * (fminus - feqminus); fstartemp1 = f1[LU4(i, j, k, q)] - fplus - fminus; fstartemp2 = f1[LU4(i, j, k, oppq)] - fplus + fminus; // Stream inew = i + c[q][0]; jnew = j + c[q][1]; knew = k + c[q][2]; if (inew < N && jnew < N && knew < N && inew >= 0 && jnew >= 0 && knew >= 0) f2[LU4(inew, jnew, knew, q)] = fstartemp1; inew = i + c[oppq][0]; jnew = j + c[oppq][1]; knew = k + c[oppq][2]; if (inew < N && jnew < N && knew < N && inew >= 0 && jnew >= 0 && knew >= 0) f2[LU4(inew, jnew, knew, oppq)] = fstartemp2; } } } } } } // Returns evenly spaced numbers over a specified interval void linspace(double *array, double start, double stop, int num){ #pragma omp parallel for for (int i = 0; i < num; i++){ array[i] = start + ((double) i) * (stop - start) / (double) (num-1); } } // Allocates memory for 1D array of doubles double *malloc_vectord(int n1) { if (n1 <= 0) // Checks for invalid inputs printf("Invalid input into malloc_vectord\n"); else { double *mat = malloc(n1 * sizeof(double)); if (mat == NULL) { printf("Error allocating memory!\n"); exit(1); } return mat; } exit(1); } // Frees memory for 1D double array void free_vectord(double *a) { if (a == NULL) printf("Error: Null input in free_vectord"); free((void *)a); } // Assigns zeros to a vector void zeros(double *array, int n){ #pragma omp parallel for for (int i = 0; i < n; i++){ array[i] = 0.0; } } // Writes Tecplot file void datwrite(double *x, double *y, double *z, char name3[], double *value3, char name4[], double *value4, char name5[], double *value5){ if (SAVETXT==1){ macrovars(f2); calcvmag(); FILE *fstar = fopen(filename,"w"); if (fstar == NULL) { printf("Error opening file!\n"); exit(1); } fprintf(fstar, "TITLE=\"%s\" VARIABLES=\"x\", \"y\", \"z\", \"%s\", \"%s\", \"%s\", \"vmag\" ZONE T=\"%s\" I=%d J=%d K=%d F=POINT\n", filename, name3, name4, name5, filename,N,N,N); for (int i = 0; i < N; i++) { for (int j = 0; j < N ; j++) { for (int k = 0; k < N; k++) { fprintf(fstar, "%.10f, %.10f, %.10f, %.10f, %.10f, %.10f, %.10f\n", x[i], y[j], z[k], value3[LU3(i, j, k)],value4[LU3(i, j, k)],value5[LU3(i, j, k)],vmag[LU3(i, j, k)]); } } } fclose(fstar); } } // Non-equilibrium bounce back, Hecht, Harting 2010 void HechtBC(double *fstar){ double rhotemp,Nzx,Nzy,Nxy,Nxz,Nyx,Nyz,temp, vfrac = 1.0 / (vlid + 1.0); #pragma omp parallel for collapse(2) private(rhotemp,Nzx,Nzy,Nxy,Nxz,Nyx,Nyz) for (int i = 1; i < Nm1; i++) { for (int j = 1; j < Nm1; j++) { // z=0 f2[LU4(i,j,0,5)] = f2[LU4(i,j,0,6)]; Nzx = 0.5*((f2[LU4(i,j,0,1)]+f2[LU4(i,j,0,7)]+f2[LU4(i,j,0,13)]) - (f2[LU4(i,j,0,2)]+f2[LU4(i,j,0,14)]+f2[LU4(i,j,0,8)])); Nzy = 0.5*((f2[LU4(i,j,0,3)]+f2[LU4(i,j,0,7)]+f2[LU4(i,j,0,14)]) - (f2[LU4(i,j,0,4)]+f2[LU4(i,j,0,13)]+f2[LU4(i,j,0,8)])); f2[LU4(i,j,0,9)] = f2[LU4(i,j,0,10)] - Nzx; f2[LU4(i,j,0,16)] = f2[LU4(i,j,0,15)] + Nzx; f2[LU4(i,j,0,11)] = f2[LU4(i,j,0,12)] - Nzy; f2[LU4(i,j,0,18)] = f2[LU4(i,j,0,17)] + Nzy; // z = Nm1 f2[LU4(i,j,Nm1,6)] = f2[LU4(i,j,Nm1,5)]; Nzx = 0.5*((f2[LU4(i,j,Nm1,1)]+f2[LU4(i,j,Nm1,7)]+f2[LU4(i,j,Nm1,13)]) - (f2[LU4(i,j,Nm1,2)]+f2[LU4(i,j,Nm1,14)]+f2[LU4(i,j,Nm1,8)])); Nzy = 0.5*((f2[LU4(i,j,Nm1,3)]+f2[LU4(i,j,Nm1,7)]+f2[LU4(i,j,Nm1,14)]) - (f2[LU4(i,j,Nm1,4)]+f2[LU4(i,j,Nm1,13)]+f2[LU4(i,j,Nm1,8)])); f2[LU4(i,j,Nm1,10)] = f2[LU4(i,j,Nm1,9)] + Nzx; f2[LU4(i,j,Nm1,15)] = f2[LU4(i,j,Nm1,16)] - Nzx; f2[LU4(i,j,Nm1,12)] = f2[LU4(i,j,Nm1,11)] + Nzy; f2[LU4(i,j,Nm1,17)] = f2[LU4(i,j,Nm1,18)] - Nzy; // x = 0 f2[LU4(0,i,j,1)] = f2[LU4(0,i,j,2)]; Nxy = 0.5*((f2[LU4(0,i,j,3)]+f2[LU4(0,i,j,11)]+f2[LU4(0,i,j,17)]) - (f2[LU4(0,i,j,4)]+f2[LU4(0,i,j,18)]+f2[LU4(0,i,j,12)])); Nxz = 0.5*((f2[LU4(0,i,j,5)]+f2[LU4(0,i,j,14)]+f2[LU4(0,i,j,11)]) - (f2[LU4(0,i,j,6)]+f2[LU4(0,i,j,17)]+f2[LU4(0,i,j,12)])); f2[LU4(0,i,j,13)] = f2[LU4(0,i,j,14)] + Nxy; f2[LU4(0,i,j,7)] = f2[LU4(0,i,j,8)] - Nxy; f2[LU4(0,i,j,9)] = f2[LU4(0,i,j,10)] - Nxz; f2[LU4(0,i,j,15)] = f2[LU4(0,i,j,16)] + Nxz; // x = Nm1 f2[LU4(Nm1,i,j,2)] = f2[LU4(Nm1,i,j,1)]; Nxy = 0.5*((f2[LU4(Nm1,i,j,3)]+f2[LU4(Nm1,i,j,11)]+f2[LU4(Nm1,i,j,17)]) - (f2[LU4(Nm1,i,j,4)]+f2[LU4(Nm1,i,j,18)]+f2[LU4(Nm1,i,j,12)])); Nxz = 0.5*((f2[LU4(Nm1,i,j,5)]+f2[LU4(Nm1,i,j,14)]+f2[LU4(Nm1,i,j,11)]) - (f2[LU4(Nm1,i,j,6)]+f2[LU4(Nm1,i,j,17)]+f2[LU4(Nm1,i,j,12)])); f2[LU4(Nm1,i,j,14)] = f2[LU4(Nm1,i,j,13)] - Nxy; f2[LU4(Nm1,i,j,8)] = f2[LU4(Nm1,i,j,7)] + Nxy; f2[LU4(Nm1,i,j,10)] = f2[LU4(Nm1,i,j,9)] + Nxz; f2[LU4(Nm1,i,j,16)] = f2[LU4(Nm1,i,j,15)] - Nxz; // y = 0 f2[LU4(i,0,j,3)] = f2[LU4(i,0,j,4)]; Nyx = 0.5*((f2[LU4(i,0,j,1)]+f2[LU4(i,0,j,9)]+f2[LU4(i,0,j,15)]) - (f2[LU4(i,0,j,2)]+f2[LU4(i,0,j,16)]+f2[LU4(i,0,j,10)])); Nyz = 0.5*((f2[LU4(i,0,j,5)]+f2[LU4(i,0,j,9)]+f2[LU4(i,0,j,16)]) - (f2[LU4(i,0,j,6)]+f2[LU4(i,0,j,15)]+f2[LU4(i,0,j,10)])); f2[LU4(i,0,j,7)] = f2[LU4(i,0,j,8)] - Nyx; f2[LU4(i,0,j,14)] = f2[LU4(i,0,j,13)] + Nyx; f2[LU4(i,0,j,11)] = f2[LU4(i,0,j,12)] - Nyz; f2[LU4(i,0,j,17)] = f2[LU4(i,0,j,18)] + Nyz; // y = Nm1 (Lid) rhotemp = vfrac * (f2[LU4(i,Nm1,j,1)] + f2[LU4(i,Nm1,j,2)] + f2[LU4(i,Nm1,j,5)] + f2[LU4(i,Nm1,j,6)] + f2[LU4(i,Nm1,j,9)] + f2[LU4(i,Nm1,j,15)] + f2[LU4(i,Nm1,j,16)] + f2[LU4(i,Nm1,j,10)] + f2[LU4(i,Nm1,j,0)] + 2.0*(f2[LU4(i,Nm1,j,3)] + f2[LU4(i,Nm1,j,7)] + f2[LU4(i,Nm1,j,14)] + f2[LU4(i,Nm1,j,11)] + f2[LU4(i,Nm1,j,17)])); f2[LU4(i,Nm1,j,4)] = f2[LU4(i,Nm1,j,3)] - rhotemp * vlid * third; Nyx = 0.5*((f2[LU4(i,Nm1,j,1)]+f2[LU4(i,Nm1,j,9)]+f2[LU4(i,Nm1,j,15)]) - (f2[LU4(i,Nm1,j,2)]+f2[LU4(i,Nm1,j,16)]+f2[LU4(i,Nm1,j,10)])) - rhotemp * ulid * third; Nyz = 0.5*((f2[LU4(i,Nm1,j,5)]+f2[LU4(i,Nm1,j,9)]+f2[LU4(i,Nm1,j,16)]) - (f2[LU4(i,Nm1,j,6)]+f2[LU4(i,Nm1,j,15)]+f2[LU4(i,Nm1,j,10)])) - rhotemp * wlid * third; f2[LU4(i,Nm1,j,8)] = f2[LU4(i,Nm1,j,7)] - rhotemp * (vlid + ulid) * sixth + Nyx; f2[LU4(i,Nm1,j,13)] = f2[LU4(i,Nm1,j,14)] + rhotemp * (-vlid + ulid) * sixth - Nyx; f2[LU4(i,Nm1,j,12)] = f2[LU4(i,Nm1,j,11)] - rhotemp * (vlid + wlid) * sixth + Nyz; f2[LU4(i,Nm1,j,18)] = f2[LU4(i,Nm1,j,17)] + rhotemp * (-vlid + wlid) * sixth - Nyz; } } // Edges #pragma omp parallel for private(temp) for (int i = 1; i < Nm1; i++){ temp = 0.25 * (f2[LU4(i, 0, 0, 1)] - f2[LU4(i, 0, 0, 2)]); // Bottom Back f2[LU4(i, 0, 0, 3)] = fstar[LU4(i, 0, 0, 4)]; f2[LU4(i, 0, 0, 7)] = fstar[LU4(i, 0, 0, 8)] - temp; f2[LU4(i, 0, 0, 11)] = fstar[LU4(i, 0, 0, 12)]; f2[LU4(i, 0, 0, 14)] = fstar[LU4(i, 0, 0, 13)] + temp; f2[LU4(i, 0, 0, 17)] = fstar[LU4(i, 0, 0, 18)]; f2[LU4(i, 0, 0, 5)] = fstar[LU4(i, 0, 0, 6)]; f2[LU4(i, 0, 0, 9)] = fstar[LU4(i, 0, 0, 10)] - temp; f2[LU4(i, 0, 0, 16)] = fstar[LU4(i, 0, 0, 15)] + temp; f2[LU4(i, 0, 0, 18)] = fstar[LU4(i, 0, 0, 17)]; // Bottom Front temp = 0.25 * (f2[LU4(i, 0, Nm1, 1)] - f2[LU4(i, 0, Nm1, 2)]); f2[LU4(i, 0, Nm1, 3)] = fstar[LU4(i, 0, Nm1, 4)]; f2[LU4(i, 0, Nm1, 7)] = fstar[LU4(i, 0, Nm1, 8)] - temp; f2[LU4(i, 0, Nm1, 11)] = fstar[LU4(i, 0, Nm1, 12)]; f2[LU4(i, 0, Nm1, 14)] = fstar[LU4(i, 0, Nm1, 13)] + temp; f2[LU4(i, 0, Nm1, 17)] = fstar[LU4(i, 0, Nm1, 18)]; f2[LU4(i, 0, Nm1, 6)] = fstar[LU4(i, 0, Nm1, 5)]; f2[LU4(i, 0, Nm1, 10)] = fstar[LU4(i, 0, Nm1, 9)] + temp; f2[LU4(i, 0, Nm1, 12)] = fstar[LU4(i, 0, Nm1, 11)]; f2[LU4(i, 0, Nm1, 15)] = fstar[LU4(i, 0, Nm1, 16)]- temp; // Top Back temp = 0.25 * (f2[LU4(i, Nm1, 0, 1)] - f2[LU4(i, Nm1, 0, 2)]); f2[LU4(i, Nm1, 0, 4)] = fstar[LU4(i, Nm1, 0, 3)]; f2[LU4(i, Nm1, 0, 8)] = fstar[LU4(i, Nm1, 0, 7)] + temp; f2[LU4(i, Nm1, 0, 12)] = fstar[LU4(i, Nm1,0, 11)]; f2[LU4(i, Nm1, 0, 13)] = fstar[LU4(i, Nm1, 0, 14)] - temp; f2[LU4(i, Nm1, 0, 18)] = fstar[LU4(i, Nm1, 0, 17)]; f2[LU4(i, Nm1,0, 5)] = fstar[LU4(i, Nm1,0, 6)]; f2[LU4(i, Nm1,0, 9)] = fstar[LU4(i, Nm1,0, 10)] - temp; f2[LU4(i, Nm1,0, 11)] = fstar[LU4(i, Nm1, 0, 12)]; f2[LU4(i, Nm1,0, 16)] = fstar[LU4(i, Nm1,0, 15)] + temp; // Top Front temp = 0.25 * (f2[LU4(i, Nm1, Nm1, 1)] - f2[LU4(i, Nm1, Nm1, 2)]); f2[LU4(i, Nm1, Nm1, 4)] = fstar[LU4(i, Nm1, Nm1, 3)]; f2[LU4(i, Nm1, Nm1, 8)] = fstar[LU4(i, Nm1, Nm1, 7)] + temp; f2[LU4(i, Nm1, Nm1, 12)] = fstar[LU4(i, Nm1, Nm1, 11)]; f2[LU4(i, Nm1, Nm1, 13)] = fstar[LU4(i, Nm1, Nm1, 14)]- temp; f2[LU4(i, Nm1, Nm1, 18)] = fstar[LU4(i, Nm1,Nm1, 17)]; f2[LU4(i, Nm1,Nm1, 6)] = fstar[LU4(i, Nm1,Nm1, 5)]; f2[LU4(i, Nm1,Nm1, 10)] = fstar[LU4(i, Nm1,Nm1, 9)] + temp; f2[LU4(i, Nm1,Nm1, 15)] = fstar[LU4(i, Nm1,Nm1, 16)] - temp; f2[LU4(i, Nm1,Nm1, 17)] = fstar[LU4(i, Nm1, Nm1, 18)] ; // Left Back temp = 0.25 * (f2[LU4(0, i, 0, 3)] - f2[LU4(0, i, 0, 4)]); f2[LU4(0, i, 0, 1)] = fstar[LU4(0, i, 0, 2)]; f2[LU4(0, i, 0, 7)] = fstar[LU4(0, i, 0, 8)] - temp; f2[LU4(0, i, 0, 9)] = fstar[LU4(0, i, 0, 10)]; f2[LU4(0, i, 0, 13)] = fstar[LU4(0, i, 0, 14)] + temp; f2[LU4(0, i, 0, 15)] = fstar[LU4(0, i, 0, 16)]; f2[LU4(0, i, 0, 5)] = fstar[LU4(0, i, 0, 6)]; f2[LU4(0, i, 0, 11)] = fstar[LU4(0, i, 0, 12)] - temp; f2[LU4(0, i, 0, 16)] = fstar[LU4(0, i, 0, 15)]; f2[LU4(0, i, 0, 18)] = fstar[LU4(0, i, 0, 17)] + temp; // Left Front temp = 0.25 * (f2[LU4(0, i, Nm1, 3)] - f2[LU4(0, i, Nm1, 4)]); f2[LU4(0, i, Nm1, 1)] = fstar[LU4(0, i, Nm1, 2)]; f2[LU4(0, i, Nm1, 7)] = fstar[LU4(0, i, Nm1, 8)] - temp; f2[LU4(0, i, Nm1, 9)] = fstar[LU4(0, i, Nm1, 10)]; f2[LU4(0, i, Nm1, 13)] = fstar[LU4(0, i, Nm1, 14)] + temp; f2[LU4(0, i, Nm1, 15)] = fstar[LU4(0, i, Nm1, 16)]; f2[LU4(0, i, Nm1, 6)] = fstar[LU4(0, i, Nm1, 5)]; f2[LU4(0, i, Nm1, 10)] = fstar[LU4(0, i, Nm1, 9)]; f2[LU4(0, i, Nm1, 12)] = fstar[LU4(0, i, Nm1, 11)] + temp; f2[LU4(0, i, Nm1, 17)] = fstar[LU4(0, i, Nm1, 18)] - temp; // Right Back temp = 0.25 * (f2[LU4(Nm1, i, 0, 3)] - f2[LU4(Nm1, i, 0, 4)]); f2[LU4(Nm1, i, 0, 2)] = fstar[LU4(Nm1, i, 0, 1)]; f2[LU4(Nm1, i, 0, 8)] = fstar[LU4(Nm1, i, 0, 7)] - temp; f2[LU4(Nm1, i, 0, 10)] = fstar[LU4(Nm1, i,0, 9)]; f2[LU4(Nm1, i, 0, 14)] = fstar[LU4(Nm1, i, 0, 13)] + temp; f2[LU4(Nm1, i, 0, 16)] = fstar[LU4(Nm1, i, 0, 15)]; f2[LU4(Nm1, i,0, 5)] = fstar[LU4(Nm1, i,0, 6)]; f2[LU4(Nm1, i,0, 9)] = fstar[LU4(Nm1, i, 0, 10)] ; f2[LU4(Nm1, i,0, 11)] = fstar[LU4(Nm1, i,0, 12)] - temp; f2[LU4(Nm1, i,0, 18)] = fstar[LU4(Nm1, i,0, 17)] + temp; // Right Front temp = -0.25 * (f2[LU4(Nm1, i, Nm1, 3)] - f2[LU4(Nm1, i, Nm1, 4)]); f2[LU4(Nm1, i, Nm1, 2)] = fstar[LU4(Nm1, i, Nm1, 1)]; f2[LU4(Nm1, i, Nm1, 8)] = fstar[LU4(Nm1, i, Nm1, 7)] - temp; f2[LU4(Nm1, i, Nm1, 10)] = fstar[LU4(Nm1, i, Nm1, 9)]; f2[LU4(Nm1, i, Nm1, 14)] = fstar[LU4(Nm1, i, Nm1, 13)] + temp; f2[LU4(Nm1, i, Nm1, 16)] = fstar[LU4(Nm1, i,Nm1, 15)]; f2[LU4(Nm1, i,Nm1, 6)] = fstar[LU4(Nm1, i,Nm1, 5)]; f2[LU4(Nm1, i,Nm1, 12)] = fstar[LU4(Nm1, i,Nm1, 11)] - temp; f2[LU4(Nm1, i,Nm1, 15)] = fstar[LU4(Nm1, i, Nm1, 16)]; f2[LU4(Nm1, i,Nm1, 17)] = fstar[LU4(Nm1, i,Nm1, 18)] + temp; // Bottom Left temp = 0.25 * (f2[LU4(0, 0, i, 5)] - f2[LU4(0, 0, i, 6)]); f2[LU4(0, 0, i, 3)] = fstar[LU4(0, 0, i, 4)]; f2[LU4(0, 0, i, 7)] = fstar[LU4(0, 0, i, 8)]; f2[LU4(0, 0, i, 11)] = fstar[LU4(0, 0, i, 12)] - temp; f2[LU4(0, 0, i, 14)] = fstar[LU4(0, 0, i, 13)]; f2[LU4(0, 0, i, 17)] = fstar[LU4(0, 0, i, 18)] + temp; f2[LU4(0, 0, i, 1)] = fstar[LU4(0, 0, i, 2)]; f2[LU4(0, 0, i, 9)] = fstar[LU4(0, 0, i, 10)] - temp; f2[LU4(0, 0, i, 13)] = fstar[LU4(0, 0, i, 14)]; f2[LU4(0, 0, i, 15)] = fstar[LU4(0, 0, i, 16)] + temp; // Top Left temp = 0.25 * (f2[LU4(0, Nm1, i, 5)] - f2[LU4(0, Nm1, i, 6)]); f2[LU4(0, Nm1, i, 4)] = fstar[LU4(0, Nm1, i, 3)]; f2[LU4(0, Nm1, i, 8)] = fstar[LU4(0, Nm1, i, 7)]; f2[LU4(0, Nm1, i, 12)] = fstar[LU4(0, Nm1, i, 11)]+ temp; f2[LU4(0, Nm1, i, 13)] = fstar[LU4(0, Nm1, i, 14)]; f2[LU4(0, Nm1, i, 18)] = fstar[LU4(0, Nm1, i, 17)]- temp; f2[LU4(0, Nm1, i, 1)] = fstar[LU4(0, Nm1, i, 2)]; f2[LU4(0, Nm1, i, 7)] = fstar[LU4(0, Nm1, i, 8)]; f2[LU4(0, Nm1, i, 9)] = fstar[LU4(0, Nm1, i, 10)] - temp; f2[LU4(0, Nm1, i, 15)] = fstar[LU4(0, Nm1, i, 16)] + temp; // Bottom Right temp = 0.25 * (f2[LU4(Nm1, 0, i, 5)] - f2[LU4(Nm1, 0, i, 6)]); f2[LU4(Nm1, 0, i, 3)] = fstar[LU4(Nm1, 0, i, 4)]; f2[LU4(Nm1, 0, i, 7)] = fstar[LU4(Nm1, 0, i, 8)]; f2[LU4(Nm1, 0, i, 11)] = fstar[LU4(Nm1, 0, i, 12)] - temp; f2[LU4(Nm1, 0, i, 14)] = fstar[LU4(Nm1, 0, i, 13)]; f2[LU4(Nm1, 0, i, 17)] = fstar[LU4(Nm1, 0, i, 18)] + temp; f2[LU4(Nm1, 0, i, 2)] = fstar[LU4(Nm1, 0, i, 1)]; f2[LU4(Nm1, 0, i, 8)] = fstar[LU4(Nm1, 0, i, 7)]; f2[LU4(Nm1, 0, i, 10)] = fstar[LU4(Nm1, 0, i, 9)] + temp; f2[LU4(Nm1, 0, i, 16)] = fstar[LU4(Nm1, 0, i, 15)] - temp; // Top Right temp = 0.25 * (f2[LU4(Nm1, Nm1, i, 5)] - f2[LU4(Nm1, Nm1, i, 6)]); f2[LU4(Nm1, Nm1, i, 4)] = fstar[LU4(Nm1, Nm1, i, 3)]; f2[LU4(Nm1, Nm1, i, 8)] = fstar[LU4(Nm1, Nm1, i, 7)]; f2[LU4(Nm1, Nm1, i, 12)] = fstar[LU4(Nm1, Nm1, i, 11)] + temp; f2[LU4(Nm1, Nm1, i, 13)] = fstar[LU4(Nm1, Nm1, i, 14)]; f2[LU4(Nm1, Nm1, i, 18)] = fstar[LU4(Nm1, Nm1, i, 17)] - temp; f2[LU4(Nm1, Nm1, i, 2)] = fstar[LU4(Nm1, Nm1, i, 1)]; f2[LU4(Nm1, Nm1, i, 10)] = fstar[LU4(Nm1, Nm1, i, 9)] + temp; f2[LU4(Nm1, Nm1, i, 14)] = fstar[LU4(Nm1, Nm1, i, 13)]; f2[LU4(Nm1, Nm1, i, 16)] = fstar[LU4(Nm1, Nm1, i, 15)] - temp; } // Corners // Back Top left f2[LU4(0, Nm1, 0, 1)] = fstar[LU4(0, Nm1, 0, 2)]; f2[LU4(0, Nm1, 0, 4)] = fstar[LU4(0, Nm1, 0, 3)]; f2[LU4(0, Nm1, 0, 5)] = fstar[LU4(0, Nm1, 0, 6)]; f2[LU4(0, Nm1, 0, 9)] = fstar[LU4(0, Nm1, 0, 10)]; f2[LU4(0, Nm1, 0, 13)] = fstar[LU4(0, Nm1, 0, 14)]; f2[LU4(0, Nm1, 0, 18)] = fstar[LU4(0, Nm1, 0, 17)]; // Back Bottom Left f2[LU4(0, 0, 0, 1)] = fstar[LU4(0, 0, 0, 2)]; f2[LU4(0, 0, 0, 3)] = fstar[LU4(0, 0, 0, 4)]; f2[LU4(0, 0, 0, 5)] = fstar[LU4(0, 0, 0, 6)]; f2[LU4(0, 0, 0, 9)] = fstar[LU4(0, 0, 0, 10)]; f2[LU4(0, 0, 0, 7)] = fstar[LU4(0, 0, 0, 8)]; f2[LU4(0, 0, 0, 11)] = fstar[LU4(0, 0, 0, 12)]; // Back Top Right f2[LU4(Nm1, Nm1, 0, 2)] = fstar[LU4(Nm1, Nm1, 0, 1)]; f2[LU4(Nm1, Nm1, 0, 4)] = fstar[LU4(Nm1, Nm1, 0, 3)]; f2[LU4(Nm1, Nm1, 0, 5)] = fstar[LU4(Nm1, Nm1, 0, 6)]; f2[LU4(Nm1, Nm1, 0, 16)] = fstar[LU4(Nm1, Nm1, 0, 15)]; f2[LU4(Nm1, Nm1, 0, 8)] = fstar[LU4(Nm1, Nm1, 0, 7)]; f2[LU4(Nm1, Nm1, 0, 18)] = fstar[LU4(Nm1, Nm1, 0, 17)]; // Back Bottom Right f2[LU4(Nm1, 0, 0, 2)] = fstar[LU4(Nm1, 0, 0, 1)]; f2[LU4(Nm1, 0, 0, 3)] = fstar[LU4(Nm1, 0, 0, 4)]; f2[LU4(Nm1, 0, 0, 5)] = fstar[LU4(Nm1, 0, 0, 6)]; f2[LU4(Nm1, 0, 0, 16)] = fstar[LU4(Nm1, 0, 0, 15)]; f2[LU4(Nm1, 0, 0, 14)] = fstar[LU4(Nm1, 0, 0, 13)]; f2[LU4(Nm1, 0, 0, 11)] = fstar[LU4(Nm1, 0, 0, 12)]; // Front Top left f2[LU4(0, Nm1, Nm1, 1)] = fstar[LU4(0, Nm1, Nm1, 2)]; f2[LU4(0, Nm1, Nm1, 4)] = fstar[LU4(0, Nm1, Nm1, 3)]; f2[LU4(0, Nm1, Nm1, 6)] = fstar[LU4(0, Nm1, Nm1, 5)]; f2[LU4(0, Nm1, Nm1, 15)] = fstar[LU4(0, Nm1, Nm1, 16)]; f2[LU4(0, Nm1, Nm1, 13)] = fstar[LU4(0, Nm1, Nm1, 14)]; f2[LU4(0, Nm1, Nm1, 12)] = fstar[LU4(0, Nm1, Nm1, 11)]; // Front Bottom Left f2[LU4(0, 0, Nm1, 1)] = fstar[LU4(0, 0, Nm1, 2)]; f2[LU4(0, 0, Nm1, 3)] = fstar[LU4(0, 0, Nm1, 4)]; f2[LU4(0, 0, Nm1, 6)] = fstar[LU4(0, 0, Nm1, 5)]; f2[LU4(0, 0, Nm1, 15)] = fstar[LU4(0, 0, Nm1, 16)]; f2[LU4(0, 0, Nm1, 7)] = fstar[LU4(0, 0, Nm1, 8)]; f2[LU4(0, 0, Nm1, 17)] = fstar[LU4(0, 0, Nm1, 18)]; // Front Top Right f2[LU4(Nm1, Nm1, Nm1, 2)] = fstar[LU4(Nm1, Nm1, Nm1, 1)]; f2[LU4(Nm1, Nm1, Nm1, 4)] = fstar[LU4(Nm1, Nm1, Nm1, 3)]; f2[LU4(Nm1, Nm1, Nm1, 6)] = fstar[LU4(Nm1, Nm1, Nm1, 5)]; f2[LU4(Nm1, Nm1, Nm1, 10)] = fstar[LU4(Nm1, Nm1, Nm1, 9)]; f2[LU4(Nm1, Nm1, Nm1, 8)] = fstar[LU4(Nm1, Nm1, Nm1, 7)]; f2[LU4(Nm1, Nm1, Nm1, 12)] = fstar[LU4(Nm1, Nm1, Nm1, 11)]; // Front Bottom Right f2[LU4(Nm1, 0, Nm1, 2)] = fstar[LU4(Nm1, 0, Nm1, 1)]; f2[LU4(Nm1, 0, Nm1, 3)] = fstar[LU4(Nm1, 0, Nm1, 4)]; f2[LU4(Nm1, 0, Nm1, 6)] = fstar[LU4(Nm1, 0, Nm1, 5)]; f2[LU4(Nm1, 0, Nm1, 10)] = fstar[LU4(Nm1, 0, Nm1, 9)]; f2[LU4(Nm1, 0, Nm1, 14)] = fstar[LU4(Nm1, 0, Nm1, 13)]; f2[LU4(Nm1, 0, Nm1, 17)] = fstar[LU4(Nm1, 0, Nm1, 18)]; } // Returns L2 norm of difference of two arrays double diff(double *array1, double *array2, int n){ double difference = 0; #pragma omp parallel for default(none) shared(array1,array2,n) reduction(+:difference) for (int i = 0; i < n; i++){ difference += P2(array1[i] - array2[i]); } return sqrt(difference); } void checkfeq(double feq){ if (feq < 0.0) { printf("Error: negative feq. Therefore, unstable.\n"); exit(1); } } // Calculate macro variables void macrovars(double* F){ double rhotemp,utemp,vtemp,wtemp,ftemp; #pragma omp parallel for private(rhotemp, utemp, vtemp, wtemp, ftemp) collapse(3) for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ for (int k = 0; k < N; k++) { rhotemp = 0.0; utemp = 0.0; vtemp = 0.0; wtemp = 0.0; for (int q = 0; q < Q; q++) { ftemp = F[LU4(i, j, k, q)]; rhotemp += ftemp; utemp += c[q][0] * ftemp; vtemp += c[q][1] * ftemp; wtemp += c[q][2] * ftemp; } rho[LU3(i, j, k)] = rhotemp; u1[LU3(i, j, k)] = utemp / rhotemp; u2[LU3(i, j, k)] = vtemp / rhotemp; u3[LU3(i, j, k)] = wtemp / rhotemp; } } } } // Swap pointers void swap(double **a, double **b){ double *temp; temp=*a; *a = *b; *b = temp; } // Calculate velocity magnitude void calcvmag(void){ #pragma omp parallel for default(none) shared(vmag,u1,u2,u3) collapse(3) for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { vmag[LU3(i,j,k)] = sqrt(P2(u1[LU3(i,j,k)]) + P2(u2[LU3(i,j,k)]) + P2(u3[LU3(i,j,k)])); } } } }
allocator.h
#pragma once #include "adabs/pgas_addr.h" namespace adabs { namespace impl { inline void* real_allocate(const int num_objects, const int batch_size, const int sizeT, const int alignmentT); } /** * This is our single assignment allocator, that is it creates all our * single assignment shared memory. It will allocate memory as follows * FTTTTTTTTTTTFTTTTTTTTTTTFTTTTTTTTTTT * |---num---| |---num---| |---num---| * whereas F is our flag indicating if data is available * T is the data * num indicates the batch size * NOTE: This allocator follows the STL concept, but is not expected * to be STL conform. We may decide to bend (or even break) * parts of what is expected from STL allocators. After all * STL allocators are "weird" (see Effective STL) * Currently missing: * - non-const references * - max_size() */ template <typename T> class pgas_addr; template <typename T> struct allocator; // specialize for void, since we can't have void& // not sure if we really need this... template <> struct allocator<void> { typedef pgas_addr<void> pointer; typedef const pgas_addr<void> const_pointer; typedef void value_type; template <class U> struct rebind { typedef allocator<U> other; }; }; template <typename T> struct allocator { /***************** TYPEDEFS ***********************/ typedef size_t size_type; //typedef ptrdiff_t difference_type; typedef pgas_addr<T> pointer; typedef const pgas_addr<T> const_pointer; typedef T value_type; //typedef T& reference; typedef const T& const_reference; // allows to rebind this allocator to a different type template <typename U> struct rebind { typedef allocator<U> other; }; /***************** CONSTRUCTORS ********************/ allocator() throw() {} allocator(const allocator&) throw() {} template <class U> allocator(const allocator<U>&) throw() {} ~allocator() throw() {} /****************** ALLOCATE **********************/ static pointer allocate(size_type num_objects, const void* localityHint = 0) { void* ptr = allocate (num_objects, 1, localityHint); return pointer(ptr, 1); } static pointer allocate(size_type num_objects, size_type batch_size, const void* localityHint = 0) { int a = tools::alignment<T>::val(); if (a<sizeof(int)) a = sizeof(int); void* ptr = impl::real_allocate(num_objects, batch_size, sizeof(T), a); return pointer(ptr, batch_size); } /****************** DEALLOCATE **********************/ static void deallocate(pointer &p, size_type n) { deallocate(p); } static void deallocate(pointer &p); /****************** CONSTRUCT **********************/ static void construct(pointer p, const T& val); static void destroy(pointer p); /****************** ADDRESS **********************/ static const_pointer address(const_reference x); }; template <typename T> void allocator<T>::deallocate(pointer &p) { assert(p.is_local()); free(p._orig_ptr); } template <typename T> void allocator<T>::construct(pointer p, const T& val) { // TODO throw "not implemented"; p->T(val); } template <typename T> void allocator<T>::destroy(pointer p) { // TODO throw "not implemented"; p->~T(); } template <typename T> allocator<T>::const_pointer allocator<T>::address(const_reference x) { char* ptr = &x; ptr -= sizeof(int); return const_pointer((void*)ptr); } template <class T1, class T2> bool operator==(const allocator<T1>&, const allocator<T2>&) throw() { return true; } template <class T1, class T2> bool operator!=(const allocator<T1>&, const allocator<T2>&) throw() { return false; } namespace impl { inline void* real_allocate(const int num_objects, const int batch_size, const int sizeT, const int alignmentT) { const size_t batch_mem_size = sizeT * batch_size + alignmentT; //#pragma omp critical //std::cout << "malloc: |T| = " << sizeT << ", #batch = " << batch_size << ", alignment = " << alignmentT << std::endl; const size_t num_batch = (num_objects % batch_size == 0) ? (num_objects / batch_size) : (num_objects / batch_size) + 1; const size_t mem_size = num_batch * batch_mem_size; //std::cout << "malloc: #batches = " << num_batch << ", |batch| = " << batch_mem_size << std::endl; void *ptr = malloc (mem_size); char *init_ptr = (char*)ptr; //#pragma omp critical //std::cout << "malloc: returned " << ptr << " to " << (void*)((char*)ptr + mem_size) << ", bytes: " << mem_size << std::endl; for (int i=0; i<num_batch; ++i) { //std::cout << "init ptr " << (void*)init_ptr << std::endl; init_ptr += batch_mem_size - alignmentT; //std::cout << "init ptr " << (void*)init_ptr << std::endl; int *flag_ptr = (int*)init_ptr; //#pragma omp critical //std::cout << "write 0 to " << flag_ptr << std::endl; *flag_ptr = 0; init_ptr += alignmentT; } return ptr; } } }
scattering.c
/****************************************************************************** * * * SCATTERING.C * * * * RELATIVISTIC SCATTERING KERNEL * * * ******************************************************************************/ #include "decs.h" #if RADIATION // RADIATION HOT CROSS SECTION #define NW 220 #define NT 90 #define MINW (1.e-16) // w = h nu/m_e c^2 // #define MAXW (1.e10) #define MINT (0.001) // Theta = k_b T / m c^2, m = mass of scatterer #define MAXT (1.e11) #define MAXGAMMA (12.) #define DMUE (0.05) #define DGAMMAE (0.05) #define N_HC_TABLES (1) #define TRUNCATE_HOTCROSS (1) #if RADIATION == RADTYPE_NEUTRINOS #if MULTISCATT_TEST const char *HOTCROSS[N_HC_TABLES] = {"hotcross_multiscatt.dat"}; #else const char *HOTCROSS[N_HC_TABLES] = {"hotcross_quad.dat"}; #endif #else const char *HOTCROSS[N_HC_TABLES] = {"hotcross.dat"}; #endif double table[N_HC_TABLES][NW + 1][NT + 1]; double MAXW, dlw, dlT, lminw, lmint; void sample_gas_particle(double Ktetrad[NDIM], double Pelectron[NDIM], const struct of_microphysics *m, int type, int interaction); void sample_beta(double Thetae, double *gamma_e, double *beta_e); double sample_y(double Thetae); double sample_mu(double beta_e); double get_total_cross_section(double k, const struct of_microphysics *m, int type, int interaction, int normalized); void sample_scattered_rad(double k[NDIM], double p[NDIM], double kp[NDIM], const struct of_microphysics *m, int type, int interaction); void boost(double v[NDIM], double u[NDIM], double vp[NDIM]); void sample_cross_section(double k, double *k0p, double *cth, const struct of_microphysics *m, int type, int interaction); double total_cross_num(hc_ftype f, double w, double Thetae); double dNdgammae(double thetae, double gammae); double boostcross(hc_ftype f, double w, double mue, double gammae); void init_hc_table( hc_ftype f, double table[NW + 1][NT + 1], const char *hc_name); double interpolate_hc_table(double w, double theta, hc_ftype f, double table[NW + 1][NT + 1], const char *hc_name); // rejection sampling void rejection_sample(dsdom_ftype f, double xmax, double k, double *k0p, double *cth, const struct of_microphysics *m, int type, int interaction); // compton scattering double sample_klein_nishina(double k0); double klein_nishina(double a, double ap); double hc_klein_nishina(double we, double mue); // Neutrino physics double hc_quad(double we, double mue); double hc_quad_max(); double nu_cross_factor( double sigma, int type, int interaction, const struct of_microphysics *m); double total_cross_ions(double sigma_hc, double A, double Z); double nu_cross_delta(int type, int interaction); double nu_cross(double w, double mu, const struct of_microphysics *m, int type, int interaction); double nu_cross_max(const struct of_microphysics *m, int type, int interaction); // multiscatt test #if MULTISCATT_TEST double hc_flat(double we, double mue); double ms_flat(double w, double mu, const struct of_microphysics *m, int type, int interaction); double ms_flat_max(const struct of_microphysics *m, int type, int interaction); #endif // Scattering temperature too small int scatt_temp_too_small(const struct of_microphysics *m) { #if MULTISCATT_TEST return 0; #else // normal scattering #if RADIATION == RADTYPE_LIGHT { return m->Thetae < 10. * SMALL; } #elif RADIATION == RADTYPE_NEUTRINOS { return (KBOL * m->T) / (ME * CL * CL) < 10. * SMALL; } #endif // neutrinos #endif // Not multiscatt test } int scatter_superphoton(grid_prim_type P, grid_eosvar_type extra, struct of_photon *ph, double X[NDIM], double Kcov[NDIM], double Kcon[NDIM], int interaction) { const int fail = 0; const int success = 1; double Pelectron[NDIM], gcov[NDIM][NDIM], gcon[NDIM][NDIM]; double Econ[NDIM][NDIM], Ecov[NDIM][NDIM]; double Ktetrad[NDIM], Ktetrad_scatt[NDIM]; int i, j, k; int bad_scatter = 0; Xtoijk(X, &i, &j, &k); set_gcov(X, gcov); gcon_func(gcov, gcon); normalize_null(gcov, Kcon); normalize_null_cov(gcon, Kcov); // Quality control if (ph->type == TYPE_TRACER) return fail; if (Kcon[0] < 0. || Kcov[0] > 0.) return fail; DLOOP1 { if (is_practically_nan(Kcon[mu]) || is_practically_nan(Kcov[mu])) { return fail; } } double Ucon[NDIM], Ucov[NDIM], Bcon[NDIM], Bcov[NDIM]; struct of_microphysics m; get_fluid_zone(i, j, k, P, extra, &m, Ucon, Ucov, Bcon, Bcov); if (scatt_temp_too_small(&m)) return fail; make_tetrad(i, j, k, Ucon, Bcon, gcov, Econ, Ecov); coord_to_tetrad(Ecov, Kcon, Ktetrad); DLOOP1 { if (is_practically_nan(Ktetrad[mu])) { bad_scatter = 1; } } if (bad_scatter) { fprintf(stderr, "Bad tetrad!\n" "\tUcon = [%e %e %e %e]\n" "\tUcov = [%e %e %e %e]\n" "\tBcon = [%e %e %e %e]\n" "\tBcov = [%e %e %e %e]\n" "\tKtetrad = [%e %e %e %e]\n" "\tKcoord = [%e %e %e %e]\n" "\n" "\tEcon = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n" "\n" "\tEcov = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n" "\t = [%e %e %e %e]\n", Ucon[0], Ucon[1], Ucon[2], Ucon[3], Ucov[0], Ucov[1], Ucov[2], Ucov[3], Bcon[0], Bcon[1], Bcon[2], Bcon[3], Bcov[0], Bcov[1], Bcov[2], Bcov[3], Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3], Kcon[0], Kcon[1], Kcon[2], Kcon[3], Econ[0][0], Econ[0][1], Econ[0][2], Econ[0][3], Econ[1][0], Econ[1][1], Econ[1][2], Econ[1][3], Econ[2][0], Econ[2][1], Econ[2][2], Econ[2][3], Econ[3][0], Econ[3][1], Econ[3][2], Econ[3][3], Ecov[0][0], Ecov[0][1], Ecov[0][2], Ecov[0][3], Ecov[1][0], Ecov[1][1], Ecov[1][2], Ecov[1][3], Ecov[2][0], Ecov[2][1], Ecov[2][2], Ecov[2][3], Ecov[3][0], Ecov[3][1], Ecov[3][2], Ecov[3][3]); return fail; } sample_gas_particle(Ktetrad, Pelectron, &m, ph->type, interaction); DLOOP1 { if (is_practically_nan(Pelectron[mu])) { #if RADIATION == RADTYPE_LIGHT printf("m.Thetae = %e m.Ne = %e m.B = %e\n", m.Thetae, m.Ne, m.B); #endif printf("Pelectron[%i] = %e!\n", mu, Pelectron[mu]); printf( "K = %e %e %e %e\n", Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3]); printf("k.k = %e\n", -Ktetrad[0] * Ktetrad[0] + Ktetrad[1] * Ktetrad[1] + Ktetrad[2] * Ktetrad[2] + Ktetrad[3] * Ktetrad[3]); return fail; } } sample_scattered_rad( Ktetrad, Pelectron, Ktetrad_scatt, &m, ph->type, interaction); DLOOP1 { if (is_practically_nan(Ktetrad_scatt[mu])) { // printf("Ktetrad_scatt[%i] = %e!\n", mu, Ktetrad_scatt[mu]); bad_scatter = 1; } } // If scatter fails, return failure and complain if (bad_scatter) { fprintf(stderr, "Bad scatter after sample_scattered_rad:\n" "\tph->Kcon[2] is bad\n" "\tUcon = [%e %e %e %e]\n" "\tUcov = [%e %e %e %e]\n" "\tBcon = [%e %e %e %e]\n" "\tBcov = [%e %e %e %e]\n" "\tKtetrad = [%e %e %e %e]\n" "\tKcon = [%e %e %e %e]\n", Ucon[0], Ucon[1], Ucon[2], Ucon[3], Ucov[0], Ucov[1], Ucov[2], Ucov[3], Bcon[0], Bcon[1], Bcon[2], Bcon[3], Bcov[0], Bcov[1], Bcov[2], Bcov[3], Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3], ph->Kcon[2][0], ph->Kcon[2][1], ph->Kcon[2][2], ph->Kcon[2][3]); return fail; } // Check NAN after each of these tetrad_to_coord(Econ, Ktetrad_scatt, ph->Kcon[2]); DLOOP1 { if (is_practically_nan(ph->Kcon[2][mu])) { // fprintf(stderr,"ph->Kcon[2][%i] = %e!\n", mu, ph->Kcon[2][mu]); bad_scatter = 1; } } if (bad_scatter) { fprintf(stderr, "Bad scatter after tetrad_to_coord:\n" "\tph->Kcon[2] is bad\n" "\ttype = %d\n" "\tinteraction = %d\n" "\tUcon = [%e %e %e %e]\n" "\tUcov = [%e %e %e %e]\n" "\tBcon = [%e %e %e %e]\n" "\tBcov = [%e %e %e %e]\n" "\tKtetrad = [%e %e %e %e]\n" "\tKcon = [%e %e %e %e]\n", ph->type, interaction, Ucon[0], Ucon[1], Ucon[2], Ucon[3], Ucov[0], Ucov[1], Ucov[2], Ucov[3], Bcon[0], Bcon[1], Bcon[2], Bcon[3], Bcov[0], Bcov[1], Bcov[2], Bcov[3], Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3], ph->Kcon[2][0], ph->Kcon[2][1], ph->Kcon[2][2], ph->Kcon[2][3]); return fail; } // Ensure scattered superphoton is sane normalize_null(gcov, ph->Kcon[2]); DLOOP1 { if (is_practically_nan(ph->Kcon[2][mu])) { // fprintf(stderr,"after norm ph->Kcon[2][%i] = %e!\n", mu, // ph->Kcon[2][mu]); bad_scatter = 1; } } if (bad_scatter) { fprintf(stderr, "Bad scatter after normalize_Null:\n" "\tph-Kcon[2] is bad\n" "\ttype = %d\n" "\tinteraction = %d\n" "\tUcon = [%e %e %e %e]\n" "\tUcov = [%e %e %e %e]\n" "\tBcon = [%e %e %e %e]\n" "\tBcov = [%e %e %e %e]\n" "\tKtetrad = [%e %e %e %e]\n" "\tKcon = [%e %e %e %e]\n", ph->type, interaction, Ucon[0], Ucon[1], Ucon[2], Ucon[3], Ucov[0], Ucov[1], Ucov[2], Ucov[3], Bcon[0], Bcon[1], Bcon[2], Bcon[3], Bcov[0], Bcov[1], Bcov[2], Bcov[3], Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3], ph->Kcon[2][0], ph->Kcon[2][1], ph->Kcon[2][2], ph->Kcon[2][3]); return fail; } lower(ph->Kcon[2], gcov, ph->Kcov[2]); DLOOP1 { if (is_practically_nan(ph->Kcov[2][mu])) { // fprintf(stderr,"after lower ph->Kcov[2][%i] = %e!\n", mu, // ph->Kcov[2][mu]); bad_scatter = 1; } } if (bad_scatter) { fprintf(stderr, "Bad scatter after lower Kcon:\n" "\tph-Kcov[2] is bad\n" "\ttype = %d\n" "\tinteraction = %d\n" "\tUcon = [%e %e %e %e]\n" "\tUcov = [%e %e %e %e]\n" "\tBcon = [%e %e %e %e]\n" "\tBcov = [%e %e %e %e]\n" "\tKcon = [%e %e %e %e]\n" "\tKtetrad = [%e %e %e %e]\n" "\tKcov = [%e %e %e %e]\n", ph->type, interaction, Ucon[0], Ucon[1], Ucon[2], Ucon[3], Ucov[0], Ucov[1], Ucov[2], Ucov[3], Bcon[0], Bcon[1], Bcon[2], Bcon[3], Bcov[0], Bcov[1], Bcov[2], Bcov[3], Ktetrad[0], Ktetrad[1], Ktetrad[2], Ktetrad[3], ph->Kcon[2][0], ph->Kcon[2][1], ph->Kcon[2][2], ph->Kcon[2][3], ph->Kcov[2][0], ph->Kcov[2][1], ph->Kcov[2][2], ph->Kcov[2][3]); return fail; } // Ensure scattered superphoton is sane // normalize_null(gcov, ph->Kcon[2]); // normalize_null_cov(gcon, ph->Kcov[2]); /*if (ph->Kcov[2][0] > 0.) { printf("Kcov[0] > 0 after scattering!\n"); printf("ph->X[] = %e %e %e %e\n", ph->X[2][0], ph->X[2][1], ph->X[2][2], ph->X[2][3]); printf("ph->Kcon[] = %e %e %e %e\n", ph->Kcon[2][0], ph->Kcon[2][1], ph->Kcon[2][2], ph->Kcon[2][3]); printf("ph->Kcov[] = %e %e %e %e\n", ph->Kcov[2][0], ph->Kcov[2][1], ph->Kcov[2][2], ph->Kcov[2][3]); }*/ return success; } // Procedure from Canfield et al. 1987 void sample_gas_particle(double k[NDIM], double p[NDIM], const struct of_microphysics *m, int type, int interaction) { double beta_e, mu, phi, cphi, sphi, gamma_e, sigma; double K, sth, cth, x1, n0dotv0, v0, v1; double n0x, n0y, n0z; double v0x, v0y, v0z; double v1x, v1y, v1z; double v2x, v2y, v2z; int sample_cnt = 0; double Thetae = scatterer_dimensionless_temp(type, interaction, m); double factor = 1.0; do { sample_beta(Thetae, &gamma_e, &beta_e); mu = sample_mu(beta_e); // Sometimes |mu| > 1 from roundoff error. Fix it if (mu > 1.) mu = 1.; else if (mu < -1.) mu = -1; // Frequency in electron rest frame K = gamma_e * (1. - beta_e * mu) * k[0]; sigma = get_total_cross_section(K, m, type, interaction, 1); x1 = factor * get_rand(); sample_cnt++; if (sample_cnt > 1000000) { fprintf(stderr, "in sample_gas_particle:\n" "\t type, int, mu, gamma_e, K, sigma, x1, factor:\n" "\t%d %d %g %g %g %g %g %g %g\n", type, interaction, Thetae, mu, gamma_e, K, sigma, x1, factor); // Kluge to prevent stalling for large values of \Theta_e // TODO: does this work? // Thetae *= 0.5 ; factor *= 0.5; sample_cnt = 0; } } while (x1 >= sigma); // First unit vector for coordinate system v0x = k[1]; v0y = k[2]; v0z = k[3]; v0 = sqrt(v0x * v0x + v0y * v0y + v0z * v0z); v0x /= v0; v0y /= v0; v0z /= v0; // Pick zero-angle for coordinate system get_ran_dir_3d(&n0x, &n0y, &n0z); n0dotv0 = v0x * n0x + v0y * n0y + v0z * n0z; // Second unit vector v1x = n0x - (n0dotv0)*v0x; v1y = n0y - (n0dotv0)*v0y; v1z = n0z - (n0dotv0)*v0z; // Normalize v1 = sqrt(v1x * v1x + v1y * v1y + v1z * v1z); v1x /= v1; v1y /= v1; v1z /= v1; // Find one more unit vector using cross product; automatically normalized v2x = v0y * v1z - v0z * v1y; v2y = v0z * v1x - v0x * v1z; v2z = v0x * v1y - v0y * v1x; // Resolve new momentum vector along unit vectors and create a four-vector p phi = get_rand() * 2. * M_PI; // uniform orientation sphi = sin(phi); cphi = cos(phi); cth = mu; sth = sqrt(1. - mu * mu); p[0] = gamma_e; p[1] = gamma_e * beta_e * (cth * v0x + sth * (cphi * v1x + sphi * v2x)); p[2] = gamma_e * beta_e * (cth * v0y + sth * (cphi * v1y + sphi * v2y)); p[3] = gamma_e * beta_e * (cth * v0z + sth * (cphi * v1z + sphi * v2z)); if (beta_e < 0) { fprintf(stderr, "betae error: %g %g %g %g\n", p[0], p[1], p[2], p[3]); } } void sample_beta(double Thetae, double *gamma_e, double *beta_e) { double y = sample_y(Thetae); *gamma_e = y * y * Thetae + 1.; *beta_e = sqrt(1. - 1. / ((*gamma_e) * (*gamma_e))); *beta_e += SMALL; // to prevent numerical problems for zero temperature } double sample_y(double Thetae) { double S_3, pi_3, pi_4, pi_5, pi_6, y, x1, x2, x, prob, num, den; pi_3 = sqrt(M_PI) / 4.; pi_4 = sqrt(0.5 * Thetae) / 2.; pi_5 = 3. * sqrt(M_PI) * Thetae / 8.; pi_6 = Thetae * sqrt(0.5 * Thetae); S_3 = pi_3 + pi_4 + pi_5 + pi_6; pi_3 /= S_3; pi_4 /= S_3; pi_5 /= S_3; pi_6 /= S_3; int max_samp = 100000; int n = 0; do { n++; x1 = get_rand(); if (x1 < pi_3) { x = get_chisq(3); } else if (x1 < pi_3 + pi_4) { x = get_chisq(4); } else if (x1 < pi_3 + pi_4 + pi_5) { x = get_chisq(5); } else { x = get_chisq(6); } // Translate between Canfield et al. and standard chisq distribution y = sqrt(x / 2); x2 = get_rand(); num = sqrt(1. + 0.5 * Thetae * y * y); den = 1. + y * sqrt(0.5 * Thetae); prob = num / den; } while (x2 >= prob && n < max_samp); if (n >= max_samp) { fprintf(stderr, "FAILED TO SAMPLE Y! Thetae = %e\n", Thetae); exit(-1); } return y; } double sample_mu(double beta_e) { double mu, x1; x1 = get_rand(); mu = (1. - sqrt(1. + 2. * beta_e + beta_e * beta_e - 4. * beta_e * x1)) / beta_e; return mu; } /* * True total cross section * in rest frame of the scattering particle * Distinct from hot cross section, * which is looked up in total_cross_lkup */ double get_total_cross_section(double k, const struct of_microphysics *m, int type, int interaction, int normalized) { #if RADIATION == RADTYPE_LIGHT { double sigma = hc_klein_nishina(k, 0); if (!normalized) sigma *= THOMSON; return sigma; } #else // RADIATION == RADTYPE_NEUTRINOS { #if MULTISCATT_TEST { double sigma = hc_flat(k, 0); if (!normalized) { int i = interaction; sigma *= (2 * 2 * i + 1) * NUSIGMA0 * pow(ms_theta_nu0, 2.0) / (4); } return sigma; } #else // Normal neutrino scattering { // TODO: doesn't work with electrons double sigma = hc_quad(k, 0); if (normalized) { return sigma / hc_quad_max(); } return nu_cross_factor(sigma, type, interaction, m); } #endif // multiscatt test? } #endif // RADTYPE_NEUTRINOS } void sample_scattered_rad(double k[NDIM], double p[NDIM], double kp[NDIM], const struct of_microphysics *m, int type, int interaction) { double ke[4], kpe[4]; double k0p; double n0x, n0y, n0z, n0dotv0, v0x, v0y, v0z, v1x, v1y, v1z, v2x, v2y, v2z, v1, dir1, dir2, dir3; double cth, sth, phi, cphi, sphi; boost(k, p, ke); sample_cross_section(ke[0], &k0p, &cth, m, type, interaction); sth = sqrt(fabs(1. - cth * cth)); // Unit vector 1 for scattering coordinate system is oriented along initial // photon wavevector // Explicitly compute kemag instead of using ke[0] to ensure that photon is // created normalized and doesn't inherit the light cone errors from the // original photon double kemag = sqrt(ke[1] * ke[1] + ke[2] * ke[2] + ke[3] * ke[3]); v0x = ke[1] / kemag; v0y = ke[2] / kemag; v0z = ke[3] / kemag; // Randomly pick zero-angle for scattering coordinate system. get_ran_dir_3d(&n0x, &n0y, &n0z); n0dotv0 = v0x * n0x + v0y * n0y + v0z * n0z; // Unit vector 2 v1x = n0x - (n0dotv0)*v0x; v1y = n0y - (n0dotv0)*v0y; v1z = n0z - (n0dotv0)*v0z; v1 = sqrt(v1x * v1x + v1y * v1y + v1z * v1z); v1x /= v1; v1y /= v1; v1z /= v1; // Find one more unit vector using cross product; automatically normalized v2x = v0y * v1z - v0z * v1y; v2y = v0z * v1x - v0x * v1z; v2z = v0x * v1y - v0y * v1x; // Resolve new momentum vector along unit vectors // Create a four-vector p // Solve for orientation of scattered photon // Find phi for new photon phi = 2. * M_PI * get_rand(); sphi = sin(phi); cphi = cos(phi); p[1] *= -1.; p[2] *= -1.; p[3] *= -1.; dir1 = cth * v0x + sth * (cphi * v1x + sphi * v2x); dir2 = cth * v0y + sth * (cphi * v1y + sphi * v2y); dir3 = cth * v0z + sth * (cphi * v1z + sphi * v2z); kpe[0] = k0p; kpe[1] = k0p * dir1; kpe[2] = k0p * dir2; kpe[3] = k0p * dir3; // Transform k back to lab frame boost(kpe, p, kp); if (kp[0] < 0 || isnan(kp[0])) { fprintf(stderr, "in sample_scattered_photon:\n"); fprintf(stderr, "kp[0], kpe[0]: %g %g\n", kp[0], kpe[0]); fprintf(stderr, "kpe: %g %g %g %g\n", kpe[0], kpe[1], kpe[2], kpe[3]); fprintf(stderr, "k: %g %g %g %g\n", k[0], k[1], k[2], k[3]); fprintf(stderr, "p: %g %g %g %g\n", p[0], p[1], p[2], p[3]); fprintf(stderr, "kp: %g %g %g %g\n", kp[0], kp[1], kp[2], kp[3]); } } void boost(double v[NDIM], double u[NDIM], double vp[NDIM]) { double g, V, n1, n2, n3, gm1; g = u[0]; V = sqrt(fabs(1. - 1. / (g * g))); n1 = u[1] / (g * V + SMALL); n2 = u[2] / (g * V + SMALL); n3 = u[3] / (g * V + SMALL); gm1 = g - 1.; // Lorentz boost into frame u from lab frame vp[0] = u[0] * v[0] - (u[1]) * v[1] - (u[2]) * v[2] - (u[3]) * v[3]; vp[1] = -u[1] * v[0] + (1. + n1 * n1 * gm1) * v[1] + (n1 * n2 * gm1) * v[2] + (n1 * n3 * gm1) * v[3]; vp[2] = -u[2] * v[0] + (n2 * n1 * gm1) * v[1] + (1. + n2 * n2 * gm1) * v[2] + (n2 * n3 * gm1) * v[3]; vp[3] = -u[3] * v[0] + (n3 * n1 * gm1) * v[1] + (n3 * n2 * gm1) * v[2] + (1. + n3 * n3 * gm1) * v[3]; } void sample_cross_section(double k, double *k0p, double *cth, const struct of_microphysics *m, int type, int interaction) { #if RADIATION == RADTYPE_LIGHT { *k0p = sample_klein_nishina(k); *cth = 1. - 1. / (*k0p) + 1. / k; } #elif RADIATION == RADTYPE_NEUTRINOS { #if MULTISCATT_TEST { double xmax = ms_flat_max(m, type, interaction); rejection_sample(ms_flat, xmax, k, k0p, cth, m, type, interaction); } #else // Normal neutrino scattering { // TODO: doesn't work for electrons double xmax = nu_cross_max(m, type, interaction); rejection_sample(nu_cross, xmax, k, k0p, cth, m, type, interaction); } #endif // neutrino scattering } #endif // radiation type } double sample_klein_nishina(double k0) { double k0pmin, k0pmax, k0p_tent, x1; int n = 0; // A low efficiency sampling algorithm, particularly for large k0. Limiting // efficiency is log(2 k0)/(2 k0) k0pmin = k0 / (1. + 2. * k0); // at theta = Pi k0pmax = k0; // at theta = 0 do { // Tentative value k0p_tent = k0pmin + (k0pmax - k0pmin) * get_rand(); // Rejection sample in box of height = kn(kmin) x1 = 2. * (1. + 2. * k0 + 2. * k0 * k0) / (k0 * k0 * (1. + 2. * k0)); x1 *= get_rand(); n++; } while (x1 >= klein_nishina(k0, k0p_tent)); return k0p_tent; } double klein_nishina(double a, double ap) { double ch = 1. + 1. / a - 1. / ap; double kn = (a / ap + ap / a - 1. + ch * ch) / (a * a); return kn; } void init_all_hotcross() { #if RADIATION == RADTYPE_LIGHT { init_hc_table(hc_klein_nishina, table[0], HOTCROSS[0]); } #elif RADIATION == RADTYPE_NEUTRINOS { #if MULTISCATT_TEST { init_hc_table(hc_flat, table[0], HOTCROSS[0]); } #else // Normal neutrino scattering { init_hc_table(hc_quad, table[0], HOTCROSS[0]); } #endif // neutrino scattering type } #endif // RADIATION TYPE } void init_hc_table( hc_ftype f, double table[NW + 1][NT + 1], const char *hc_name) { int nread; double lw, lT; FILE * fp; MAXW = 100. * (HPL * numax) / (ME * CL * CL); dlw = log10(MAXW / MINW) / NW; dlT = log10(MAXT / MINT) / NT; lminw = log10(MINW); lmint = log10(MINT); // Create file if needed using IO proc if (mpi_io_proc()) { fp = fopen(hc_name, "r"); if (fp == NULL) { fprintf(stdout, "Making lookup table for %s cross section...\n", hc_name); #pragma omp parallel for collapse(2) for (int i = 0; i <= NW; i++) { for (int j = 0; j <= NT; j++) { lw = lminw + i * dlw; lT = lmint + j * dlT; table[i][j] = log10(total_cross_num(f, pow(10., lw), pow(10., lT))); if (isnan(table[i][j])) { fprintf(stderr, "NAN for %s cross section: %d %d %g %g\n", hc_name, i, j, lw, lT); exit(0); } } } fprintf(stdout, "Lookup table created.\n\n"); fprintf(stdout, "Writing lookup table to file...\n"); fp = fopen(hc_name, "w"); if (fp == NULL) { fprintf(stderr, "Couldn't write to file %s\n", hc_name); exit(0); } for (int i = 0; i <= NW; i++) { for (int j = 0; j <= NT; j++) { lw = lminw + i * dlw; lT = lmint + j * dlT; fprintf(fp, "%d %d %g %g %15.10g\n", i, j, lw, lT, table[i][j]); } } fprintf(stderr, "Lookup table written.\n\n"); } // fp == NULL fclose(fp); } // mpi_io_proc() mpi_barrier(); // Read lookup table with every MPI processor fp = fopen(hc_name, "r"); if (fp == NULL) { fprintf(stderr, "rank %i: file %s not found.\n", mpi_myrank(), hc_name); exit(-1); } for (int i = 0; i <= NW; i++) { for (int j = 0; j <= NT; j++) { nread = fscanf(fp, "%*d %*d %*f %*f %lf\n", &table[i][j]); if (isnan(table[i][j]) || nread != 1) { fprintf(stderr, "Error on table %s read: %d %d\n", hc_name, i, j); exit(0); } } } fclose(fp); } double interpolate_hc_table(double w, double thetae, hc_ftype f, double table[NW + 1][NT + 1], const char *hc_name) { int i, j; double lw, lT, di, dj, lcross; // DEBUG // double cross_section = RAD_SCATT_TYPES*NUSIGMA0; // return 0.1/(Rout_rad*L_unit*cross_section*Ne_unit); // if hotcross takes too long! #if TRUNCATE_HOTCROSS if (w <= MINW) w = MINW + fabs(0.01 * MINW); if (w >= MAXW) w = MAXW - fabs(0.01 * MAXW); if (thetae <= MINT) thetae = MINT + fabs(0.01 * MINT); if (thetae >= MAXT) thetae = MAXT - fabs(0.01 * MAXT); #endif // In-bounds for table if ((w > MINW && w < MAXW) && (thetae > MINT && thetae < MAXT)) { lw = log10(w); lT = log10(thetae); i = (int)((lw - lminw) / dlw); j = (int)((lT - lmint) / dlT); di = (lw - lminw) / dlw - i; dj = (lT - lmint) / dlT - j; lcross = (1. - di) * (1. - dj) * table[i][j] + di * (1. - dj) * table[i + 1][j] + (1. - di) * dj * table[i][j + 1] + di * dj * table[i + 1][j + 1]; if (isnan(lcross)) { fprintf(stderr, "NAN cross section %s: %g %g %d %d %g %g\n", hc_name, lw, lT, i, j, di, dj); } return pow(10., lcross); } fprintf(stderr, "Cross section %s out of bounds: %g [%g,%g] %g [%g,%g]\n", hc_name, w, MINW, MAXW, thetae, MINT, MAXT); return total_cross_num(f, w, thetae); } double total_cross_lkup( double w, int type, int interaction, const struct of_microphysics *m) { double thetae = scatterer_dimensionless_temp(type, interaction, m); #if RADIATION == RADTYPE_LIGHT { // Cold/low-energy: Use Thomson cross section if (w * thetae < 1.e-6) return (THOMSON); // Cold, but possible high-energy photon: use Klein-Nishina if (thetae < MINT) return (hc_klein_nishina(w, 0) * THOMSON); double sigma = interpolate_hc_table( w, thetae, hc_klein_nishina, table[0], HOTCROSS[0]); return THOMSON * sigma; } #elif RADIATION == RADTYPE_NEUTRINOS { if (thetae < MINT) { // easy zero-temperature limit return get_total_cross_section(w, m, type, interaction, 0); } #if MULTISCATT_TEST { double sigma = interpolate_hc_table(w, thetae, hc_flat, table[0], HOTCROSS[0]); return 4 * M_PI * sigma * ms_flat(w, 0, m, type, interaction) / hc_flat(w, 0); } #else // Normal neutrino scattering { if (type == NU_HEAVY && interaction == RSCATT_TYPE_E) { return 0.0; // heavy cannot scatter off of electrons } double sigma = interpolate_hc_table(w, thetae, hc_quad, table[0], HOTCROSS[0]); return nu_cross_factor(sigma, type, interaction, m); } #endif // neutrino scattering type } #endif // radiation type } double total_cross_num(hc_ftype f, double w, double thetae) { double dmue, dgammae, mue, gammae, maxwell, cross; if (isnan(w)) { fprintf(stderr, "NAN cross section: %g %g\n", w, thetae); return 0.; } // Check for easy limits #if RADIATION == RADTYPE_LIGHT { if (thetae < MINT && w < MINW) return 1.; if (thetae < MINT) return hc_klein_nishina(w, 0); } #endif dmue = DMUE; dgammae = thetae * DGAMMAE; // Integrate over mu_e and gamma_e, where mu_e is the cosine of the angle // between K and U_e, and the angle k is assumed to lie, wlog, along the z // z axis cross = 0.; for (mue = -1. + 0.5 * dmue; mue < 1.; mue += dmue) for (gammae = 1. + 0.5 * dgammae; gammae < 1. + MAXGAMMA * thetae; gammae += dgammae) { maxwell = 0.5 * dNdgammae(thetae, gammae); cross += dmue * dgammae * boostcross(f, w, mue, gammae) * maxwell; if (isnan(cross)) { fprintf(stderr, "NAN cross section: %g %g %g %g %g %g\n", w, thetae, mue, gammae, dNdgammae(thetae, gammae), boostcross(f, w, mue, gammae)); } } return cross; } // Normalized (per unit proper electron number density) electron distribution double dNdgammae(double thetae, double gammae) { double K2f; if (thetae > 1.e-2) { K2f = gsl_sf_bessel_Kn(2, 1. / thetae) * exp(1. / thetae); } else { K2f = sqrt(M_PI * thetae / 2.) + 15. / 8. * sqrt(M_PI / 2.) * pow(thetae, 1.5) + 105. / 128. * sqrt(M_PI / 2.) * pow(thetae, 2.5) - 315. / 1024. * sqrt(M_PI / 2.) * pow(thetae, 3.5); } return (gammae * sqrt(gammae * gammae - 1.) / (thetae * K2f)) * exp(-(gammae - 1.) / thetae); } double boostcross(hc_ftype f, double w, double mue, double gammae) { double we, boostcross, v; // Energy in electron rest frame v = sqrt(gammae * gammae - 1.) / gammae; we = w * gammae * (1. - mue * v); boostcross = f(we, mue) * (1. - mue * v); #if RADIATION == RADTYPE_LIGHT if (boostcross > 2) { fprintf(stderr, "w, mue, gammae: %g %g %g\n" "v, we, boostcross: %g %g %g\n" "kn: %g %g %g\n", w, mue, gammae, v, we, boostcross, v, we, boostcross); exit(1); } #endif if (isnan(boostcross)) { fprintf(stderr, "isnan: %g %g %g\n", w, mue, gammae); return 0.; } return boostcross; } /* * TODO: for elastic scattering, we could * inverse-transform sample for significant speedup */ void rejection_sample(dsdom_ftype f, double xmax, double k, double *k0p, double *cth, const struct of_microphysics *m, int type, int interaction) { double mu, x, sigma; do { mu = 2 * get_rand() - 1.; x = get_rand() * xmax; sigma = f(k, mu, m, type, interaction); } while (x >= sigma); *k0p = k; // because scattering is elastic *cth = mu; } double hc_klein_nishina(double we, double mue) { double sigma; if (we < 1.e-3) { sigma = 1. - 2. * we + 5.2 * we * we - 13.3 * we * we * we + 1144 * we * we * we * we / 35.; } else { sigma = (3. / 4.) * (2. / (we * we) + (1. / (2. * we) - (1. + we) / (we * we * we)) * log(1. + 2. * we) + (1. + we) / ((1. + 2. * we) * (1. + 2. * we))); } return sigma; } #if RADIATION == RADTYPE_NEUTRINOS #if MULTISCATT_TEST double hc_flat(double we, double mue) { return 1.0; } double ms_flat(double w, double mu, const struct of_microphysics *m, int type, int interaction) { int i = interaction; double sigma = hc_flat(w, 0); sigma *= (2 * 2 * i + 1) * NUSIGMA0 * pow(ms_theta_nu0, 2.0) / (16 * M_PI); sigma *= (1 + ms_delta0 * pow(mu, 2 * i + 1)); return sigma; } double ms_flat_max(const struct of_microphysics *m, int type, int interaction) { if (ms_delta0 > 0) return ms_flat(1, 1, m, type, interaction); if (ms_delta0 < 0) return ms_flat(1, -1, m, type, interaction); return ms_flat(1, 0, m, type, interaction); } #else // not multiscatt test double nu_cross(double w, double mu, const struct of_microphysics *m, int type, int interaction) { // TODO: doesn't work for electrons double sigma = hc_quad(w, mu); double delta = nu_cross_delta(type, interaction); sigma *= nu_cross_factor(sigma, type, interaction, m); sigma /= 4. * M_PI; sigma *= 1 + delta * mu; return sigma; } double nu_cross_max( const struct of_microphysics *m, int type, int interaction) { // TODO: doesn't work for electrons double sigma = hc_quad_max(); double delta = nu_cross_delta(type, interaction); sigma = nu_cross_factor(sigma, type, interaction, m); sigma /= 4. * M_PI; sigma *= 1 + fabs(delta); return sigma; } // Burrows, Reddy, Thomson, arXiv:astro-ph/0404432 double total_cross_ions(double sigma_hc, double A, double Z) { const double CFF = 1.; // form factor const double CLOS = 1.; // electron polarization const double Sion = 1.; // ion screening double W = 1. - 2. * (Z / A) * (1. - 2. * S2THW); double out = ((1. / 16.) * NUSIGMA0 * sigma_hc * A * A * (W * CFF + CLOS) * (W * CFF + CLOS) * Sion); return out; } // Burrows, Reddy, Thomson, arXiv:astro-ph/0404432 double nu_cross_delta(int type, int interaction) { // heavy cannot scatter off of electrons if (type == NU_HEAVY && interaction == RSCATT_TYPE_E) return 0.0; if (interaction == RSCATT_TYPE_P) { double Cpv = 0.5 + 2.0 * S2THW; double Cpa = 0.5; double num = (Cpv - 1) * (Cpv - 1) - GA2 * (Cpa - 1) * (Cpa - 1); double den = (Cpv - 1) * (Cpv - 1) + 3 * GA2 * (Cpa - 1) * (Cpa - 1); return num / den; } else if (interaction == RSCATT_TYPE_N) { return (1 - GA2) / (1 + 3 * GA2); } else if (interaction == RSCATT_TYPE_A || interaction == RSCATT_TYPE_ALPHA) { return 1.0; } else { fprintf(stderr, "total_cross_lkup: cross not implemented\n"); exit(1); } } // Burrows, Reddy, Thomson, arXiv:astro-ph/0404432 double nu_cross_factor( double sigma, int type, int interaction, const struct of_microphysics *m) { // heavy cannot scatter off of electrons if (type == NU_HEAVY && interaction == RSCATT_TYPE_E) return 0.0; if (interaction == RSCATT_TYPE_P) { return 0.25 * NUSIGMA0 * sigma * (4. * S4THW - 2. * S2THW + 0.25 * (1 + 3. * GA2)); } else if (interaction == RSCATT_TYPE_N) { return (NUSIGMA0 / 4.) * sigma * (1 + 3 * GA2) / 4.; } else if (interaction == RSCATT_TYPE_A) { return total_cross_ions(sigma, m->Abar, m->Zbar); } else if (interaction == RSCATT_TYPE_ALPHA) { return total_cross_ions(sigma, 4.0, 2.0); } else { // TODO: add neutrino-electron scattering fprintf(stderr, "total_cross_lkup: cross not implemented\n"); exit(1); } } double hc_quad(double we, double mue) { // we in units of hnu/Mec^2 double nu_maxw = (HPL * numax) / (ME * CL * CL); if (we >= nu_maxw) we = nu_maxw; return we * we; } double hc_quad_max() { double nu_maxw = (HPL * numax) / (ME * CL * CL); return hc_quad(nu_maxw, 0); } #endif // MULTISCATT_TEST #endif // Neutrinos #endif // RADIATION
sgd.c
/****************************************************************************** * INCLUDES *****************************************************************************/ #include "completion.h" #include "../csf.h" #include "../reorder.h" #include "../util.h" #include "../thd_info.h" #include "../io.h" #include <math.h> #define USE_CSF_SGD 1 /****************************************************************************** * PRIVATE FUNCTIONS *****************************************************************************/ /** * @brief Update a three-mode model based on a given observation. * * @param train The training data. * @param nnz_index The index of the observation to update from. * @param model The model to update. * @param ws Workspace to use. */ static inline void p_update_model3( sptensor_t const * const train, idx_t const nnz_index, tc_model * const model, tc_ws * const ws) { idx_t const nfactors = model->rank; idx_t const x = nnz_index; assert(train->nmodes == 3); idx_t * * const ind = train->ind; val_t * const restrict arow = model->factors[0] + (ind[0][x] * nfactors); val_t * const restrict brow = model->factors[1] + (ind[1][x] * nfactors); val_t * const restrict crow = model->factors[2] + (ind[2][x] * nfactors); /* predict value */ val_t predicted = 0; for(idx_t f=0; f < nfactors; ++f) { predicted += arow[f] * brow[f] * crow[f]; } val_t const loss = train->vals[x] - predicted; val_t const rate = ws->learn_rate; val_t const * const restrict reg = ws->regularization; /* update rows */ for(idx_t f=0; f < nfactors; ++f) { val_t const moda = (loss * brow[f] * crow[f]) - (reg[0] * arow[f]); val_t const modb = (loss * arow[f] * crow[f]) - (reg[1] * brow[f]); val_t const modc = (loss * arow[f] * brow[f]) - (reg[2] * crow[f]); arow[f] += rate * moda; brow[f] += rate * modb; crow[f] += rate * modc; } } /** * @brief Update a three-mode model based on the i-th node of a CSF tensor. * * @param train The training data (in CSf format). * @param i Which node to process. * @param model The model to update. * @param ws Workspace to use. */ static inline void p_update_model_csf3( splatt_csf const * const train, idx_t const i, tc_model * const model, tc_ws * const ws) { idx_t const nfactors = model->rank; csf_sparsity const * const pt = train->pt; assert(model->nmodes == 3); assert(train->ntiles == 1); /* sparsity structure */ idx_t const * const restrict sptr = pt->fptr[0]; idx_t const * const restrict fptr = pt->fptr[1]; idx_t const * const restrict fids = pt->fids[1]; idx_t const * const restrict inds = pt->fids[2]; /* current model */ val_t const * const restrict vals = pt->vals; val_t * const restrict avals = model->factors[train->dim_perm[0]]; val_t * const restrict bvals = model->factors[train->dim_perm[1]]; val_t * const restrict cvals = model->factors[train->dim_perm[2]]; val_t const rate = ws->learn_rate; val_t const areg = ws->regularization[train->dim_perm[0]]; val_t const breg = ws->regularization[train->dim_perm[1]]; val_t const creg = ws->regularization[train->dim_perm[2]]; /* grab the top-level row */ idx_t const a_id = (pt->fids[0] == NULL) ? i : pt->fids[0][i]; val_t * const restrict arow = avals + (a_id * nfactors); /* process each fiber */ for(idx_t fib=sptr[i]; fib < sptr[i+1]; ++fib) { val_t * const restrict brow = bvals + (fids[fib] * nfactors); /* foreach nnz in fiber */ for(idx_t jj=fptr[fib]; jj < fptr[fib+1]; ++jj) { val_t * const restrict crow = cvals + (inds[jj] * nfactors); /* compute the loss */ val_t loss = vals[jj]; for(idx_t f=0; f < nfactors; ++f) { loss -= arow[f] * brow[f] * crow[f]; } /* update model */ for(idx_t f=0; f < nfactors; ++f) { /* compute all modifications FIRST since we are updating all rows */ val_t const moda = (loss * brow[f] * crow[f]) - (areg * arow[f]); val_t const modb = (loss * arow[f] * crow[f]) - (breg * brow[f]); val_t const modc = (loss * arow[f] * brow[f]) - (creg * crow[f]); arow[f] += rate * moda; brow[f] += rate * modb; crow[f] += rate * modc; } } } /* foreach fiber */ } /** * @brief Update a model based on a given observation. * * @param train The training data. * @param nnz_index The index of the observation to update from. * @param model The model to update. * @param ws Workspace to use. */ static void p_update_model( sptensor_t const * const train, idx_t const nnz_index, tc_model * const model, tc_ws * const ws) { idx_t const nmodes = train->nmodes; if(nmodes == 3) { p_update_model3(train, nnz_index, model, ws); return; } idx_t const nfactors = model->rank; idx_t const x = nnz_index; val_t * const restrict buffer = ws->thds[splatt_omp_get_thread_num()].scratch[0]; /* compute the error */ val_t const err = train->vals[x] - tc_predict_val(model, train, x, buffer); idx_t * * const ind = train->ind; /* update each of the factor (row-wise) */ for(idx_t m=0; m < nmodes; ++m) { /* first fill buffer with the Hadamard product of all rows but current */ idx_t moff = (m + 1) % nmodes; val_t const * const restrict init_row = model->factors[moff] + (ind[moff][x] * nfactors); for(idx_t f=0; f < nfactors; ++f) { buffer[f] = init_row[f]; } for(moff = 2; moff < nmodes; ++moff) { idx_t const madj = (m + moff) % nmodes; val_t const * const restrict row = model->factors[madj] + (ind[madj][x] * nfactors); for(idx_t f=0; f < nfactors; ++f) { buffer[f] *= row[f]; } } /* now actually update the row */ val_t * const restrict update_row = model->factors[m] + (ind[m][x] * nfactors); val_t const reg = ws->regularization[m]; val_t const rate = ws->learn_rate; for(idx_t f=0; f < nfactors; ++f) { update_row[f] += rate * ((err * buffer[f]) - (reg * update_row[f])); } } } /****************************************************************************** * PUBLIC FUNCTIONS *****************************************************************************/ void splatt_tc_sgd( sptensor_t * train, sptensor_t const * const validate, tc_model * const model, tc_ws * const ws) { idx_t const nfactors = model->rank; #if USE_CSF_SGD /* convert training data to a single CSF */ double * opts = splatt_default_opts(); opts[SPLATT_OPTION_TILE] = SPLATT_NOTILE; splatt_csf * csf = splatt_malloc(sizeof(*csf)); csf_alloc_mode(train, CSF_SORTED_BIGFIRST, 0, csf, opts); assert(csf->ntiles == 1); idx_t const nslices = csf[0].pt->nfibs[0]; idx_t * perm_i = splatt_malloc(nslices * sizeof(*perm_i)); for(idx_t n=0; n < nslices; ++n) { perm_i[n] = n; } #else /* initialize perm */ idx_t * perm = splatt_malloc(train->nnz * sizeof(*perm)); for(idx_t n=0; n < train->nnz; ++n) { perm[n] = n; } #endif val_t loss = tc_loss_sq(train, model, ws); val_t frobsq = tc_frob_sq(model, ws); tc_converge(train, validate, model, loss, frobsq, 0, ws); /* for bold driver */ val_t obj = loss + frobsq; val_t prev_obj = obj; timer_start(&ws->tc_time); /* foreach epoch */ for(idx_t e=1; e < ws->max_its+1; ++e) { /* update model from all training observations */ #if USE_CSF_SGD shuffle_idx(perm_i, nslices); #pragma omp parallel for schedule(dynamic, 16) for(idx_t i=0; i < nslices; ++i) { p_update_model_csf3(csf, perm_i[i], model, ws); } #else shuffle_idx(perm, train->nnz); #pragma omp parallel for schedule(static, 1) for(idx_t n=0; n < train->nnz; ++n) { p_update_model(train, perm[n], model, ws); } #endif /* compute RMSE and adjust learning rate */ loss = tc_loss_sq(train, model, ws); frobsq = tc_frob_sq(model, ws); obj = loss + frobsq; if(tc_converge(train, validate, model, loss, frobsq, e, ws)) { break; } /* bold driver */ if(e > 1) { if(obj < prev_obj) { ws->learn_rate *= 1.05; } else { ws->learn_rate *= 0.50; } } prev_obj = obj; } #if USE_CSF_SGD splatt_free(perm_i); csf_free_mode(csf); splatt_free(csf); splatt_free_opts(opts); #else splatt_free(perm); #endif }
GB_binop__max_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__max_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__max_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__max_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__max_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__max_uint32) // A*D function (colscale): GB (_AxD__max_uint32) // D*A function (rowscale): GB (_DxB__max_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__max_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__max_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__max_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__max_uint32) // C=scalar+B GB (_bind1st__max_uint32) // C=scalar+B' GB (_bind1st_tran__max_uint32) // C=A+scalar GB (_bind2nd__max_uint32) // C=A'+scalar GB (_bind2nd_tran__max_uint32) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = GB_IMAX (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMAX (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MAX || GxB_NO_UINT32 || GxB_NO_MAX_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__max_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__max_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__max_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__max_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__max_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__max_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__max_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__max_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__max_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__max_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__max_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__max_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMAX (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__max_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMAX (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMAX (x, aij) ; \ } GrB_Info GB (_bind1st_tran__max_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMAX (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__max_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
prop2DAcoIsoDenQ_DEO2_FDTD.h
#ifndef PROP2DACOISODENQ_DEO2_FDTD_H #define PROP2DACOISODENQ_DEO2_FDTD_H #include <omp.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <fftw3.h> #include <complex> #include "propagatorStaticFunctions.h" #define MIN(x,y) ((x)<(y)?(x):(y)) class Prop2DAcoIsoDenQ_DEO2_FDTD { public: const bool _freeSurface; const long _nbx, _nbz, _nthread, _nx, _nz, _nsponge; const float _dx, _dz, _dt; const float _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz; float * __restrict__ _v = NULL; float * __restrict__ _b = NULL; float * __restrict__ _dtOmegaInvQ = NULL; float * __restrict__ _pSpace = NULL; float * __restrict__ _tmpPx1 = NULL; float * __restrict__ _tmpPz1 = NULL; float * __restrict__ _tmpPx2 = NULL; float * __restrict__ _tmpPz2 = NULL; float * _pOld = NULL; float * _pCur = NULL; Prop2DAcoIsoDenQ_DEO2_FDTD( bool freeSurface, long nthread, long nx, long nz, long nsponge, float dx, float dz, float dt, const long nbx, const long nbz) : _freeSurface(freeSurface), _nthread(nthread), _nx(nx), _nz(nz), _nsponge(nsponge), _nbx(nbx), _nbz(nbz), _dx(dx), _dz(dz), _dt(dt), _c8_1(+1225.0 / 1024.0), _c8_2(-245.0 / 3072.0), _c8_3(+49.0 / 5120.0), _c8_4(-5.0 / 7168.0), _invDx(1.0 / _dx), _invDz(1.0 / _dz) { // Allocate arrays _v = new float[_nx * _nz]; _b = new float[_nx * _nz]; _dtOmegaInvQ = new float[_nx * _nz]; _pSpace = new float[_nx * _nz]; _tmpPx1 = new float[_nx * _nz]; _tmpPz1 = new float[_nx * _nz]; _tmpPx2 = new float[_nx * _nz]; _tmpPz2 = new float[_nx * _nz]; _pOld = new float[_nx * _nz]; _pCur = new float[_nx * _nz]; numaFirstTouch(_nx, _nz, _nthread, _v, _b, _dtOmegaInvQ, _pSpace, _tmpPx1, _tmpPz1, _tmpPx2, _tmpPz2, _pOld, _pCur, _nbx, _nbz); } #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void numaFirstTouch( const long nx, const long nz, const long nthread, float * __restrict__ v, float * __restrict__ b, float * __restrict__ dtOmegaInvQ, float * __restrict__ pSpace, float * __restrict__ tmpPx1, float * __restrict__ tmpPz1, float * __restrict__ tmpPx2, float * __restrict__ tmpPz2, float * __restrict__ pOld, float * __restrict__ pCur, const long BX_2D, const long BZ_2D) { const long nx4 = nx - 4; const long nz4 = nz - 4; #pragma omp parallel for collapse(2) num_threads(nthread) schedule(static) for (long bx = 4; bx < nx4; bx += BX_2D) { for (long bz = 4; bz < nz4; bz += BZ_2D) { const long kxmax = MIN(bx + BX_2D, nx4); const long kzmax = MIN(bz + BZ_2D, nz4); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; v[k] = 0; b[k] = 0; dtOmegaInvQ[k] = 0; pSpace[k] = 0; tmpPx1[k] = 0; tmpPz1[k] = 0; tmpPx2[k] = 0; tmpPz2[k] = 0; pOld[k] = 0; pCur[k] = 0; } } } } // zero annulus #pragma omp parallel for num_threads(nthread) schedule(static) for (long kz = 0; kz < 4; kz++) { #pragma omp simd for (long kx = 0; kx < nx; kx++) { const long k = kx * _nz + kz; v[k] = b[k] = dtOmegaInvQ[k] = tmpPx1[k] = tmpPz1[k] = tmpPx2[k] = tmpPz2[k] = pOld[k] = pCur[k] = 0; } } #pragma omp parallel for num_threads(nthread) schedule(static) for (long kz = nz4; kz < nz; kz++) { #pragma omp simd for (long kx = 0; kx < nx; kx++) { const long k = kx * _nz + kz; v[k] = b[k] = dtOmegaInvQ[k] = tmpPx1[k] = tmpPz1[k] = tmpPx2[k] = tmpPz2[k] = pOld[k] = pCur[k] = 0; } } #pragma omp parallel for num_threads(nthread) schedule(static) for (long kx = 0; kx < 4; kx++) { #pragma omp simd for (long kz = 0; kz < nz; kz++) { const long k = kx * _nz + kz; v[k] = b[k] = dtOmegaInvQ[k] = tmpPx1[k] = tmpPz1[k] = tmpPx2[k] = tmpPz2[k] = pOld[k] = pCur[k] = 0; } } #pragma omp parallel for num_threads(nthread) schedule(static) for (long kx = nx4; kx < nx; kx++) { #pragma omp simd for (long kz = 0; kz < nz; kz++) { const long k = kx * _nz + kz; v[k] = b[k] = dtOmegaInvQ[k] = tmpPx1[k] = tmpPz1[k] = tmpPx2[k] = tmpPz2[k] = pOld[k] = pCur[k] = 0; } } } ~Prop2DAcoIsoDenQ_DEO2_FDTD() { if (_v != NULL) delete [] _v; if (_b != NULL) delete [] _b; if (_dtOmegaInvQ != NULL) delete [] _dtOmegaInvQ; if (_pSpace != NULL) delete [] _pSpace; if (_tmpPx1 != NULL) delete [] _tmpPx1; if (_tmpPz1 != NULL) delete [] _tmpPz1; if (_tmpPx2 != NULL) delete [] _tmpPx2; if (_tmpPz2 != NULL) delete [] _tmpPz2; if (_pOld != NULL) delete [] _pOld; if (_pCur != NULL) delete [] _pCur; } #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif void info() { printf("\n"); printf("Prop2DAcoIsoDenQ_DEO2_FDTD\n"); printf(" nx,nz; %5ld %5ld\n", _nx, _nz); printf(" nthread,nsponge,fs; %5ld %5ld %5d\n", _nthread, _nsponge, _freeSurface); printf(" X min,max,inc; %+16.6f %+16.6f %+16.6f\n", 0.0, _dx * (_nx - 1), _dx); printf(" Z min,max,inc; %+16.6f %+16.6f %+16.6f\n", 0.0, _dz * (_nz - 1), _dz); } /** * Notes * - User must have called setupDtOmegaInvQ_2D to initialize the array _dtOmegaInvQ * - wavefield arrays are switched in this call * pCur -> pOld * pOld -> pCur */ #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void timeStep() { applyFirstDerivatives2D_PlusHalf_Sandwich( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _pCur, _pCur, _b, _tmpPx1, _tmpPz1, _nbx, _nbz); applyFirstDerivatives2D_MinusHalf_TimeUpdate_Nonlinear( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _dt, _tmpPx1, _tmpPz1, _v, _b, _dtOmegaInvQ, _pCur, _pSpace, _pOld, _nbx, _nbz); // swap pointers float *pswap = _pOld; _pOld = _pCur; _pCur = pswap; } /** * Scale spatial derivatives by v^2/b to make them temporal derivs */ #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void scaleSpatialDerivatives() { #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const float v2OverB = _v[k] * _v[k] / _b[k]; _pSpace[k] *= v2OverB; } } } } } /** * Add the Born source for velocity only model-space at the current time * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born source term will be injected into the _pCur array */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void forwardBornInjection_V(Type *dVel, Type *wavefieldDP) { #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type dV = dVel[k]; // const Type dt2v2OverB = _dt * _dt * V * V / B; // const Type factorV = 2 * B * dV / (V * V * V); const Type factor = 2 * _dt * _dt * dV / V; _pCur[k] += factor * wavefieldDP[k]; } } } } } /** * Add the Born source for buoyancy and velocity model-space at the current time * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born source term will be injected into the _pCur array * * TODO: if these second derivative call and following loop is expensive, * could consider fusing the two derivative loops with the final loop */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void forwardBornInjection_VB(Type *dVel, Type *dBuoy, Type *wavefieldP, Type *wavefieldDP) { applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, wavefieldP, wavefieldP, _tmpPx1, _tmpPz1, _nbx, _nbz); #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type dB = dBuoy[k]; _tmpPx2[k] = dB * _tmpPx1[k]; _tmpPz2[k] = dB * _tmpPz1[k]; } } } } applyFirstDerivatives2D_MinusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _tmpPx2, _tmpPz2, _tmpPx1, _tmpPz1, _nbx, _nbz); #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type dV = dVel[k]; const Type dB = dBuoy[k]; const Type V2 = V * V; const Type dt2v2OverB = _dt * _dt * V2 / B; // const Type factorV = 2 * B * dV / (V * V * V); // const Type factorB = - dB / (V * V); _pCur[k] += dt2v2OverB * (wavefieldDP[k] / V2 * (2 * B * dV / V - dB) + _tmpPx1[k] + _tmpPz1[k]); } } } } } /** * Add the Born source for buoyancy model-space at the current time * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born source term will be injected into the _pCur array * * TODO: if these second derivatice call and following loop is expensive, * could consider fusing the two derivative loops with the final loop */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void forwardBornInjection_B(Type *dBuoy, Type *wavefieldP, Type *wavefieldDP) { applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, wavefieldP, wavefieldP, _tmpPx1, _tmpPz1, _nbx, _nbz); #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type dB = dBuoy[k]; _tmpPx2[k] = dB * _tmpPx1[k]; _tmpPz2[k] = dB * _tmpPz1[k]; } } } } applyFirstDerivatives2D_MinusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _tmpPx2, _tmpPz2, _tmpPx1, _tmpPz1, _nbx, _nbz); #pragma omp parallel for collapse(2) num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type dB = dBuoy[k]; const Type V2 = V * V; const Type dt2v2OverB = _dt * _dt * V2 / B; const Type factorB = - dB / V2; _pCur[k] += dt2v2OverB * (wavefieldDP[k] * factorB + _tmpPx1[k] + _tmpPz1[k]); } } } } } /** * Accumulate the Born image term at the current time for velocity only model-space * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born image term will be accumulated iu the _dm array * * - velocity term: [+ 2B/V^3 LtP r ] * - buoyancy term: [- 1/V^2 LtP r - dx' P dx - dy' P dy - dz' P dz] * * TODO: if these adjoint accumulations are expensive, could consider fusing the * two derivative loops with the final loop */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void adjointBornAccumulation_V(Type *dVel, Type *wavefieldDP) { #pragma omp parallel for num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type factorV = + 2 * B / (V * V * V); dVel[k] += factorV * wavefieldDP[k] * _pOld[k]; } } } } } /** * Accumulate the Born image term at the current time for velocity and buoyancy model-space * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born image term will be accumulated iu the _dm array * * - velocity term: [+ 2B/V^3 LtP r ] * - buoyancy term: [- 1/V^2 LtP r - dx' P dx - dy' P dy - dz' P dz] */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void adjointBornAccumulation_VB(Type *dVel, Type *dBuoy, Type *wavefieldP, Type *wavefieldDP) { applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, wavefieldP, wavefieldP, _tmpPx1, _tmpPz1, _nbx, _nbz); applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _pOld, _pOld, _tmpPx2, _tmpPz2, _nbx, _nbz); #pragma omp parallel for num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type factorV = + 2 * B / (V * V * V); const Type factorB = - 1 / (V * V); dVel[k] += factorV * wavefieldDP[k] * _pOld[k]; dBuoy[k] += factorB * wavefieldDP[k] * _pOld[k] - _tmpPx1[k] * _tmpPx2[k] - _tmpPz1[k] * _tmpPz2[k]; } } } } } /** * Accumulate the Born image term at the current time for buoyancy only model-space * * User must have: * - called the nonlinear forward * - saved 2nd time derivative of pressure at corresponding time index in array dp2 * - Born image term will be accumulated iu the _dm array * * - velocity term: [+ 2B/V^3 LtP r ] * - buoyancy term: [- 1/V^2 LtP r - dx' P dx - dy' P dy - dz' P dz] */ template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void adjointBornAccumulation_B(Type *dBuoy, Type *wavefieldP, Type *wavefieldDP) { applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, wavefieldP, wavefieldP, _tmpPx1, _tmpPz1, _nbx, _nbz); applyFirstDerivatives2D_PlusHalf( _freeSurface, _nx, _nz, _nthread, _c8_1, _c8_2, _c8_3, _c8_4, _invDx, _invDz, _pOld, _pOld, _tmpPx2, _tmpPz2, _nbx, _nbz); #pragma omp parallel for num_threads(_nthread) schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { for (long bz = 0; bz < _nz; bz += _nbz) { const long kxmax = MIN(bx + _nbx, _nx); const long kzmax = MIN(bz + _nbz, _nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long k = kx * _nz + kz; const Type V = _v[k]; const Type B = _b[k]; const Type factorB = - 1 / (V * V); dBuoy[k] += factorB * wavefieldDP[k] * _pOld[k] - _tmpPx1[k] * _tmpPx2[k] - _tmpPz1[k] * _tmpPz2[k]; } } } } } /** * Apply Kz wavenumber filter for up/down wavefield seperation * Faqi, 2011, Geophysics https://library.seg.org/doi/full/10.1190/1.3533914 * * We handle the FWI and RTM imaging conditions with a condition inside the OMP loop * * Example Kz filtering with 8 samples * frequency | +0 | +1 | +2 | +3 | N | -3 | -2 | -1 | * original | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | * upgoing | 0 | X | X | X | 4 | 5 | 6 | 7 | * dngoing | 0 | 1 | 2 | 3 | 4 | X | X | X | */ #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline void adjointBornAccumulation_wavefieldsep(float *dVel, float *wavefieldDP, const long isFWI) { const long nfft = 2 * _nz; const float scale = 1.0f / (float)(nfft); // FWI: adj wavefield is dngoing // RTM: adj wavefield is upgoing const long kfft_adj = (isFWI) ? 0 : nfft / 2; std::complex<float> * __restrict__ tmp = new std::complex<float>[nfft]; fftwf_plan planForward = fftwf_plan_dft_1d(nfft, reinterpret_cast<fftwf_complex*>(tmp), reinterpret_cast<fftwf_complex*>(tmp), +1, FFTW_ESTIMATE); fftwf_plan planInverse = fftwf_plan_dft_1d(nfft, reinterpret_cast<fftwf_complex*>(tmp), reinterpret_cast<fftwf_complex*>(tmp), -1, FFTW_ESTIMATE); delete [] tmp; #pragma omp parallel num_threads(_nthread) { std::complex<float> * __restrict__ tmp_nlf = new std::complex<float>[nfft]; std::complex<float> * __restrict__ tmp_adj = new std::complex<float>[nfft]; #pragma omp for schedule(static) for (long bx = 0; bx < _nx; bx += _nbx) { const long kxmax = MIN(bx + _nbx, _nx); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kfft = 0; kfft < nfft; kfft++) { tmp_nlf[kfft] = 0; tmp_adj[kfft] = 0; } #pragma omp simd for (long kz = 0; kz < _nz; kz++) { const long k = kx * _nz + kz; tmp_nlf[kz] = scale * wavefieldDP[k]; tmp_adj[kz] = scale * _pOld[k]; } fftwf_execute_dft(planForward, reinterpret_cast<fftwf_complex*>(tmp_nlf), reinterpret_cast<fftwf_complex*>(tmp_nlf)); fftwf_execute_dft(planForward, reinterpret_cast<fftwf_complex*>(tmp_adj), reinterpret_cast<fftwf_complex*>(tmp_adj)); // upgoing: zero the positive frequencies, excluding Nyquist // dngoing: zero the negative frequencies, excluding Nyquist #pragma omp simd for (long k = 1; k < nfft / 2; k++) { tmp_nlf[nfft / 2 + k] = 0; tmp_adj[kfft_adj + k] = 0; } fftwf_execute_dft(planInverse, reinterpret_cast<fftwf_complex*>(tmp_nlf), reinterpret_cast<fftwf_complex*>(tmp_nlf)); fftwf_execute_dft(planInverse, reinterpret_cast<fftwf_complex*>(tmp_adj), reinterpret_cast<fftwf_complex*>(tmp_adj)); // Faqi eq 10 // Applied to FWI: [Sup * Rdn] // Applied to RTM: [Sup * Rup] #pragma omp simd for (long kz = 0; kz < _nz; kz++) { const long k = kx * _nz + kz; const float V = _v[k]; const float B = _b[k]; const float factor = 2 * B / (V * V * V); dVel[k] += factor * real(tmp_nlf[kz] * tmp_adj[kz]); } } // end loop over kx } // end loop over bx delete [] tmp_nlf; delete [] tmp_adj; } // end parallel region fftwf_destroy_plan(planForward); fftwf_destroy_plan(planInverse); } template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline static void applyFirstDerivatives2D_PlusHalf_Sandwich( const long freeSurface, const long nx, const long nz, const long nthread, const Type c8_1, const Type c8_2, const Type c8_3, const Type c8_4, const Type invDx, const Type invDz, const Type * __restrict__ const inPX, const Type * __restrict__ const inPZ, const Type * __restrict__ const fieldBuoy, Type * __restrict__ tmpPX, Type * __restrict__ tmpPZ, const long BX_2D, const long BZ_2D) { // zero output arrays #pragma omp parallel for collapse(2) num_threads(nthread) schedule(static) for (long bx = 0; bx < nx; bx += BX_2D) { for (long bz = 0; bz < nz; bz += BZ_2D) { const long kxmax = MIN(bx + BX_2D - 1, nx); const long kzmax = MIN(bz + BZ_2D - 1, nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { long k = kx * nz + kz; tmpPX[k] = 0; tmpPZ[k] = 0; } } } } const long nx4 = nx - 4; const long nz4 = nz - 4; // interior #pragma omp parallel for collapse(2) num_threads(nthread) schedule(static) for (long bx = 4; bx < nx4; bx += BX_2D) { for (long bz = 4; bz < nz4; bz += BZ_2D) { /* cache blocking */ const long kxmax = MIN(bx + BX_2D, nx4); const long kzmax = MIN(bz + BZ_2D, nz4); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const long kxnz = kx * nz; const long k = kxnz + kz; const Type stencilDPx = c8_1 * (- inPX[(kx+0) * nz + kz] + inPX[(kx+1) * nz + kz]) + c8_2 * (- inPX[(kx-1) * nz + kz] + inPX[(kx+2) * nz + kz]) + c8_3 * (- inPX[(kx-2) * nz + kz] + inPX[(kx+3) * nz + kz]) + c8_4 * (- inPX[(kx-3) * nz + kz] + inPX[(kx+4) * nz + kz]); const Type stencilDPz = c8_1 * (- inPZ[kxnz + (kz+0)] + inPZ[kxnz + (kz+1)]) + c8_2 * (- inPZ[kxnz + (kz-1)] + inPZ[kxnz + (kz+2)]) + c8_3 * (- inPZ[kxnz + (kz-2)] + inPZ[kxnz + (kz+3)]) + c8_4 * (- inPZ[kxnz + (kz-3)] + inPZ[kxnz + (kz+4)]); const Type dPx = invDx * stencilDPx; const Type dPz = invDz * stencilDPz; const Type B = fieldBuoy[k]; tmpPX[k] = B * dPx; tmpPZ[k] = B * dPz; } } } } // roll on free surface if (freeSurface) { #pragma omp parallel for num_threads(nthread) schedule(static) for (long kx = 4; kx < nx4; kx++) { // kz = 0 -- 1/2 cells below free surface for Z derivative, at free surface for X/Y derivative // X and Y derivatives are identically zero // [kx * nz + 0] { const Type stencilDPz0 = c8_1 * (- inPZ[kx * nz + 0] + inPZ[kx * nz + 1]) + c8_2 * (+ inPZ[kx * nz + 1] + inPZ[kx * nz + 2]) + c8_3 * (+ inPZ[kx * nz + 2] + inPZ[kx * nz + 3]) + c8_4 * (+ inPZ[kx * nz + 3] + inPZ[kx * nz + 4]); const Type dPx = 0; const Type dPz = invDz * stencilDPz0; const long k = kx * nz + 0; const Type B = fieldBuoy[k]; tmpPX[k] = B * dPx; tmpPZ[k] = B * dPz; } // kz = 1 -- 1 1/2 cells below free surface for Z derivative, 1 cells below for X/Y derivative // [kx * nz + 1] { const Type stencilDPx1 = c8_1 * (- inPX[(kx+0) * nz + 1] + inPX[(kx+1) * nz + 1]) + c8_2 * (- inPX[(kx-1) * nz + 1] + inPX[(kx+2) * nz + 1]) + c8_3 * (- inPX[(kx-2) * nz + 1] + inPX[(kx+3) * nz + 1]) + c8_4 * (- inPX[(kx-3) * nz + 1] + inPX[(kx+4) * nz + 1]); const Type stencilDPz1 = c8_1 * (- inPZ[kx * nz + 1] + inPZ[kx * nz + 2]) + c8_2 * (- inPZ[kx * nz + 0] + inPZ[kx * nz + 3]) + c8_3 * (+ inPZ[kx * nz + 1] + inPZ[kx * nz + 4]) + c8_4 * (+ inPZ[kx * nz + 2] + inPZ[kx * nz + 5]); const Type dPx = invDx * stencilDPx1; const Type dPz = invDz * stencilDPz1; const long k = kx * nz + 1; const Type B = fieldBuoy[k]; tmpPX[k] = B * dPx; tmpPZ[k] = B * dPz; } // kz = 2 -- 2 1/2 cells below free surface for Z derivative, 2 cells below for X/Y derivative // [kx * nz + 2] { const Type stencilDPx2 = c8_1 * (- inPX[(kx+0) * nz + 2] + inPX[(kx+1) * nz + 2]) + c8_2 * (- inPX[(kx-1) * nz + 2] + inPX[(kx+2) * nz + 2]) + c8_3 * (- inPX[(kx-2) * nz + 2] + inPX[(kx+3) * nz + 2]) + c8_4 * (- inPX[(kx-3) * nz + 2] + inPX[(kx+4) * nz + 2]); const Type stencilDPz2 = c8_1 * (- inPZ[kx * nz + 2] + inPZ[kx * nz + 3]) + c8_2 * (- inPZ[kx * nz + 1] + inPZ[kx * nz + 4]) + c8_3 * (- inPZ[kx * nz + 0] + inPZ[kx * nz + 5]) + c8_4 * (+ inPZ[kx * nz + 1] + inPZ[kx * nz + 6]); const Type dPx = invDx * stencilDPx2; const Type dPz = invDz * stencilDPz2; const long k = kx * nz + 2; const Type B = fieldBuoy[k]; tmpPX[k] = B * dPx; tmpPZ[k] = B * dPz; } // kz = 3 -- 3 1/2 cells below free surface for Z derivative, 3 cells below for X/Y derivative // [kx * nz + 3] { const Type stencilDPx3 = c8_1 * (- inPX[(kx+0) * nz + 3] + inPX[(kx+1) * nz + 3]) + c8_2 * (- inPX[(kx-1) * nz + 3] + inPX[(kx+2) * nz + 3]) + c8_3 * (- inPX[(kx-2) * nz + 3] + inPX[(kx+3) * nz + 3]) + c8_4 * (- inPX[(kx-3) * nz + 3] + inPX[(kx+4) * nz + 3]); const Type stencilDPz3 = c8_1 * (- inPZ[kx * nz + 3] + inPZ[kx * nz + 4]) + c8_2 * (- inPZ[kx * nz + 2] + inPZ[kx * nz + 5]) + c8_3 * (- inPZ[kx * nz + 1] + inPZ[kx * nz + 6]) + c8_4 * (- inPZ[kx * nz + 0] + inPZ[kx * nz + 7]); const Type dPx = invDx * stencilDPx3; const Type dPz = invDz * stencilDPz3; const long k = kx * nz + 3; const Type B = fieldBuoy[k]; tmpPX[k] = B * dPx; tmpPZ[k] = B * dPz; } } } } template<class Type> #if defined(__FUNCTION_CLONES__) __attribute__((target_clones("avx","avx2","avx512f","default"))) #endif inline static void applyFirstDerivatives2D_MinusHalf_TimeUpdate_Nonlinear( const long freeSurface, const long nx, const long nz, const long nthread, const Type c8_1, const Type c8_2, const Type c8_3, const Type c8_4, const Type invDx, const Type invDz, const Type dtMod, const Type * __restrict__ const tmpPX, const Type * __restrict__ const tmpPZ, const Type * __restrict__ const fieldVel, const Type * __restrict__ const fieldBuoy, const Type * __restrict__ const dtOmegaInvQ, Type * __restrict__ pCur, Type * __restrict__ pSpace, Type * __restrict__ pOld, const long BX_2D, const long BZ_2D) { const long nx4 = nx - 4; const long nz4 = nz - 4; const Type dt2 = dtMod * dtMod; // zero output arrays #pragma omp parallel for collapse(2) num_threads(nthread) schedule(static) for (long bx = 0; bx < nx; bx += BX_2D) { for (long bz = 0; bz < nz; bz += BZ_2D) { const long kxmax = MIN(bx + BX_2D, nx); const long kzmax = MIN(bz + BZ_2D, nz); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { long k = kx * nz + kz; pSpace[k] = 0; } } } } // interior #pragma omp parallel for collapse(2) num_threads(nthread) schedule(static) for (long bx = 4; bx < nx4; bx += BX_2D) { for (long bz = 4; bz < nz4; bz += BZ_2D) { /* cache blocking */ const long kxmax = MIN(bx + BX_2D, nx4); const long kzmax = MIN(bz + BZ_2D, nz4); for (long kx = bx; kx < kxmax; kx++) { #pragma omp simd for (long kz = bz; kz < kzmax; kz++) { const Type stencilDPx = c8_1 * (- tmpPX[(kx-1) * nz + kz] + tmpPX[(kx+0) * nz + kz]) + c8_2 * (- tmpPX[(kx-2) * nz + kz] + tmpPX[(kx+1) * nz + kz]) + c8_3 * (- tmpPX[(kx-3) * nz + kz] + tmpPX[(kx+2) * nz + kz]) + c8_4 * (- tmpPX[(kx-4) * nz + kz] + tmpPX[(kx+3) * nz + kz]); const Type stencilDPz = c8_1 * (- tmpPZ[kx * nz + (kz-1)] + tmpPZ[kx * nz + (kz+0)]) + c8_2 * (- tmpPZ[kx * nz + (kz-2)] + tmpPZ[kx * nz + (kz+1)]) + c8_3 * (- tmpPZ[kx * nz + (kz-3)] + tmpPZ[kx * nz + (kz+2)]) + c8_4 * (- tmpPZ[kx * nz + (kz-4)] + tmpPZ[kx * nz + (kz+3)]); const Type dPX = invDx * stencilDPx; const Type dPZ = invDz * stencilDPz; const long k = kx * nz + kz; const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k]; pOld[k] = dt2V2_B * (dPX + dPZ) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k]; pSpace[k] = dPX + dPZ; } } } } // roll on free surface if (freeSurface) { #pragma omp parallel for num_threads(nthread) schedule(guided) for (long kx = 4; kx < nx4; kx++) { // kz = 0 -- at the free surface -- p = 0 // [kx * nz + 0] { const Type dPX = 0; const Type dPZ = 0; const long k = kx * nz + 0; const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k]; pOld[k] = dt2V2_B * (dPX + dPZ) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k]; pSpace[k] = dPX + dPZ; } // kz = 1 -- one cell below the free surface // [kx * nz + 1] { const Type stencilDPx1 = c8_1 * (- tmpPX[(kx-1) * nz + 1] + tmpPX[(kx+0) * nz + 1]) + c8_2 * (- tmpPX[(kx-2) * nz + 1] + tmpPX[(kx+1) * nz + 1]) + c8_3 * (- tmpPX[(kx-3) * nz + 1] + tmpPX[(kx+2) * nz + 1]) + c8_4 * (- tmpPX[(kx-4) * nz + 1] + tmpPX[(kx+3) * nz + 1]); const Type stencilDPz1 = c8_1 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 1]) + c8_2 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 2]) + c8_3 * (- tmpPZ[kx * nz + 1] + tmpPZ[kx * nz + 3]) + c8_4 * (- tmpPZ[kx * nz + 2] + tmpPZ[kx * nz + 4]); const Type dPx = invDx * stencilDPx1; const Type dPz = invDz * stencilDPz1; const long k = kx * nz + 1; const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k]; pOld[k] = dt2V2_B * (dPx + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k]; pSpace[k] = dPx + dPz; } // kz = 2 -- two cells below the free surface // [kx * nz + 2] { const Type stencilDPx2 = c8_1 * (- tmpPX[(kx-1) * nz + 2] + tmpPX[(kx+0) * nz + 2]) + c8_2 * (- tmpPX[(kx-2) * nz + 2] + tmpPX[(kx+1) * nz + 2]) + c8_3 * (- tmpPX[(kx-3) * nz + 2] + tmpPX[(kx+2) * nz + 2]) + c8_4 * (- tmpPX[(kx-4) * nz + 2] + tmpPX[(kx+3) * nz + 2]); const Type stencilDPz2 = c8_1 * (- tmpPZ[kx * nz + 1] + tmpPZ[kx * nz + 2]) + c8_2 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 3]) + c8_3 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 4]) + c8_4 * (- tmpPZ[kx * nz + 1] + tmpPZ[kx * nz + 5]); const Type dPx = invDx * stencilDPx2; const Type dPz = invDz * stencilDPz2; const long k = kx * nz + 2; const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k]; pOld[k] = dt2V2_B * (dPx + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k]; pSpace[k] = dPx + dPz; } // kz = 3 -- three cells below the free surface // [kx * nz + 3] { const Type stencilDPx3 = c8_1 * (- tmpPX[(kx-1) * nz + 3] + tmpPX[(kx+0) * nz + 3]) + c8_2 * (- tmpPX[(kx-2) * nz + 3] + tmpPX[(kx+1) * nz + 3]) + c8_3 * (- tmpPX[(kx-3) * nz + 3] + tmpPX[(kx+2) * nz + 3]) + c8_4 * (- tmpPX[(kx-4) * nz + 3] + tmpPX[(kx+3) * nz + 3]); const Type stencilDPz3 = c8_1 * (- tmpPZ[kx * nz + 2] + tmpPZ[kx * nz + 3]) + c8_2 * (- tmpPZ[kx * nz + 1] + tmpPZ[kx * nz + 4]) + c8_3 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 5]) + c8_4 * (- tmpPZ[kx * nz + 0] + tmpPZ[kx * nz + 6]); const Type dPx = invDx * stencilDPx3; const Type dPz = invDz * stencilDPz3; const long k = kx * nz + 3; const Type dt2V2_B = dt2 * fieldVel[k] * fieldVel[k] / fieldBuoy[k]; pOld[k] = dt2V2_B * (dPx + dPz) - dtOmegaInvQ[k] * (pCur[k] - pOld[k]) - pOld[k] + 2 * pCur[k]; pSpace[k] = dPx + dPz; } } } } }; #endif
multisort-omp-tree-optional.c
#include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <omp.h> #include <sys/time.h> double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%s: %0.6f\n",(_m), stamp); // N and MIN must be powers of 2 long N; long MIN_SORT_SIZE; long MIN_MERGE_SIZE; #define BLOCK_SIZE 1024L #define T int void basicsort(long n, T data[n]); void basicmerge(long n, T left[n], T right[n], T result[n*2], long start, long length); void merge(long n, T left[n], T right[n], T result[n*2], long start, long length) { if (length < MIN_MERGE_SIZE*2L) { // Base case basicmerge(n, left, right, result, start, length); } else { // Recursive decomposition #pragma omp task merge(n, left, right, result, start, length/2); #pragma omp task merge(n, left, right, result, start + length/2, length/2); } } void multisort(long n, T data[n], T tmp[n]) { if (n >= MIN_SORT_SIZE*4L) { // Recursive decomposition #pragma omp taskgroup { #pragma omp task multisort(n/4L, &data[0], &tmp[0]); #pragma omp task multisort(n/4L, &data[n/4L], &tmp[n/4L]); #pragma omp task multisort(n/4L, &data[n/2L], &tmp[n/2L]); #pragma omp task multisort(n/4L, &data[3L*n/4L], &tmp[3L*n/4L]); } #pragma omp taskgroup { #pragma omp task merge(n/4L, &data[0], &data[n/4L], &tmp[0], 0, n/2L); #pragma omp task merge(n/4L, &data[n/2L], &data[3L*n/4L], &tmp[n/2L], 0, n/2L); } merge(n/2L, &tmp[0], &tmp[n/2L], &data[0], 0, n); } else { // Base case basicsort(n, data); } } static void initialize(long length, T data[length]) { long i; #pragma omp parallel for for (i = 0; i < length; i++) { if (i==0) { data[i] = rand(); } else { data[i] = ((data[i-1]+1) * i * 104723L) % N; } } } static void clear(long length, T data[length]) { long i; #pragma omp parallel for for (i = 0; i < length; i++) { data[i] = 0; } } void check_sorted(long n, T data[n]) { int unsorted=0; for (int i=1; i<n; i++) if (data[i-1] > data[i]) unsorted++; if (unsorted > 0) printf ("\nERROR: data is NOT properly sorted. There are %d unordered positions\n\n",unsorted); else { // printf ("data IS ordered; "); } } int main(int argc, char **argv) { if (argc != 4) { fprintf(stderr, "Usage: %s <vector size in K> <sort size in K> <merge size in K>\n", argv[0]); return 1; } N = atol(argv[1]) * BLOCK_SIZE; MIN_SORT_SIZE = atol(argv[2]) * BLOCK_SIZE; MIN_MERGE_SIZE = atol(argv[3]) * BLOCK_SIZE; T *data = malloc(N*sizeof(T)); T *tmp = malloc(N*sizeof(T)); double stamp; START_COUNT_TIME; initialize(N, data); clear(N, tmp); STOP_COUNT_TIME("Initialization time in seconds"); START_COUNT_TIME; #pragma omp parallel #pragma omp single multisort(N, data, tmp); STOP_COUNT_TIME("Multisort execution time"); START_COUNT_TIME; check_sorted (N, data); STOP_COUNT_TIME("Check sorted data execution time"); fprintf(stdout, "Multisort program finished\n"); return 0; }
GB_unaryop__abs_uint8_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint8_uint32 // op(A') function: GB_tran__abs_uint8_uint32 // C type: uint8_t // A type: uint32_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_UINT8 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint8_uint32 ( uint8_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint8_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__second_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__second_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__second_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__second_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__second_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_uint8) // A*D function (colscale): GB (_AxD__second_uint8) // D*A function (rowscale): GB (_DxB__second_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__second_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__second_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_uint8) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint8_t // A type: uint8_t // A pattern? 1 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = bij #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SECOND || GxB_NO_UINT8 || GxB_NO_SECOND_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__second_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__second_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__second_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__second_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__second_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__second_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__second_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__second_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__second_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__second_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = y ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
test-zrocks-rw.c
#include <omp.h> #include <stdint.h> #include <stdlib.h> #include <libzrocks.h> #include <xztl.h> #include "CUnit/Basic.h" /* Write Buffer Size */ #define WRITE_TBUFFER_SZ (1024 * 1024 * 2) // 2 MB /* Number of buffers to write */ #define WRITE_COUNT (1024 * 2) // 4GB /* Parallel reads */ #define READ_NTHREADS 16 /* Sector to read per zone */ #define READ_ZONE_SEC (1024 * 16) /* Size of each read command */ #define READ_SZ (16 * ZNS_ALIGMENT) /* Read Iterations */ #define READ_ITERATIONS 16 static const char **devname; static uint64_t buffer_sz = WRITE_TBUFFER_SZ; static uint64_t nwrites = WRITE_COUNT; static uint64_t nthreads = READ_NTHREADS; static struct zrocks_map **map = NULL; static uint16_t *pieces = NULL; static void cunit_zrocksrw_assert_ptr (char *fn, void *ptr) { CU_ASSERT ((uint64_t) ptr != 0); if (!ptr) printf ("\n %s: ptr %p\n", fn, ptr); } static void cunit_zrocksrw_assert_int (char *fn, uint64_t status) { CU_ASSERT (status == 0); if (status) printf ("\n %s: %lx\n", fn, status); } static int cunit_zrocksrw_init (void) { return 0; } static int cunit_zrocksrw_exit (void) { return 0; } static void test_zrocksrw_init (void) { int ret; ret = zrocks_init (*devname); cunit_zrocksrw_assert_int ("zrocks_init", ret); } static void test_zrocksrw_exit (void) { zrocks_exit (); } static void test_zrockswr_fill_buffer (void *buf) { uint32_t byte; uint8_t value = 0x1; for (byte = 0; byte < buffer_sz; byte += 16) { value += 0x1; memset (buf, value, 16); } } static void test_zrocksrw_write (void) { void *buf[nthreads]; int bufi, th_i; struct timespec ts_s; struct timespec ts_e; uint64_t start_ns; uint64_t end_ns; double seconds, mb; for (bufi = 0; bufi < nthreads; bufi++) { buf[bufi] = zrocks_alloc (buffer_sz); cunit_zrocksrw_assert_ptr ("zrocksrw_write:alloc", buf[bufi]); if (!buf[bufi]) goto FREE; test_zrockswr_fill_buffer (buf[bufi]); } GET_NANOSECONDS(start_ns, ts_s); printf ("\n"); for (th_i = 0; th_i < nwrites; th_i++) { int ret; ret = zrocks_write (buf[th_i % nthreads], buffer_sz, 0, &map[th_i], &pieces[th_i]); printf ("\rWriting... %d/%lu", th_i, nwrites); cunit_zrocksrw_assert_int ("zrocksrw_write:write", ret); } GET_NANOSECONDS(end_ns, ts_e); seconds = (double) (end_ns - start_ns) / (double) 1000000000; mb = ( (double) nwrites * (double) buffer_sz ) / (double) 1024 / (double) 1024; printf ("\n"); printf ("Written data: %.2lf MB\n", mb); printf ("Elapsed time: %.4lf sec\n", seconds); printf ("Bandwidth: %.4lf MB/s\n", mb / seconds); FREE: while (bufi) { bufi--; zrocks_free (buf[bufi]); } } static void test_zrocksrw_read (void) { void *buf[nthreads]; uint64_t bufi, th_i, it; struct timespec ts_s; struct timespec ts_e; uint64_t start_ns; uint64_t end_ns; uint64_t read_gl[nthreads]; double seconds, mb; for (bufi = 0; bufi < nthreads; bufi++) { buf[bufi] = zrocks_alloc ((uint64_t) READ_ZONE_SEC * (uint64_t) ZNS_ALIGMENT); cunit_zrocksrw_assert_ptr ("zrocksrw_read:alloc", buf[bufi]); if (!buf[bufi]) goto FREE; } memset (read_gl, 0x0, sizeof(uint64_t) * nthreads); GET_NANOSECONDS(start_ns, ts_s); printf ("\n"); #pragma omp parallel for num_threads(nthreads) for (th_i = 0; th_i < nthreads; th_i++) { for (it = 0; it < READ_ITERATIONS; it++) { int ret; uint64_t offset, size, read; size = (uint64_t) READ_ZONE_SEC * (uint64_t) ZNS_ALIGMENT; offset = th_i * size; read = 0; while (size) { ret = zrocks_read (offset, (char *) buf[th_i] + read, READ_SZ); cunit_zrocksrw_assert_int ("zrocksrw_read:read", ret); offset += READ_SZ; read += READ_SZ; read_gl[th_i] += READ_SZ; size -= READ_SZ; } } } GET_NANOSECONDS(end_ns, ts_e); seconds = (double) (end_ns - start_ns) / (double) 1000000000; mb = 0; for (th_i = 0; th_i < nthreads; th_i++) mb += read_gl[th_i]; mb = mb / (double) 1024 / (double) 1024; printf ("\n"); printf ("Read data: %.2lf MB\n", mb); printf ("Elapsed time: %.4lf sec\n", seconds); printf ("Bandwidth: %.4lf MB/s\n", mb / seconds); FREE: while (bufi) { bufi--; zrocks_free (buf[bufi]); } } int main (int argc, const char **argv) { int failed; if (argc < 2 || !memcmp(argv[1], "--help\0", strlen(argv[1]))) { printf (" Usage: zrocks-test-rw <DEV_PATH> <NUM_THREADS> " "<BUFFER_SIZE_IN_MB> <NUM_OF_BUFFERS>\n"); printf ("\n e.g.: test-zrocks-rw liou:/dev/nvme0n2 8 2 1024\n"); printf (" This command uses 8 threads to read data and\n"); printf (" writes 2 GB to the device\n"); return 0; } if (argc >= 3) { nthreads = atoi(argv[2]); } if (argc >= 5) { buffer_sz = (1024 * 1024) * atoi(argv[3]); nwrites = atoi(argv[4]); } map = NULL; pieces = NULL; map = malloc(sizeof(struct zrocks_map *) * nwrites); pieces = malloc(sizeof(uint16_t) * nwrites); devname = &argv[1]; printf ("Device: %s\n", *devname); CU_pSuite pSuite = NULL; if (CUE_SUCCESS != CU_initialize_registry()) goto FREE; if (!map || !pieces) goto FREE; pSuite = CU_add_suite("Suite_zrocks_rw", cunit_zrocksrw_init, cunit_zrocksrw_exit); if (pSuite == NULL) { CU_cleanup_registry(); goto FREE; } if ((CU_add_test (pSuite, "Initialize ZRocks", test_zrocksrw_init) == NULL) || (CU_add_test (pSuite, "Write Bandwidth", test_zrocksrw_write) == NULL) || (CU_add_test (pSuite, "Read Bandwidth", test_zrocksrw_read) == NULL) || (CU_add_test (pSuite, "Close ZRocks", test_zrocksrw_exit) == NULL)) { failed = 1; CU_cleanup_registry(); goto FREE; } CU_basic_set_mode(CU_BRM_VERBOSE); CU_basic_run_tests(); failed = CU_get_number_of_tests_failed(); CU_cleanup_registry(); FREE: if (map) free(map); if (pieces) free(pieces); return failed; }
3d7pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 16; tile_size[1] = 16; tile_size[2] = 16; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 2) && (Nx >= 3) && (Ny >= 3) && (Nz >= 3)) { for (t1=-1;t1<=floord(Nt-2,8);t1++) { lbp=max(ceild(t1,2),ceild(16*t1-Nt+3,16)); ubp=min(floord(Nt+Nz-4,16),floord(8*t1+Nz+5,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-1,2)),ceild(16*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(8*t1+Ny+13,16)),floord(16*t2+Ny+12,16)),floord(16*t1-16*t2+Nz+Ny+11,16));t3++) { for (t4=max(max(max(0,ceild(t1-15,16)),ceild(16*t2-Nz-124,128)),ceild(16*t3-Ny-124,128));t4<=min(min(min(min(floord(Nt+Nx-4,128),floord(8*t1+Nx+13,128)),floord(16*t2+Nx+12,128)),floord(16*t3+Nx+12,128)),floord(16*t1-16*t2+Nz+Nx+11,128));t4++) { for (t5=max(max(max(max(max(0,8*t1),16*t1-16*t2+1),16*t2-Nz+2),16*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,8*t1+15),16*t2+14),16*t3+14),128*t4+126),16*t1-16*t2+Nz+13);t5++) { for (t6=max(max(16*t2,t5+1),-16*t1+16*t2+2*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(128*t4,t5+1); ubv=min(128*t4+127,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_unop__identity_int16_int8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int16_int8) // op(A') function: GB (_unop_tran__identity_int16_int8) // C type: int16_t // A type: int8_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = aij #define GB_ATYPE \ int8_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = (int16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = (int16_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_int8) ( int16_t *Cx, // Cx and Ax may be aliased const int8_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int8_t aij = Ax [p] ; int16_t z = (int16_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int8_t aij = Ax [p] ; int16_t z = (int16_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_int8) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
KDTree.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef _SPTAG_COMMON_KDTREE_H_ #define _SPTAG_COMMON_KDTREE_H_ #include <vector> #include <string> #include <shared_mutex> #include "../VectorIndex.h" #include "CommonUtils.h" #include "QueryResultSet.h" #include "WorkSpace.h" namespace SPTAG { namespace COMMON { // node type for storing KDT struct KDTNode { SizeType left; SizeType right; DimensionType split_dim; float split_value; }; class KDTree { public: KDTree() : m_iTreeNumber(2), m_numTopDimensionKDTSplit(5), m_iSamples(1000), m_lock(new std::shared_timed_mutex) {} KDTree(const KDTree& other) : m_iTreeNumber(other.m_iTreeNumber), m_numTopDimensionKDTSplit(other.m_numTopDimensionKDTSplit), m_iSamples(other.m_iSamples), m_lock(new std::shared_timed_mutex) {} ~KDTree() {} inline const KDTNode& operator[](SizeType index) const { return m_pTreeRoots[index]; } inline KDTNode& operator[](SizeType index) { return m_pTreeRoots[index]; } inline SizeType size() const { return (SizeType)m_pTreeRoots.size(); } inline SizeType sizePerTree() const { std::shared_lock<std::shared_timed_mutex> lock(*m_lock); return (SizeType)m_pTreeRoots.size() - m_pTreeStart.back(); } template <typename T> void Rebuild(const Dataset<T>& data, IAbortOperation* abort) { COMMON::KDTree newTrees(*this); newTrees.BuildTrees<T>(data, 1, nullptr, abort); std::unique_lock<std::shared_timed_mutex> lock(*m_lock); m_pTreeRoots.swap(newTrees.m_pTreeRoots); m_pTreeStart.swap(newTrees.m_pTreeStart); } template <typename T> void BuildTrees(const Dataset<T>& data, int numOfThreads, std::vector<SizeType>* indices = nullptr, IAbortOperation* abort = nullptr) { if (COMMON::DistanceUtils::Quantizer) { switch (COMMON::DistanceUtils::Quantizer->GetReconstructType()) { #define DefineVectorValueType(Name, Type) \ case VectorValueType::Name: \ BuildTreesCore<T, Type>(data, numOfThreads, indices, abort); \ break; #include "inc/Core/DefinitionList.h" #undef DefineVectorValueType default: break; } } else { BuildTreesCore<T, T>(data, numOfThreads, indices, abort); } } template <typename T, typename R> void BuildTreesCore(const Dataset<T>& data, int numOfThreads, std::vector<SizeType>* indices = nullptr, IAbortOperation* abort = nullptr) { std::vector<SizeType> localindices; if (indices == nullptr) { localindices.resize(data.R()); for (SizeType i = 0; i < localindices.size(); i++) localindices[i] = i; } else { localindices.assign(indices->begin(), indices->end()); } m_pTreeRoots.resize(m_iTreeNumber * localindices.size()); m_pTreeStart.resize(m_iTreeNumber, 0); #pragma omp parallel for num_threads(numOfThreads) for (int i = 0; i < m_iTreeNumber; i++) { if (abort && abort->ShouldAbort()) continue; Sleep(i * 100); std::srand(clock()); std::vector<SizeType> pindices(localindices.begin(), localindices.end()); std::random_shuffle(pindices.begin(), pindices.end()); m_pTreeStart[i] = i * (SizeType)pindices.size(); LOG(Helper::LogLevel::LL_Info, "Start to build KDTree %d\n", i + 1); SizeType iTreeSize = m_pTreeStart[i]; DivideTree<T, R>(data, pindices, 0, (SizeType)pindices.size() - 1, m_pTreeStart[i], iTreeSize, abort); LOG(Helper::LogLevel::LL_Info, "%d KDTree built, %d %zu\n", i + 1, iTreeSize - m_pTreeStart[i], pindices.size()); } } inline std::uint64_t BufferSize() const { return sizeof(int) + sizeof(SizeType) * m_iTreeNumber + sizeof(SizeType) + sizeof(KDTNode) * m_pTreeRoots.size(); } ErrorCode SaveTrees(std::shared_ptr<Helper::DiskPriorityIO> p_out) const { std::shared_lock<std::shared_timed_mutex> lock(*m_lock); IOBINARY(p_out, WriteBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber); IOBINARY(p_out, WriteBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data()); SizeType treeNodeSize = (SizeType)m_pTreeRoots.size(); IOBINARY(p_out, WriteBinary, sizeof(treeNodeSize), (char*)&treeNodeSize); IOBINARY(p_out, WriteBinary, sizeof(KDTNode) * treeNodeSize, (char*)m_pTreeRoots.data()); LOG(Helper::LogLevel::LL_Info, "Save KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode SaveTrees(std::string sTreeFileName) const { LOG(Helper::LogLevel::LL_Info, "Save KDT to %s\n", sTreeFileName.c_str()); auto ptr = f_createIO(); if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::out)) return ErrorCode::FailedCreateFile; return SaveTrees(ptr); } ErrorCode LoadTrees(char* pKDTMemFile) { m_iTreeNumber = *((int*)pKDTMemFile); pKDTMemFile += sizeof(int); m_pTreeStart.resize(m_iTreeNumber); memcpy(m_pTreeStart.data(), pKDTMemFile, sizeof(SizeType) * m_iTreeNumber); pKDTMemFile += sizeof(SizeType)*m_iTreeNumber; SizeType treeNodeSize = *((SizeType*)pKDTMemFile); pKDTMemFile += sizeof(SizeType); m_pTreeRoots.resize(treeNodeSize); memcpy(m_pTreeRoots.data(), pKDTMemFile, sizeof(KDTNode) * treeNodeSize); LOG(Helper::LogLevel::LL_Info, "Load KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode LoadTrees(std::shared_ptr<Helper::DiskPriorityIO> p_input) { if (m_bOldVersion) { struct KdtreeNode { int left; int right; short split_dim; float split_value; } tmpNode; IOBINARY(p_input, ReadBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber); int treeNodeSize = 0; for (int i = 0; i < m_iTreeNumber; i++) { m_pTreeStart.push_back(treeNodeSize); int iNodeSize; IOBINARY(p_input, ReadBinary, sizeof(iNodeSize), (char*)&iNodeSize); m_pTreeRoots.resize(treeNodeSize + iNodeSize); for (int j = treeNodeSize; j < treeNodeSize + iNodeSize; j++) { IOBINARY(p_input, ReadBinary, sizeof(KdtreeNode), (char*)(&tmpNode)); m_pTreeRoots[j].left = tmpNode.left + treeNodeSize; m_pTreeRoots[j].right = tmpNode.right + treeNodeSize; m_pTreeRoots[j].split_dim = tmpNode.split_dim; m_pTreeRoots[j].split_value = tmpNode.split_value; } treeNodeSize += iNodeSize; } LOG(Helper::LogLevel::LL_Info, "Load KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } IOBINARY(p_input, ReadBinary, sizeof(m_iTreeNumber), (char*)&m_iTreeNumber); m_pTreeStart.resize(m_iTreeNumber); IOBINARY(p_input, ReadBinary, sizeof(SizeType) * m_iTreeNumber, (char*)m_pTreeStart.data()); SizeType treeNodeSize; IOBINARY(p_input, ReadBinary, sizeof(treeNodeSize), (char*)&treeNodeSize); m_pTreeRoots.resize(treeNodeSize); IOBINARY(p_input, ReadBinary, sizeof(KDTNode) * treeNodeSize, (char*)m_pTreeRoots.data()); LOG(Helper::LogLevel::LL_Info, "Load KDT (%d,%d) Finish!\n", m_iTreeNumber, treeNodeSize); return ErrorCode::Success; } ErrorCode LoadTrees(std::string sTreeFileName) { LOG(Helper::LogLevel::LL_Info, "Load KDT From %s\n", sTreeFileName.c_str()); auto ptr = f_createIO(); if (ptr == nullptr || !ptr->Initialize(sTreeFileName.c_str(), std::ios::binary | std::ios::in)) return ErrorCode::FailedOpenFile; return LoadTrees(ptr); } template <typename T> void InitSearchTrees(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space) const { for (int i = 0; i < m_iTreeNumber; i++) { KDTSearch(p_data, fComputeDistance, p_query, p_space, m_pTreeStart[i], 0); } } template <typename T> void SearchTrees(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace &p_space, const int p_limits) const { while (!p_space.m_SPTQueue.empty() && p_space.m_iNumberOfCheckedLeaves < p_limits) { auto& tcell = p_space.m_SPTQueue.pop(); KDTSearch(p_data, fComputeDistance, p_query, p_space, tcell.node, tcell.distance); } } private: template <typename T> void KDTSearch(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T>& p_query, COMMON::WorkSpace& p_space, const SizeType node, const float distBound) const { if (COMMON::DistanceUtils::Quantizer) { switch (COMMON::DistanceUtils::Quantizer->GetReconstructType()) { #define DefineVectorValueType(Name, Type) \ case VectorValueType::Name: \ return KDTSearchCore<T, Type>(p_data, fComputeDistance, p_query, p_space, node, distBound); #include "inc/Core/DefinitionList.h" #undef DefineVectorValueType default: break; } } else { return KDTSearchCore<T, T>(p_data, fComputeDistance, p_query, p_space, node, distBound); } } template <typename T, typename Q> void KDTSearchCore(const Dataset<T>& p_data, float(*fComputeDistance)(const T* pX, const T* pY, DimensionType length), COMMON::QueryResultSet<T> &p_query, COMMON::WorkSpace& p_space, const SizeType node, const float distBound) const { if (node < 0) { SizeType index = -node - 1; if (index >= p_data.R()) return; #ifdef PREFETCH const T* data = p_data[index]; _mm_prefetch((const char*)data, _MM_HINT_T0); _mm_prefetch((const char*)(data + 64), _MM_HINT_T0); #endif if (p_space.CheckAndSet(index)) return; ++p_space.m_iNumberOfTreeCheckedLeaves; ++p_space.m_iNumberOfCheckedLeaves; p_space.m_NGQueue.insert(NodeDistPair(index, fComputeDistance(p_query.GetQuantizedTarget(), data, p_data.C()))); return; } auto& tnode = m_pTreeRoots[node]; float diff = ((Q*) p_query.GetTarget())[tnode.split_dim] - tnode.split_value; float distanceBound = distBound + diff * diff; SizeType otherChild, bestChild; if (diff < 0) { bestChild = tnode.left; otherChild = tnode.right; } else { otherChild = tnode.left; bestChild = tnode.right; } p_space.m_SPTQueue.insert(NodeDistPair(otherChild, distanceBound)); KDTSearchCore<T,Q>(p_data, fComputeDistance, p_query, p_space, bestChild, distBound); } template <typename T, typename R> void DivideTree(const Dataset<T>& data, std::vector<SizeType>& indices, SizeType first, SizeType last, SizeType index, SizeType &iTreeSize, IAbortOperation* abort = nullptr) { if (abort && abort->ShouldAbort()) return; ChooseDivision<T, R>(data, m_pTreeRoots[index], indices, first, last); SizeType i = Subdivide<T, R>(data, m_pTreeRoots[index], indices, first, last); if (i - 1 <= first) { m_pTreeRoots[index].left = -indices[first] - 1; } else { iTreeSize++; m_pTreeRoots[index].left = iTreeSize; DivideTree<T, R>(data, indices, first, i - 1, iTreeSize, iTreeSize); } if (last == i) { m_pTreeRoots[index].right = -indices[last] - 1; } else { iTreeSize++; m_pTreeRoots[index].right = iTreeSize; DivideTree<T, R>(data, indices, i, last, iTreeSize, iTreeSize); } } template <typename T, typename R> void ChooseDivision(const Dataset<T>& data, KDTNode& node, const std::vector<SizeType>& indices, const SizeType first, const SizeType last) { SizeType cols = data.C(); bool quantizer_exists = (nullptr != COMMON::DistanceUtils::Quantizer); R* v_holder = nullptr; if (quantizer_exists) { cols = COMMON::DistanceUtils::Quantizer->ReconstructDim(); v_holder = (R*)_mm_malloc(COMMON::DistanceUtils::Quantizer->ReconstructSize(), ALIGN_SPTAG); } std::vector<float> meanValues(cols, 0); std::vector<float> varianceValues(cols, 0); SizeType end = min(first + m_iSamples, last); SizeType count = end - first + 1; // calculate the mean of each dimension for (SizeType j = first; j <= end; j++) { R* v; if (quantizer_exists) { COMMON::DistanceUtils::Quantizer->ReconstructVector((uint8_t*)data[indices[j]], v_holder); v = v_holder; } else { v = (R*)data[indices[j]]; } for (DimensionType k = 0; k < cols; k++) { meanValues[k] += v[k]; } } for (DimensionType k = 0; k < cols; k++) { meanValues[k] /= count; } // calculate the variance of each dimension for (SizeType j = first; j <= end; j++) { R* v; if (quantizer_exists) { COMMON::DistanceUtils::Quantizer->ReconstructVector((uint8_t*)data[indices[j]], v_holder); v = v_holder; } else { v = (R*)data[indices[j]]; } for (DimensionType k = 0; k < cols; k++) { float dist = v[k] - meanValues[k]; varianceValues[k] += dist*dist; } } if (quantizer_exists) { _mm_free(v_holder); } // choose the split dimension as one of the dimension inside TOP_DIM maximum variance node.split_dim = SelectDivisionDimension(varianceValues); // determine the threshold node.split_value = meanValues[node.split_dim]; } DimensionType SelectDivisionDimension(const std::vector<float>& varianceValues) const { // Record the top maximum variances std::vector<DimensionType> topind(m_numTopDimensionKDTSplit); int num = 0; // order the variances for (DimensionType i = 0; i < (DimensionType)varianceValues.size(); i++) { if (num < m_numTopDimensionKDTSplit || varianceValues[i] > varianceValues[topind[num - 1]]) { if (num < m_numTopDimensionKDTSplit) { topind[num++] = i; } else { topind[num - 1] = i; } int j = num - 1; // order the TOP_DIM variances while (j > 0 && varianceValues[topind[j]] > varianceValues[topind[j - 1]]) { std::swap(topind[j], topind[j - 1]); j--; } } } // randomly choose a dimension from TOP_DIM return topind[COMMON::Utils::rand(num)]; } template <typename T, typename R> SizeType Subdivide(const Dataset<T>& data, const KDTNode& node, std::vector<SizeType>& indices, const SizeType first, const SizeType last) const { SizeType i = first; SizeType j = last; bool quantizer_exists = (bool) COMMON::DistanceUtils::Quantizer; R* v_holder = nullptr; if (quantizer_exists) { v_holder = (R*)_mm_malloc(COMMON::DistanceUtils::Quantizer->ReconstructSize(), ALIGN_SPTAG); } // decide which child one point belongs while (i <= j) { R* v; SizeType ind = indices[i]; if (quantizer_exists) { COMMON::DistanceUtils::Quantizer->ReconstructVector((uint8_t*)data[ind], v_holder); v = v_holder; } else { v = (R*)data[ind]; } float val = v[node.split_dim]; if (val < node.split_value) { i++; } else { std::swap(indices[i], indices[j]); j--; } } if (quantizer_exists) { _mm_free(v_holder); } // if all the points in the node are equal,equally split the node into 2 if ((i == first) || (i == last + 1)) { i = (first + last + 1) / 2; } return i; } private: std::vector<SizeType> m_pTreeStart; std::vector<KDTNode> m_pTreeRoots; public: std::unique_ptr<std::shared_timed_mutex> m_lock; int m_iTreeNumber, m_numTopDimensionKDTSplit, m_iSamples; bool m_bOldVersion; }; } } #endif
krb5_tgs_fmt_plug.c
/* * Based on the work by Tim Medin * Port from his Pythonscript to John by Michael Kramer (SySS GmbH) * * This software is * Copyright (c) 2015 Michael Kramer <michael.kramer@uni-konstanz.de>, * Copyright (c) 2015 magnum * Copyright (c) 2016 Fist0urs <eddy.maaalou@gmail.com> * * Modified by Fist0urs to improve performances by proceeding known-plain * attack, based on defined ASN1 structures (then got rid of RC4 rounds * + hmac-md5) * * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_krb5tgs; #elif FMT_REGISTERS_H john_register_one(&fmt_krb5tgs); #else #include <stdio.h> #include <string.h> #include <ctype.h> #ifdef _OPENMP #include <omp.h> #endif #include "misc.h" #include "formats.h" #include "common.h" #include "dyna_salt.h" #include "rc4.h" #include "md4.h" #include "hmacmd5.h" #include "unicode.h" #include "memdbg.h" #ifndef OMP_SCALE #define OMP_SCALE 256 #endif #define FORMAT_LABEL "krb5tgs" #define FORMAT_NAME "Kerberos 5 TGS etype 23" #define FORMAT_TAG "$krb5tgs$23$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "MD4 HMAC-MD5 RC4" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1000 #define MIN_PLAINTEXT_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 0 #define BINARY_ALIGN MEM_ALIGN_NONE #define SALT_SIZE sizeof(struct custom_salt *) #define SALT_ALIGN sizeof(struct custom_salt *) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 /* assuming checksum == edata1 formats are: checksum$edata2 $krb5tgs$23$checksum$edata2 $krb5tgs$23$*user*realm*spn*$checksum$edata2 */ static struct fmt_tests tests[] = { {"74809c4c83c3c8279c6058d2f206ec2f$78b4bbd4d229487d5afc9a6050d4144ce10e9245cdfc0df542879814ce740cebb970ee820677041596d7e55836a18cc95c04169e7c74a4a22ae94e66f3d37150e26cc9cb99e189ef54feb7a40a8db2cb2c41db80d8927c74da7b33b52c58742d2109036b8ab27184609e7adff27b8f17b2f2a7b7d85e4ad532d8a70d48685a4390a9fc7a0ab47fd17334534d795abf83462f0db3de931c6a2d5988ab5bf3253facfff1381afb192ce385511c9052f2915ffdb7ea28a1bbad0573d9071e79dc15068527d50100de8813793a15c292f145fa3797ba86f373a4f0a05e5f2ec7dbfd8c8b5139cc7fbb098ea1dd91a7440134ffe2aff7174d0df13dcad82c81c680a70127a3ec8792bdecd74a878f97ff2b21277dc8c9a2f7bbcd9f72560dd933d85585259067d45a46a6f505d03f188b62c37edf03f117503a26743ebd674d5b07324c15fc8418881613b365402e0176da97d43cf85e8239b69aee07791233a959bcaf83a7f492fa718dd0a1747eaf5ce626eb11bda89e8235a056e2721f45c3b61442d893ef32a8c192ea0dadb853f3c6f3c75e92f23c744605c6f55578f696b0f33a9586b8aae3e12e38a097692cd9a31d780d973eaaf62ef23b2fc9ae59a38bfd8ea14d3289b46910f61a90aa733e66382bc27f40ba634e55ef1bec0ca7f71546b79566d85664b92f9fae495fcef5cde4c4399a6798569a7e81b9cc4bdde7104f3fe181401f82bba944e3b0a406c7093c00ff9d5984a82517b1a64a8aa561bc1f0cbafbdbbc5654d375c91d4e485e17bb06838109fbc1504147481c91652f545086a84daa423a6286ea6bb13460c5ff3d865a7b37b9ce4e7b07fbe2f6897c12c1e4df2e875c1ec9cfbf84097a7f48b270baf3481263b21849ab93c231490d06a23461a5e00c23df76bca8e5a19256d859304e1f5752bf055ac7f4843e1ad174f1cbbf5c142958f9310025ce439d5979982fb0b8c2ea95e1a22ee8dc63423d9d364cb0b95bcdf89ec4ed485b9005326d728757d77aa3e020a4a61d7deb782bc5264dca350173609772cd6d003ee8104dd24d310c9a18a44f78e27d65095f5bb54f6118c8f0d79ad5a850cec8d40a19bd0134144e904c9eb7fdcff3293696071fc1118f6b2f934281a25bcd5ca7d567714b1e43bd6d09bfcc8744c0ca273a75938394ac2fb31957287093346078577c94a71dfa6ad4a63211f54f00ef7a9064d070aaff84116ee891728915c938a8a32e87aaa00ec18e2b4e9ae88f7e53f08d855052a995f92351be32d8df934eab487103b0f089828e5fb5f73af3a8a05b9fffd25c43a392994743de3de1a2a9b8bba27e02ae2341f09d63aafab291759c41b9635521ca02f08e21e7e5c3ce75c8c3515eaa99aeb9bf8e204663e8b6b8507ecf87230a131687b4770e250ba0ef29fa3ca3b47b34971e17c6a3ef785acdd7c90da9d2", "test123"}, {"$krb5tgs$23$ee09e292a05e3af870417758b1cdfd04$a1a480b8505d2f2f0ff06ddce40c2f6e76bd06fa64dcd5b0646a68effcd686b2e41562ebda90da7e7b36d95cd16ca8a33b8d99184d6b7fa7a2efec3a05dcb63b3e815ffd38849dc69174d1efb3a871544b73a6da55d2331bd4b60743d1654873e3c1748ce155c35a1711695296ab944d158e374b67f43dd07eab2bcacec1be480e5c1338e3834f7133909f5c7970ece39e73bd96d40f696cb5a8575e5e1feab937b616d6180cc3258e22b9fc495017593e15fc10e674af8184c282a0d80902ea9dabda5fb0a56d7980bfd4b62b330155cd8e318dc5be55500cb8ddd691b629af371463c411f1c11d21811e1546477b85f0a85e296f5df737930aff5015111d2f01a236ab7c77e9dab001f52400cccbcdb31bb180db027bd0fa2f6000dce7c1e072c0effbdee23a401720b1fe54a09a75430497f42f6e047d62d1123866d6ed37e58f8e2c1e462acb1a97a44a5ccef49897af190a46b3ab057d18c1e47d717c7a63658357d58d9cd5b7672f0a946f95f6e2ec3aee549e20e3b11237ea59f87723f24e03a6fac9e51086bc84142631ed36ee6855920f3d3d1e85d0faaa0a8b04a2b050b17f94d44af7f48302fa70dcf43279415983924e5d874c59722b6fb87ad1006fcb51e4341bb2cc4caf8c4b7993269af219cf4efa12b1009961c22f123c35f982e4ca75a97cd37f7f16be111ad301637ffb1664ccb021d3cf6bf771e07dc42202dac079c6bd7559f8e7a939bc14e9ddb45fe1b88c5f83b1ff966342bb9211afd15772cf5f871d39d0b30776d51d84b046df30d250c1877d146047e784c4bc2e6745f357dd0b1c6aaa11e26a0e3c2772781695f6a3bc536ba19e2327ec8c0866bd78d3b5b067abcf6991eafc8b7a11ad4049711263f3c68b358f246da1308d5a0daac1d7efedbc237be3d6a4bafe5ce66e941f7227d2b869bda637dfd223a4546340c59e7d0e2b58f60a67590468a53a5d28cc35cec36a9c5610c70c0633767539640b42cff787f4782057ff70d0e64658413429347f5449c1360da4d0827c4197bbb0361c6d0e04bcaf6bba1233912f806772146c0e778ac06749bbd3d8819007d070ae912580ff11a41f71b0907b88fb585585ebe42b4cc4ecde8ff7b49a856dd70f316425e53feff3ee6ca1e44d9ba5e607a41cf26edf44bffe2796f94ea2d767fbf81f665a7fedf0291e76c6fa409dc99c56954f21edc77f6173c5a3a909c8756f3cc5cc6c2d2e405f333ee0b50284aacfb81f9dfc6058b78b282db4511580eb623dc393919befc250d224490936e5fb16c483f4bd00c8915288d0ddf3812eaa3d46ad5a24c56390076730d23b2de6558ddadddba725f9b4a73d13de3e1276fc285194e3a2f613d9b020d0485d7e26b36b7b917f4911024127320627066fabbd465b4cd5d5fdebae804d15db0f5b276659364bec32a13a8d9e11349f54bd", "bluvshop2"}, {"$krb5tgs$23$*Fist0urs$MYDOMAIN$cifs/panda.com*$423cb47a258e5859c13381ae64de7464$8dd47d94e288a1b32af726d2eac33710fb1610e4c6f674907d7a74d26515a314173b2b531baa790b70467ebe538fc9e941bf4d7f7218a4ec17c1dc963b717d5837fcd5ae678189101a1b4831a53a1322ca6e8f5d644e4aa72e99bedb4a0e967c3e05ccdcc96137265612969a1214a71038dea845250cac45551963fe85f193d88aa39ed57b95b934295e17de04ebf0ad275df67f65fb1fc2ee3095c6af02c4c1b8efa570e1c2ac562601c5ac89bd6f59ca8b957660aa00787d4a0f9d9f29b15eb3b85823f7c9814eab9106210c37d863cf8413391c5941a994fdd52a44e4f8e8e4c9b8b520e62015fb5ed40e91e7a453b3ddcefb888fd896c187993a899b6a30d27a5b2b7847a410c0cce8b0fcf90367bfd8e6dfa7eb37676ecdf500c9a51ffb59792c13e222371e024f857134b7039931daa66a6902da37e71c41adf83846a9df1e75575696d7a6f1744d48e8215849773903c9475c29a1ec0fcc11257f9479467c2b65679a3da298e6806d619794dfc06b10b5e0a46e395c3ade3d750292f244cabb7172d83dbd42c6e3bd5a93a8c2d5fe84b23a3c60508733f5a087763f2fa514d18f891461b8ea22f7eaa847906182bd0415c28d197c06df8449cc2c6c2016c38672a67613a14ccac9025c4da85fc0825dcd9a1269e6064f80c0de445fbdd237d35ab0eb6ae468413c5b17c9955a8c8c34952c8a188bad7e5b18651a75b1c46cf116422378a94a19c31dfa634c8ab15f4f13e7e427741ab9e8f247b4a8fe2562986ee21f602b4fad45bd535718020b764da6f346e3b028db8a1af88419f3ea9141fcf0c622ed40d894814e5d60a9dcdfc8344f802c7b2f0089131e57ac0cc071af13c3b2b7302e9df4665c48b91f4ef0bb2a60a272e5841e0ee8da01a91773d41f295514b65ccb2190195f720d9838b3e7c701b51e813ef0262fbdbbe06391ba3fe4232e74523dfa933e6d3df2494ddd9f254afdf97623ceb5d32483a870cf72a57617bdbf97f0420c041edb5a884ff401dc21da0472d7a75d89dc9937fd65c3a422063ea44e3954435d38b8f34cec2c0360c8bef392f77fbab76a7b801e05b467d4980d20f0a7dbc1c39f50ce4429df1ec167c6be67d2fbd507a3f7b5d98cf214ae0510fac51e1075a06250d65a3a1179486bda5d982b7904682835079e3042f39a582492cd14dbafb5826e242c81998752043e2dd91b648f115900595f5191a01f187c4b6dea4917e4773a5fb28cb1d20508142a3905068c931a8c9a8fa291b92f8ece9884affd8787a5aa11858274879160e930587f3c32e2cabbd124c708641df09f82d05ab4db157ad24931dc36c616dbb778762ead6a8491ce8a48037106d382283ac69422c04af3ae2cbe22eff6dff21bc34b154a5fab666870c59aba65bd4e0ea0be3f394bb4901fd64a0e19293b8026188615c84601b7fecdb62b", "jlcirr."}, // 1-40a00000-john@HTTP-adc1.toor.com-TOOR.COM.kirbi file {"$krb5tgs$23$e43ae991b15bbd11c19395c6c785f4d4$07ea84f4cf5ab2ad5a1a15c5776e7bc024d26451771e653c9cb0b87d8a5d73317f992913621a61039d143818585aee976b5273f53023d28a1da22c8a2f79e47956da4221bd10809fb777b4684cbbc102bda46dc816eb5a5315196f1b2cd47fee6ddc1adae753c96eefe77bf8e8e54e33489595f0c3cb47db9bef77438f666c15de4ee9893839c5280daebd81d476a00944f8282eed61af43578fc6f68dbb47ad9106ea1f58125355506016ccf997d35d8ccad169ba7eebe27e76d19188a227158172b405c7e053da1e3bafae4cd39594e7a03e7a96bdbc63a793fba6c26135d6d1789395f0155341e04f80097540ffb1f299f61960a34db3ea14b95b4633b7eea3a552140e7e42708009fdda3d1b42b3297142bfc036abd3d28f07ba1c8362e1c5b346f55af7214314a92fa412733825f55fe4a56b56859af00eb4f69cc7ad339b7bc8032ff1057be3e73c5533f4f546e599ecbf60305569c9b87b22971ef012ff92f582688b001ad23901dae743c46cae6603f7b6b88db78fcfd59997e8a1078f8a27e28a6628bc59d78674d9d16a6413da369ab58cb702dba01c710fbfed87f4665dfb3cc4a8f83ebf960435ae96973e699cd419324ddf115825c99890b2bb8e35ce0005a2adf95ce691b135358c63aa87088ed615c5a9667927e691bf7135677893abc41c038d25ff9091c14e3d1da85c7f0edaed32c9b3b56d2c473b2363b93aae5cc9b02db47e7a22a639a951e2edce7580f691c2ee0f8ebdfb02cdc6de8d1028e34085d1a69cdebb00a430b5ddce223bd1cc9c66b746a46584c098f051b97180ee8db4268a3a838504884df45227cac6fe9e73704877f04558c9640ac2ed33b3216b2e17805863a955285f4633407097f439d7063faeacdcee0d6d4e6c2adbe85df0e51eb3c08da1cedb4fa70ff74b2711a7294b499597c1f30c1dd3cc12751692311a16e22b3fa6af75eb0ace4170df497ba860445b1fc964771eafc034515918bb080a6d05ab1170708e6ce80bf9b00f808a2b814e89d0ac9b5d1a23686b48e99fdc50c71b5fef8a9bfc851e40bed59f69821109be0119151768e4d91b8b00c46b39af207ad4a2566ce7751ac124c3c5851cd1026052d34988272bf2851bd1a4536816a7635d83c1378b442eb04c15d5028763e0b189c8f45703c54d62aaea570c9e56b0e721d170cda74f91a4101c495fb565bb03f2ad635335c88db112dfb073bb4d1547de3214de5e371bfe9b440de3882f7b83593ca0fc60f4e6e2e3885b2a365a56b529904c74bc58ab38432f0dfbbd3f4d543f9d8685b0aa69aa807701e09e1253b6ed4948c7ceaaafdd0baed2663881d52a163101a5bb697a65b2bfcc54d0dd", "1qaz@WSX"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static unsigned char (*saved_K1)[16]; static int any_cracked, *cracked; static size_t cracked_size; static int new_keys; static struct custom_salt { dyna_salt dsalt; unsigned char edata1[16]; uint32_t edata2len; unsigned char* edata2; } *cur_salt; static char *split(char *ciphertext, int index, struct fmt_main *self) { static char *ptr, *keeptr; int i; if (strstr(ciphertext, "$SOURCE_HASH$")) return ciphertext; ptr = mem_alloc_tiny(strlen(ciphertext) + FORMAT_TAG_LEN + 1, MEM_ALIGN_NONE); keeptr = ptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) { memcpy(ptr, FORMAT_TAG, FORMAT_TAG_LEN); ptr += FORMAT_TAG_LEN; } for (i = 0; i < strlen(ciphertext) + 1; i++) ptr[i] = tolower(ARCH_INDEX(ciphertext[i])); return keeptr; } static int valid(char *ciphertext, struct fmt_main *self) { char *p; char *ctcopy; char *keeptr; int extra; ctcopy = strdup(ciphertext); keeptr = ctcopy; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) == 0) { ctcopy += FORMAT_TAG_LEN; if (ctcopy[0] == '*') { /* assume account's info provided */ ctcopy++; p = strtokm(ctcopy, "*"); ctcopy = strtokm(NULL, ""); if (!ctcopy || *ctcopy != '$') goto err; ++ctcopy; /* set after '$' */ goto edata; } if (ctcopy[0] == '$') ctcopy++; } edata: /* assume checksum */ if (((p = strtokm(ctcopy, "$")) == NULL) || strlen(p) != 32) goto err; /* assume edata2 following */ if (((p = strtokm(NULL, "$")) == NULL)) goto err; if (!ishex(p) && (hexlen(p, &extra) < 64 || extra)) goto err; if ((strtokm(NULL, "$") != NULL)) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_alloc_align(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); saved_K1 = mem_alloc_align(sizeof(*saved_K1) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); any_cracked = 0; cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt; cracked = mem_calloc(cracked_size, 1); } static void done(void) { MEM_FREE(saved_K1); MEM_FREE(cracked); MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { int i; static struct custom_salt cs; char *p; char *ctcopy; char *keeptr; static void *ptr; ctcopy = strdup(ciphertext); keeptr = ctcopy; memset(&cs, 0, sizeof(cs)); cs.edata2 = NULL; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) == 0) { ctcopy += FORMAT_TAG_LEN; if (ctcopy[0] == '*') { ctcopy++; p = strtokm(ctcopy, "*"); ctcopy += strlen(p) + 2; goto edata; } if (ctcopy[0]=='$') ctcopy++; } edata: if (((p = strtokm(ctcopy, "$")) != NULL) && strlen(p) == 32) { /* assume checksum */ for (i = 0; i < 16; i++) { cs.edata1[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } /* skip '$' */ p += strlen(p) + 1; /* retrieve non-constant length of edata2 */ for (i = 0; p[i] != '\0'; i++) ; cs.edata2len = i/2; cs.edata2 = (unsigned char*) mem_calloc_tiny(cs.edata2len + 1, sizeof(char)); for (i = 0; i < cs.edata2len; i++) { /* assume edata2 */ cs.edata2[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } } MEM_FREE(keeptr); /* following is used to fool dyna_salt stuff */ cs.dsalt.salt_cmp_offset = SALT_CMP_OFF(struct custom_salt, edata1); cs.dsalt.salt_cmp_size = SALT_CMP_SIZE(struct custom_salt, edata1, edata2len, 0); cs.dsalt.salt_alloc_needs_free = 0; ptr = mem_alloc_tiny(sizeof(struct custom_salt), MEM_ALIGN_WORD); memcpy(ptr, &cs, sizeof(struct custom_salt)); return (void *) &ptr; } static void set_salt(void *salt) { cur_salt = *(struct custom_salt**)salt; } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, strlen(key) + 1); new_keys = 1; } static char *get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; const unsigned char data[4] = {2, 0, 0, 0}; int index; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { unsigned char K3[16]; #ifdef _MSC_VER unsigned char ddata[65536]; #else unsigned char ddata[cur_salt->edata2len + 1]; #endif unsigned char checksum[16]; RC4_KEY rckey; if (new_keys) { MD4_CTX ctx; unsigned char key[16]; UTF16 wkey[PLAINTEXT_LENGTH + 1]; int len; len = enc_to_utf16(wkey, PLAINTEXT_LENGTH, (UTF8*)saved_key[index], strlen(saved_key[index])); if (len <= 0) { saved_key[index][-len] = 0; len = strlen16(wkey); } MD4_Init(&ctx); MD4_Update(&ctx, (char*)wkey, 2 * len); MD4_Final(key, &ctx); hmac_md5(key, data, 4, saved_K1[index]); } hmac_md5(saved_K1[index], cur_salt->edata1, 16, K3); RC4_set_key(&rckey, 16, K3); RC4(&rckey, 32, cur_salt->edata2, ddata); /* 8 first bytes are nonce, then ASN1 structures (DER encoding: type-length-data) if length >= 128 bytes: length is on 2 bytes and type is \x63\x82 (encode_krb5_enc_tkt_part) and data is an ASN1 sequence \x30\x82 else: length is on 1 byte and type is \x63\x81 and data is an ASN1 sequence \x30\x81 next headers follow the same ASN1 "type-length-data" scheme */ if (((!memcmp(ddata + 8, "\x63\x82", 2)) && (!memcmp(ddata + 16, "\xA0\x07\x03\x05", 4))) || ((!memcmp(ddata + 8, "\x63\x81", 2)) && (!memcmp(ddata + 16, "\x03\x05\x00", 3)))) { /* check the checksum to be sure */ RC4(&rckey, cur_salt->edata2len - 32, cur_salt->edata2 + 32, ddata + 32); hmac_md5(saved_K1[index], ddata, cur_salt->edata2len, checksum); if (!memcmp(checksum, cur_salt->edata1, 16)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } } new_keys = 0; return *pcount; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return cracked[index]; } struct fmt_main fmt_krb5tgs = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, MIN_PLAINTEXT_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_UNICODE | FMT_UTF8 | FMT_OMP | FMT_DYNA_SALT, {NULL}, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, fmt_default_binary, get_salt, {NULL}, fmt_default_source, { fmt_default_binary_hash }, fmt_default_dyna_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 16; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
nn_index.h
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #ifndef FLANN_NNINDEX_H #define FLANN_NNINDEX_H #include <vector> #include "flann/general.h" #include "flann/util/matrix.h" #include "flann/util/params.h" #include "flann/util/result_set.h" #include "flann/util/dynamic_bitset.h" #include "flann/util/saving.h" namespace flann { #define KNN_HEAP_THRESHOLD 250 class IndexBase { public: virtual ~IndexBase() {}; virtual size_t veclen() const = 0; virtual size_t size() const = 0; virtual flann_algorithm_t getType() const = 0; virtual int usedMemory() const = 0; virtual IndexParams getParameters() const = 0; virtual void loadIndex(FILE* stream) = 0; virtual void saveIndex(FILE* stream) = 0; }; /** * Nearest-neighbour index base class */ template <typename Distance> class NNIndex : public IndexBase { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::ResultType DistanceType; NNIndex(Distance d) : distance_(d), last_id_(0), size_(0), size_at_build_(0), veclen_(0), removed_(false), removed_count_(0), data_ptr_(NULL) { } NNIndex(const IndexParams& params, Distance d) : distance_(d), last_id_(0), size_(0), size_at_build_(0), veclen_(0), index_params_(params), removed_(false), removed_count_(0), data_ptr_(NULL) { } NNIndex(const NNIndex& other) : distance_(other.distance_), last_id_(other.last_id_), size_(other.size_), size_at_build_(other.size_at_build_), veclen_(other.veclen_), index_params_(other.index_params_), removed_(other.removed_), removed_points_(other.removed_points_), removed_count_(other.removed_count_), ids_(other.ids_), points_(other.points_), data_ptr_(NULL) { if (other.data_ptr_) { data_ptr_ = new ElementType[size_*veclen_]; std::copy(other.data_ptr_, other.data_ptr_+size_*veclen_, data_ptr_); for (size_t i=0;i<size_;++i) { points_[i] = data_ptr_ + i*veclen_; } } } virtual ~NNIndex() { if (data_ptr_) { delete[] data_ptr_; } } virtual NNIndex* clone() const = 0; /** * Builds the index */ virtual void buildIndex() { freeIndex(); cleanRemovedPoints(); // building index buildIndexImpl(); size_at_build_ = size_; } /** * Builds th index using using the specified dataset * @param dataset the dataset to use */ virtual void buildIndex(const Matrix<ElementType>& dataset) { setDataset(dataset); this->buildIndex(); } /** * @brief Incrementally add points to the index. * @param points Matrix with points to be added * @param rebuild_threshold */ virtual void addPoints(const Matrix<ElementType>& points, float rebuild_threshold = 2) { throw FLANNException("Functionality not supported by this index"); } /** * Remove point from the index * @param index Index of point to be removed */ virtual void removePoint(size_t id) { if (!removed_) { ids_.resize(size_); for (size_t i=0;i<size_;++i) { ids_[i] = i; } removed_points_.resize(size_); removed_points_.reset(); last_id_ = size_; removed_ = true; } size_t point_index = id_to_index(id); if (point_index!=size_t(-1) && !removed_points_.test(point_index)) { removed_points_.set(point_index); removed_count_++; } } /** * Get point with specific id * @param id * @return */ virtual ElementType* getPoint(size_t id) { size_t index = id_to_index(id); if (index!=size_t(-1)) { return points_[index]; } else { return NULL; } } /** * @return number of features in this index. */ inline size_t size() const { return size_ - removed_count_; } /** * @return The dimensionality of the features in this index. */ inline size_t veclen() const { return veclen_; } /** * Returns the parameters used by the index. * * @return The index parameters */ IndexParams getParameters() const { return index_params_; } template<typename Archive> void serialize(Archive& ar) { IndexHeader header; if (Archive::is_saving::value) { header.data_type = flann_datatype_value<ElementType>::value; header.index_type = getType(); header.rows = size_; header.cols = veclen_; } ar & header; // sanity checks if (Archive::is_loading::value) { if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { throw FLANNException("Invalid index file, wrong signature"); } if (header.data_type != flann_datatype_value<ElementType>::value) { throw FLANNException("Datatype of saved index is different than of the one to be created."); } if (header.index_type != getType()) { throw FLANNException("Saved index type is different then the current index type."); } // TODO: check for distance type } ar & size_; ar & veclen_; ar & size_at_build_; bool save_dataset; if (Archive::is_saving::value) { save_dataset = get_param(index_params_,"save_dataset", false); } ar & save_dataset; if (save_dataset) { if (Archive::is_loading::value) { if (data_ptr_) { delete[] data_ptr_; } data_ptr_ = new ElementType[size_*veclen_]; points_.resize(size_); for (size_t i=0;i<size_;++i) { points_[i] = data_ptr_ + i*veclen_; } } for (size_t i=0;i<size_;++i) { ar & serialization::make_binary_object (points_[i], veclen_*sizeof(ElementType)); } } else { if (points_.size()!=size_) { throw FLANNException("Saved index does not contain the dataset and no dataset was provided."); } } ar & last_id_; ar & ids_; ar & removed_; if (removed_) { ar & removed_points_; } ar & removed_count_; } /** * @brief Perform k-nearest neighbor search * @param[in] queries The query points for which to find the nearest neighbors * @param[out] indices The indices of the nearest neighbors found * @param[out] dists Distances to the nearest neighbors found * @param[in] knn Number of nearest neighbors to return * @param[in] params Search parameters */ virtual int knnSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen()); assert(indices.rows >= queries.rows); assert(dists.rows >= queries.rows); assert(indices.cols >= knn); assert(dists.cols >= knn); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } int count = 0; if (use_heap) { #pragma omp parallel num_threads(params.cores) { KNNResultSet2<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNSimpleResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); resultSet.copy(indices[i], dists[i], n, params.sorted); indices_to_ids(indices[i], indices[i], n); count += n; } } } return count; } /** * * @param queries * @param indices * @param dists * @param knn * @param params * @return */ int knnSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, size_t knn, const SearchParams& params) const { flann::Matrix<size_t> indices_(new size_t[indices.rows*indices.cols], indices.rows, indices.cols); int result = knnSearch(queries, indices_, dists, knn, params); for (size_t i=0;i<indices.rows;++i) { for (size_t j=0;j<indices.cols;++j) { indices[i][j] = indices_[i][j]; } } delete[] indices_.ptr(); return result; } /** * @brief Perform k-nearest neighbor search * @param[in] queries The query points for which to find the nearest neighbors * @param[out] indices The indices of the nearest neighbors found * @param[out] dists Distances to the nearest neighbors found * @param[in] knn Number of nearest neighbors to return * @param[in] params Search parameters */ int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { assert(queries.cols == veclen()); bool use_heap; if (params.use_heap==FLANN_Undefined) { use_heap = (knn>KNN_HEAP_THRESHOLD)?true:false; } else { use_heap = (params.use_heap==FLANN_True)?true:false; } if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); int count = 0; if (use_heap) { #pragma omp parallel num_threads(params.cores) { KNNResultSet2<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n>0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } else { #pragma omp parallel num_threads(params.cores) { KNNSimpleResultSet<DistanceType> resultSet(knn); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = std::min(resultSet.size(), knn); indices[i].resize(n); dists[i].resize(n); if (n>0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } count += n; } } } return count; } /** * * @param queries * @param indices * @param dists * @param knn * @param params * @return */ int knnSearch(const Matrix<ElementType>& queries, std::vector< std::vector<int> >& indices, std::vector<std::vector<DistanceType> >& dists, size_t knn, const SearchParams& params) const { std::vector<std::vector<size_t> > indices_; int result = knnSearch(queries, indices_, dists, knn, params); indices.resize(indices_.size()); for (size_t i=0;i<indices_.size();++i) { indices[i].assign(indices_[i].begin(), indices_[i].end()); } return result; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indinces of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ int radiusSearch(const Matrix<ElementType>& queries, Matrix<size_t>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; size_t num_neighbors = std::min(indices.cols, dists.cols); int max_neighbors = params.max_neighbors; if (max_neighbors<0) max_neighbors = num_neighbors; else max_neighbors = std::min(max_neighbors,(int)num_neighbors); if (max_neighbors==0) { #pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); count += resultSet.size(); } } } else { // explicitly indicated to use unbounded radius result set // and we know there'll be enough room for resulting indices and dists if (params.max_neighbors<0 && (num_neighbors>=size())) { #pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if (n>num_neighbors) n = num_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } else { // number of neighbors limited to max_neighbors #pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, max_neighbors); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if ((int)n>max_neighbors) n = max_neighbors; resultSet.copy(indices[i], dists[i], n, params.sorted); // mark the next element in the output buffers as unused if (n<indices.cols) indices[i][n] = size_t(-1); if (n<dists.cols) dists[i][n] = std::numeric_limits<DistanceType>::infinity(); indices_to_ids(indices[i], indices[i], n); } } } } return count; } /** * * @param queries * @param indices * @param dists * @param radius * @param params * @return */ int radiusSearch(const Matrix<ElementType>& queries, Matrix<int>& indices, Matrix<DistanceType>& dists, float radius, const SearchParams& params) const { flann::Matrix<size_t> indices_(new size_t[indices.rows*indices.cols], indices.rows, indices.cols); int result = radiusSearch(queries, indices_, dists, radius, params); for (size_t i=0;i<indices.rows;++i) { for (size_t j=0;j<indices.cols;++j) { indices[i][j] = indices_[i][j]; } } delete[] indices_.ptr(); return result; } /** * @brief Perform radius search * @param[in] query The query point * @param[out] indices The indinces of the neighbors found within the given radius * @param[out] dists The distances to the nearest neighbors found * @param[in] radius The radius used for search * @param[in] params Search parameters * @return Number of neighbors found */ int radiusSearch(const Matrix<ElementType>& queries, std::vector< std::vector<size_t> >& indices, std::vector<std::vector<DistanceType> >& dists, float radius, const SearchParams& params) const { assert(queries.cols == veclen()); int count = 0; // just count neighbors if (params.max_neighbors==0) { #pragma omp parallel num_threads(params.cores) { CountRadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); count += resultSet.size(); } } } else { if (indices.size() < queries.rows ) indices.resize(queries.rows); if (dists.size() < queries.rows ) dists.resize(queries.rows); if (params.max_neighbors<0) { // search for all neighbors #pragma omp parallel num_threads(params.cores) { RadiusResultSet<DistanceType> resultSet(radius); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } } } } else { // number of neighbors limited to max_neighbors #pragma omp parallel num_threads(params.cores) { KNNRadiusResultSet<DistanceType> resultSet(radius, params.max_neighbors); #pragma omp for schedule(static) reduction(+:count) for (int i = 0; i < (int)queries.rows; i++) { resultSet.clear(); findNeighbors(resultSet, queries[i], params); size_t n = resultSet.size(); count += n; if ((int)n>params.max_neighbors) n = params.max_neighbors; indices[i].resize(n); dists[i].resize(n); if (n > 0) { resultSet.copy(&indices[i][0], &dists[i][0], n, params.sorted); indices_to_ids(&indices[i][0], &indices[i][0], n); } } } } } return count; } /** * * @param queries * @param indices * @param dists * @param radius * @param params * @return */ int radiusSearch(const Matrix<ElementType>& queries, std::vector< std::vector<int> >& indices, std::vector<std::vector<DistanceType> >& dists, float radius, const SearchParams& params) const { std::vector<std::vector<size_t> > indices_; int result = radiusSearch(queries, indices_, dists, radius, params); indices.resize(indices_.size()); for (size_t i=0;i<indices_.size();++i) { indices[i].assign(indices_[i].begin(), indices_[i].end()); } return result; } virtual void findNeighbors(ResultSet<DistanceType>& result, const ElementType* vec, const SearchParams& searchParams) const = 0; protected: virtual void freeIndex() = 0; virtual void buildIndexImpl() = 0; size_t id_to_index(size_t id) { if (ids_.size()==0) { return id; } size_t point_index = size_t(-1); if (ids_[id]==id) { return id; } else { // binary search size_t start = 0; size_t end = ids_.size(); while (start<end) { size_t mid = (start+end)/2; if (ids_[mid]==id) { point_index = mid; break; } else if (ids_[mid]<id) { start = mid + 1; } else { end = mid; } } } return point_index; } void indices_to_ids(const size_t* in, size_t* out, size_t size) const { if (removed_) { for (size_t i=0;i<size;++i) { out[i] = ids_[in[i]]; } } } void setDataset(const Matrix<ElementType>& dataset) { size_ = dataset.rows; veclen_ = dataset.cols; last_id_ = 0; ids_.clear(); removed_points_.clear(); removed_ = false; removed_count_ = 0; points_.resize(size_); for (size_t i=0;i<size_;++i) { points_[i] = dataset[i]; } } void extendDataset(const Matrix<ElementType>& new_points) { size_t new_size = size_ + new_points.rows; if (removed_) { removed_points_.resize(new_size); ids_.resize(new_size); } points_.resize(new_size); for (size_t i=size_;i<new_size;++i) { points_[i] = new_points[i-size_]; if (removed_) { ids_[i] = last_id_++; removed_points_.reset(i); } } size_ = new_size; } void cleanRemovedPoints() { if (!removed_) return; size_t last_idx = 0; for (size_t i=0;i<size_;++i) { if (!removed_points_.test(i)) { points_[last_idx] = points_[i]; ids_[last_idx] = ids_[i]; removed_points_.reset(last_idx); ++last_idx; } } points_.resize(last_idx); ids_.resize(last_idx); removed_points_.resize(last_idx); size_ = last_idx; removed_count_ = 0; } void swap(NNIndex& other) { std::swap(distance_, other.distance_); std::swap(last_id_, other.last_id_); std::swap(size_, other.size_); std::swap(size_at_build_, other.size_at_build_); std::swap(veclen_, other.veclen_); std::swap(index_params_, other.index_params_); std::swap(removed_, other.removed_); std::swap(removed_points_, other.removed_points_); std::swap(removed_count_, other.removed_count_); std::swap(ids_, other.ids_); std::swap(points_, other.points_); std::swap(data_ptr_, other.data_ptr_); } protected: /** * The distance functor */ Distance distance_; /** * Each index point has an associated ID. IDs are assigned sequentially in * increasing order. This indicates the ID assigned to the last point added to the * index. */ size_t last_id_; /** * Number of points in the index (and database) */ size_t size_; /** * Number of features in the dataset when the index was last built. */ size_t size_at_build_; /** * Size of one point in the index (and database) */ size_t veclen_; /** * Parameters of the index. */ IndexParams index_params_; /** * Flag indicating if at least a point was removed from the index */ bool removed_; /** * Array used to mark points removed from the index */ DynamicBitset removed_points_; /** * Number of points removed from the index */ size_t removed_count_; /** * Array of point IDs, returned by nearest-neighbour operations */ std::vector<size_t> ids_; /** * Point data */ std::vector<ElementType*> points_; /** * Pointer to dataset memory if allocated by this index, otherwise NULL */ ElementType* data_ptr_; }; #define USING_BASECLASS_SYMBOLS \ using NNIndex<Distance>::distance_;\ using NNIndex<Distance>::size_;\ using NNIndex<Distance>::size_at_build_;\ using NNIndex<Distance>::veclen_;\ using NNIndex<Distance>::index_params_;\ using NNIndex<Distance>::removed_points_;\ using NNIndex<Distance>::ids_;\ using NNIndex<Distance>::removed_;\ using NNIndex<Distance>::points_;\ using NNIndex<Distance>::extendDataset;\ using NNIndex<Distance>::setDataset;\ using NNIndex<Distance>::cleanRemovedPoints;\ using NNIndex<Distance>::indices_to_ids; } #endif //FLANN_NNINDEX_H
GB_binop__pow_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__pow_int64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__pow_int64) // A.*B function (eWiseMult): GB (_AemultB_03__pow_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pow_int64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__pow_int64) // C+=b function (dense accum): GB (_Cdense_accumb__pow_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pow_int64) // C=scalar+B GB (_bind1st__pow_int64) // C=scalar+B' GB (_bind1st_tran__pow_int64) // C=A+scalar GB (_bind2nd__pow_int64) // C=A'+scalar GB (_bind2nd_tran__pow_int64) // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = GB_pow_int64 (aij, bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_pow_int64 (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_POW || GxB_NO_INT64 || GxB_NO_POW_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__pow_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__pow_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__pow_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((node)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__pow_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__pow_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__pow_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__pow_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__pow_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__pow_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = Bx [p] ; Cx [p] = GB_pow_int64 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__pow_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = Ax [p] ; Cx [p] = GB_pow_int64 (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_pow_int64 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__pow_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_pow_int64 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__pow_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
convolution_2x2_pack8_fp16.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv2x2s1_weight_fp16_pack8_avx(const Mat& kernel, Mat& kernel_tm_pack8, int num_input, int num_output) { // src = kw-kh-inch-outch // dst = 8b-8a-kw-kh-inch/8a-outch/8b Mat weight_data_r2 = kernel.reshape(4, num_input, num_output); kernel_tm_pack8.create(4, num_input / 8, num_output / 8, (size_t)2 * 64, 64); for (int q = 0; q + 7 < num_output; q += 8) { const Mat k0 = weight_data_r2.channel(q); const Mat k1 = weight_data_r2.channel(q + 1); const Mat k2 = weight_data_r2.channel(q + 2); const Mat k3 = weight_data_r2.channel(q + 3); const Mat k4 = weight_data_r2.channel(q + 4); const Mat k5 = weight_data_r2.channel(q + 5); const Mat k6 = weight_data_r2.channel(q + 6); const Mat k7 = weight_data_r2.channel(q + 7); Mat g0 = kernel_tm_pack8.channel(q / 8); for (int p = 0; p + 7 < num_input; p += 8) { const float* k00 = k0.row(p); const float* k01 = k0.row(p + 1); const float* k02 = k0.row(p + 2); const float* k03 = k0.row(p + 3); const float* k04 = k0.row(p + 4); const float* k05 = k0.row(p + 5); const float* k06 = k0.row(p + 6); const float* k07 = k0.row(p + 7); const float* k10 = k1.row(p); const float* k11 = k1.row(p + 1); const float* k12 = k1.row(p + 2); const float* k13 = k1.row(p + 3); const float* k14 = k1.row(p + 4); const float* k15 = k1.row(p + 5); const float* k16 = k1.row(p + 6); const float* k17 = k1.row(p + 7); const float* k20 = k2.row(p); const float* k21 = k2.row(p + 1); const float* k22 = k2.row(p + 2); const float* k23 = k2.row(p + 3); const float* k24 = k2.row(p + 4); const float* k25 = k2.row(p + 5); const float* k26 = k2.row(p + 6); const float* k27 = k2.row(p + 7); const float* k30 = k3.row(p); const float* k31 = k3.row(p + 1); const float* k32 = k3.row(p + 2); const float* k33 = k3.row(p + 3); const float* k34 = k3.row(p + 4); const float* k35 = k3.row(p + 5); const float* k36 = k3.row(p + 6); const float* k37 = k3.row(p + 7); const float* k40 = k4.row(p); const float* k41 = k4.row(p + 1); const float* k42 = k4.row(p + 2); const float* k43 = k4.row(p + 3); const float* k44 = k4.row(p + 4); const float* k45 = k4.row(p + 5); const float* k46 = k4.row(p + 6); const float* k47 = k4.row(p + 7); const float* k50 = k5.row(p); const float* k51 = k5.row(p + 1); const float* k52 = k5.row(p + 2); const float* k53 = k5.row(p + 3); const float* k54 = k5.row(p + 4); const float* k55 = k5.row(p + 5); const float* k56 = k5.row(p + 6); const float* k57 = k5.row(p + 7); const float* k60 = k6.row(p); const float* k61 = k6.row(p + 1); const float* k62 = k6.row(p + 2); const float* k63 = k6.row(p + 3); const float* k64 = k6.row(p + 4); const float* k65 = k6.row(p + 5); const float* k66 = k6.row(p + 6); const float* k67 = k6.row(p + 7); const float* k70 = k7.row(p); const float* k71 = k7.row(p + 1); const float* k72 = k7.row(p + 2); const float* k73 = k7.row(p + 3); const float* k74 = k7.row(p + 4); const float* k75 = k7.row(p + 5); const float* k76 = k7.row(p + 6); const float* k77 = k7.row(p + 7); unsigned short* g00 = (unsigned short*)g0.row(p / 8); for (int k = 0; k < 4; k++) { g00[0] = float32_to_float16(k00[k]); g00[1] = float32_to_float16(k10[k]); g00[2] = float32_to_float16(k20[k]); g00[3] = float32_to_float16(k30[k]); g00[4] = float32_to_float16(k40[k]); g00[5] = float32_to_float16(k50[k]); g00[6] = float32_to_float16(k60[k]); g00[7] = float32_to_float16(k70[k]); g00 += 8; g00[0] = float32_to_float16(k01[k]); g00[1] = float32_to_float16(k11[k]); g00[2] = float32_to_float16(k21[k]); g00[3] = float32_to_float16(k31[k]); g00[4] = float32_to_float16(k41[k]); g00[5] = float32_to_float16(k51[k]); g00[6] = float32_to_float16(k61[k]); g00[7] = float32_to_float16(k71[k]); g00 += 8; g00[0] = float32_to_float16(k02[k]); g00[1] = float32_to_float16(k12[k]); g00[2] = float32_to_float16(k22[k]); g00[3] = float32_to_float16(k32[k]); g00[4] = float32_to_float16(k42[k]); g00[5] = float32_to_float16(k52[k]); g00[6] = float32_to_float16(k62[k]); g00[7] = float32_to_float16(k72[k]); g00 += 8; g00[0] = float32_to_float16(k03[k]); g00[1] = float32_to_float16(k13[k]); g00[2] = float32_to_float16(k23[k]); g00[3] = float32_to_float16(k33[k]); g00[4] = float32_to_float16(k43[k]); g00[5] = float32_to_float16(k53[k]); g00[6] = float32_to_float16(k63[k]); g00[7] = float32_to_float16(k73[k]); g00 += 8; g00[0] = float32_to_float16(k04[k]); g00[1] = float32_to_float16(k14[k]); g00[2] = float32_to_float16(k24[k]); g00[3] = float32_to_float16(k34[k]); g00[4] = float32_to_float16(k44[k]); g00[5] = float32_to_float16(k54[k]); g00[6] = float32_to_float16(k64[k]); g00[7] = float32_to_float16(k74[k]); g00 += 8; g00[0] = float32_to_float16(k05[k]); g00[1] = float32_to_float16(k15[k]); g00[2] = float32_to_float16(k25[k]); g00[3] = float32_to_float16(k35[k]); g00[4] = float32_to_float16(k45[k]); g00[5] = float32_to_float16(k55[k]); g00[6] = float32_to_float16(k65[k]); g00[7] = float32_to_float16(k75[k]); g00 += 8; g00[0] = float32_to_float16(k06[k]); g00[1] = float32_to_float16(k16[k]); g00[2] = float32_to_float16(k26[k]); g00[3] = float32_to_float16(k36[k]); g00[4] = float32_to_float16(k46[k]); g00[5] = float32_to_float16(k56[k]); g00[6] = float32_to_float16(k66[k]); g00[7] = float32_to_float16(k76[k]); g00 += 8; g00[0] = float32_to_float16(k07[k]); g00[1] = float32_to_float16(k17[k]); g00[2] = float32_to_float16(k27[k]); g00[3] = float32_to_float16(k37[k]); g00[4] = float32_to_float16(k47[k]); g00[5] = float32_to_float16(k57[k]); g00[6] = float32_to_float16(k67[k]); g00[7] = float32_to_float16(k77[k]); g00 += 8; } } } } static void conv2x2s1_fp16_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out0 = top_blob.channel(p); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + p * 8) : _mm256_set1_ps(0.f); out0.fill(_bias0); for (int q = 0; q < inch; q++) { float* outptr0 = out0.row(0); const Mat img0 = bottom_blob.channel(q); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const unsigned short* kptr = (const unsigned short*)kernel.channel(p).row(q); // const float* kptr = (const float*)kernel + 4 * inch * p * 64; int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { __m256 _sum0 = _mm256_loadu_ps(outptr0); __m256 _sum1 = _mm256_loadu_ps(outptr0 + 8); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; __m256 _k00 = loadfp16(kptr); __m256 _k01 = loadfp16(kptr + 8); __m256 _k02 = loadfp16(kptr + 16); __m256 _k03 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); __m256 _k04 = loadfp16(kptr); __m256 _k05 = loadfp16(kptr + 8); __m256 _k06 = loadfp16(kptr + 16); __m256 _k07 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k07, _r07, _sum0); //======================================== _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); r0 += 8; _sum1 = _mm256_comp_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k07, _r07, _sum1); _k00 = loadfp16(kptr); _k01 = loadfp16(kptr + 8); _k02 = loadfp16(kptr + 16); _k03 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); _k04 = loadfp16(kptr); _k05 = loadfp16(kptr + 8); _k06 = loadfp16(kptr + 16); _k07 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k05, _r05, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k06, _r06, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k07, _r07, _sum0); _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _sum1 = _mm256_comp_fmadd_ps(_k00, _r00, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k01, _r01, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k02, _r02, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k03, _r03, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k04, _r04, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k05, _r05, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k06, _r06, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k07, _r07, _sum1); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = loadfp16(kptr); __m256 _k11 = loadfp16(kptr + 8); __m256 _k12 = loadfp16(kptr + 16); __m256 _k13 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); __m256 _k14 = loadfp16(kptr); __m256 _k15 = loadfp16(kptr + 8); __m256 _k16 = loadfp16(kptr + 16); __m256 _k17 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k17, _r17, _sum0); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_comp_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k17, _r17, _sum1); _k10 = loadfp16(kptr); _k11 = loadfp16(kptr + 8); _k12 = loadfp16(kptr + 16); _k13 = loadfp16(kptr + 24); kptr += 32; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); _k14 = loadfp16(kptr); _k15 = loadfp16(kptr + 8); _k16 = loadfp16(kptr + 16); _k17 = loadfp16(kptr + 24); _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k15, _r15, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k16, _r16, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k17, _r17, _sum0); r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _sum1 = _mm256_comp_fmadd_ps(_k10, _r10, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k11, _r11, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k12, _r12, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k13, _r13, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k14, _r14, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k15, _r15, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k16, _r16, _sum1); _sum1 = _mm256_comp_fmadd_ps(_k17, _r17, _sum1); kptr -= 224; _mm256_storeu_ps(outptr0, _sum0); _mm256_storeu_ps(outptr0 + 8, _sum1); outptr0 += 16; } for (; j < outw; j++) { __m256 _sum = _mm256_loadu_ps(outptr0); __m256 _r00 = _mm256_broadcast_ss(r0); __m256 _r01 = _mm256_broadcast_ss(r0 + 1); __m256 _r02 = _mm256_broadcast_ss(r0 + 2); __m256 _r03 = _mm256_broadcast_ss(r0 + 3); __m256 _r04 = _mm256_broadcast_ss(r0 + 4); __m256 _r05 = _mm256_broadcast_ss(r0 + 5); __m256 _r06 = _mm256_broadcast_ss(r0 + 6); __m256 _r07 = _mm256_broadcast_ss(r0 + 7); __m256 _k00 = loadfp16(kptr); __m256 _k01 = loadfp16(kptr + 8); __m256 _k02 = loadfp16(kptr + 16); __m256 _k03 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_comp_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_comp_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_comp_fmadd_ps(_k03, _r03, _sum); __m256 _k04 = loadfp16(kptr); __m256 _k05 = loadfp16(kptr + 8); __m256 _k06 = loadfp16(kptr + 16); __m256 _k07 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_comp_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_comp_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_comp_fmadd_ps(_k07, _r07, _sum); //======================================== r0 += 8; _r00 = _mm256_broadcast_ss(r0); _r01 = _mm256_broadcast_ss(r0 + 1); _r02 = _mm256_broadcast_ss(r0 + 2); _r03 = _mm256_broadcast_ss(r0 + 3); _r04 = _mm256_broadcast_ss(r0 + 4); _r05 = _mm256_broadcast_ss(r0 + 5); _r06 = _mm256_broadcast_ss(r0 + 6); _r07 = _mm256_broadcast_ss(r0 + 7); _k00 = loadfp16(kptr); _k01 = loadfp16(kptr + 8); _k02 = loadfp16(kptr + 16); _k03 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k00, _r00, _sum); _sum = _mm256_comp_fmadd_ps(_k01, _r01, _sum); _sum = _mm256_comp_fmadd_ps(_k02, _r02, _sum); _sum = _mm256_comp_fmadd_ps(_k03, _r03, _sum); _k04 = loadfp16(kptr); _k05 = loadfp16(kptr + 8); _k06 = loadfp16(kptr + 16); _k07 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k04, _r04, _sum); _sum = _mm256_comp_fmadd_ps(_k05, _r05, _sum); _sum = _mm256_comp_fmadd_ps(_k06, _r06, _sum); _sum = _mm256_comp_fmadd_ps(_k07, _r07, _sum); //=============== __m256 _r10 = _mm256_broadcast_ss(r1); __m256 _r11 = _mm256_broadcast_ss(r1 + 1); __m256 _r12 = _mm256_broadcast_ss(r1 + 2); __m256 _r13 = _mm256_broadcast_ss(r1 + 3); __m256 _r14 = _mm256_broadcast_ss(r1 + 4); __m256 _r15 = _mm256_broadcast_ss(r1 + 5); __m256 _r16 = _mm256_broadcast_ss(r1 + 6); __m256 _r17 = _mm256_broadcast_ss(r1 + 7); __m256 _k10 = loadfp16(kptr); __m256 _k11 = loadfp16(kptr + 8); __m256 _k12 = loadfp16(kptr + 16); __m256 _k13 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_comp_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_comp_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_comp_fmadd_ps(_k13, _r13, _sum); __m256 _k14 = loadfp16(kptr); __m256 _k15 = loadfp16(kptr + 8); __m256 _k16 = loadfp16(kptr + 16); __m256 _k17 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_comp_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_comp_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_comp_fmadd_ps(_k17, _r17, _sum); //======================================= r1 += 8; _r10 = _mm256_broadcast_ss(r1); _r11 = _mm256_broadcast_ss(r1 + 1); _r12 = _mm256_broadcast_ss(r1 + 2); _r13 = _mm256_broadcast_ss(r1 + 3); _r14 = _mm256_broadcast_ss(r1 + 4); _r15 = _mm256_broadcast_ss(r1 + 5); _r16 = _mm256_broadcast_ss(r1 + 6); _r17 = _mm256_broadcast_ss(r1 + 7); _k10 = loadfp16(kptr); _k11 = loadfp16(kptr + 8); _k12 = loadfp16(kptr + 16); _k13 = loadfp16(kptr + 24); kptr += 32; _sum = _mm256_comp_fmadd_ps(_k10, _r10, _sum); _sum = _mm256_comp_fmadd_ps(_k11, _r11, _sum); _sum = _mm256_comp_fmadd_ps(_k12, _r12, _sum); _sum = _mm256_comp_fmadd_ps(_k13, _r13, _sum); _k14 = loadfp16(kptr); _k15 = loadfp16(kptr + 8); _k16 = loadfp16(kptr + 16); _k17 = loadfp16(kptr + 24); _sum = _mm256_comp_fmadd_ps(_k14, _r14, _sum); _sum = _mm256_comp_fmadd_ps(_k15, _r15, _sum); _sum = _mm256_comp_fmadd_ps(_k16, _r16, _sum); _sum = _mm256_comp_fmadd_ps(_k17, _r17, _sum); kptr -= 224; _mm256_storeu_ps(outptr0, _sum); outptr0 += 8; } r0 += 8; r1 += 8; } } } }
simde-diagnostic.h
/* SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Copyright: * 2017-2020 Evan Nemerson <evan@nemerson.com> */ /* SIMDe targets a very wide range of standards and compilers, and our * goal is to compile cleanly even with extremely aggressive warnings * (i.e., -Weverything in clang, -Wextra in GCC, /W4 for MSVC, etc.) * treated as errors. * * While our preference is to resolve the underlying issue a given * diagnostic is warning us about, sometimes that's not possible. * Fixing a warning in one compiler may cause problems in another. * Sometimes a warning doesn't really apply to us (false positives), * and sometimes adhering to a warning would mean dropping a feature * we *know* the compiler supports since we have tested specifically * for the compiler or feature. * * When practical, warnings are only disabled for specific code. For * a list of warnings which are enabled by default in all SIMDe code, * see SIMDE_DISABLE_UNWANTED_DIAGNOSTICS. Note that we restore the * warning stack when SIMDe is done parsing, so code which includes * SIMDe is not deprived of these warnings. */ #if !defined(SIMDE_DIAGNOSTIC_H) #define SIMDE_DIAGNOSTIC_H #include "hedley.h" #include "simde-detect-clang.h" /* This is only to help us implement functions like _mm_undefined_ps. */ #if defined(SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_) #undef SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ #endif #if HEDLEY_HAS_WARNING("-Wuninitialized") #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("clang diagnostic ignored \"-Wuninitialized\"") #elif HEDLEY_GCC_VERSION_CHECK(4,2,0) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("GCC diagnostic ignored \"-Wuninitialized\"") #elif HEDLEY_PGI_VERSION_CHECK(19,10,0) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("diag_suppress 549") #elif HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,SEC_UNINITIALIZED_MEM_READ,SEC_UNDEFINED_RETURN_VALUE,unassigned)") #elif HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,SEC_UNINITIALIZED_MEM_READ,SEC_UNDEFINED_RETURN_VALUE)") #elif HEDLEY_SUNPRO_VERSION_CHECK(5,12,0) && defined(__cplusplus) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("error_messages(off,unassigned)") #elif \ HEDLEY_TI_VERSION_CHECK(16,9,9) || \ HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,2) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("diag_suppress 551") #elif HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ _Pragma("warning(disable:592)") #elif HEDLEY_MSVC_VERSION_CHECK(19,0,0) && !defined(__MSVC_RUNTIME_CHECKS) #define SIMDE_DIAGNOSTIC_DISABLE_UNINITIALIZED_ __pragma(warning(disable:4700)) #endif /* GCC emits a lot of "notes" about the ABI being different for things * in newer versions of GCC. We don't really care because all our * functions are inlined and don't generate ABI. */ #if HEDLEY_GCC_VERSION_CHECK(7,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_PSABI_ _Pragma("GCC diagnostic ignored \"-Wpsabi\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_PSABI_ #endif /* Since MMX uses x87 FP registers, you're supposed to call _mm_empty() * after each MMX function before any floating point instructions. * Some compilers warn about functions which use MMX functions but * don't call _mm_empty(). However, since SIMDe is implementyng the * MMX API we shouldn't be calling _mm_empty(); we leave it to the * caller to invoke simde_mm_empty(). */ #if HEDLEY_INTEL_VERSION_CHECK(19,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ _Pragma("warning(disable:13200 13203)") #elif defined(HEDLEY_MSVC_VERSION) #define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ __pragma(warning(disable:4799)) #else #define SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ #endif /* Intel is pushing people to use OpenMP SIMD instead of Cilk+, so they * emit a diagnostic if you use #pragma simd instead of * #pragma omp simd. SIMDe supports OpenMP SIMD, you just need to * compile with -qopenmp or -qopenmp-simd and define * SIMDE_ENABLE_OPENMP. Cilk+ is just a fallback. */ #if HEDLEY_INTEL_VERSION_CHECK(18,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_ _Pragma("warning(disable:3948)") #else #define SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_ #endif /* MSVC emits a diagnostic when we call a function (like * simde_mm_set_epi32) while initializing a struct. We currently do * this a *lot* in the tests. */ #if \ defined(HEDLEY_MSVC_VERSION) #define SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_ __pragma(warning(disable:4204)) #else #define SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_ #endif /* This warning needs a lot of work. It is triggered if all you do is * pass the value to memcpy/__builtin_memcpy, or if you initialize a * member of the union, even if that member takes up the entire union. * Last tested with clang-10, hopefully things will improve in the * future; if clang fixes this I'd love to enable it. */ #if \ HEDLEY_HAS_WARNING("-Wconditional-uninitialized") #define SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_ _Pragma("clang diagnostic ignored \"-Wconditional-uninitialized\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_ #endif /* This warning is meant to catch things like `0.3 + 0.4 == 0.7`, which * will is false. However, SIMDe uses these operations exclusively * for things like _mm_cmpeq_ps, for which we really do want to check * for equality (or inequality). * * If someone wants to put together a SIMDE_FLOAT_EQUAL(a, op, b) macro * which just wraps a check in some code do disable this diagnostic I'd * be happy to accept it. */ #if \ HEDLEY_HAS_WARNING("-Wfloat-equal") || \ HEDLEY_GCC_VERSION_CHECK(3,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_ _Pragma("GCC diagnostic ignored \"-Wfloat-equal\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_ #endif /* This is because we use HEDLEY_STATIC_ASSERT for static assertions. * If Hedley can't find an implementation it will preprocess to * nothing, which means there will be a trailing semi-colon. */ #if HEDLEY_HAS_WARNING("-Wextra-semi") #define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ _Pragma("clang diagnostic ignored \"-Wextra-semi\"") #elif HEDLEY_GCC_VERSION_CHECK(8,1,0) && defined(__cplusplus) #define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ _Pragma("GCC diagnostic ignored \"-Wextra-semi\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ #endif /* We do use a few variadic macros, which technically aren't available * until C99 and C++11, but every compiler I'm aware of has supported * them for much longer. That said, usage is isolated to the test * suite and compilers known to support them. */ #if HEDLEY_HAS_WARNING("-Wvariadic-macros") || HEDLEY_GCC_VERSION_CHECK(4,0,0) #if HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") #define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_ \ _Pragma("clang diagnostic ignored \"-Wvariadic-macros\"") \ _Pragma("clang diagnostic ignored \"-Wc++98-compat-pedantic\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_ _Pragma("GCC diagnostic ignored \"-Wvariadic-macros\"") #endif #else #define SIMDE_DIAGNOSTIC_DISABLE_VARIADIC_MACROS_ #endif /* emscripten requires us to use a __wasm_unimplemented_simd128__ macro * before we can access certain SIMD intrinsics, but this diagnostic * warns about it being a reserved name. It is a reserved name, but * it's reserved for the compiler and we are using it to convey * information to the compiler. */ #if HEDLEY_HAS_WARNING("-Wdouble-promotion") #define SIMDE_DIAGNOSTIC_DISABLE_RESERVED_ID_MACRO_ _Pragma("clang diagnostic ignored \"-Wreserved-id-macro\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_RESERVED_ID_MACRO_ #endif /* clang 3.8 warns about the packed attribute being unnecessary when * used in the _mm_loadu_* functions. That *may* be true for version * 3.8, but for later versions it is crucial in order to make unaligned * access safe. */ #if HEDLEY_HAS_WARNING("-Wpacked") #define SIMDE_DIAGNOSTIC_DISABLE_PACKED_ _Pragma("clang diagnostic ignored \"-Wpacked\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_PACKED_ #endif /* Triggered when assigning a float to a double implicitly. We use * explicit casts in SIMDe, this is only used in the test suite. */ #if HEDLEY_HAS_WARNING("-Wdouble-promotion") #define SIMDE_DIAGNOSTIC_DISABLE_DOUBLE_PROMOTION_ _Pragma("clang diagnostic ignored \"-Wdouble-promotion\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_DOUBLE_PROMOTION_ #endif /* Several compilers treat conformant array parameters as VLAs. We * test to make sure we're in C mode (C++ doesn't support CAPs), and * that the version of the standard supports CAPs. We also reject * some buggy compilers like MSVC (the logic is in Hedley if you want * to take a look), but with certain warnings enabled some compilers * still like to emit a diagnostic. */ #if HEDLEY_HAS_WARNING("-Wvla") #define SIMDE_DIAGNOSTIC_DISABLE_VLA_ _Pragma("clang diagnostic ignored \"-Wvla\"") #elif HEDLEY_GCC_VERSION_CHECK(4,3,0) #define SIMDE_DIAGNOSTIC_DISABLE_VLA_ _Pragma("GCC diagnostic ignored \"-Wvla\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_VLA_ #endif #if HEDLEY_HAS_WARNING("-Wused-but-marked-unused") #define SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_ _Pragma("clang diagnostic ignored \"-Wused-but-marked-unused\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_ #endif #if HEDLEY_HAS_WARNING("-Wunused-function") #define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ _Pragma("clang diagnostic ignored \"-Wunused-function\"") #elif HEDLEY_GCC_VERSION_CHECK(3,4,0) #define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ _Pragma("GCC diagnostic ignored \"-Wunused-function\"") #elif HEDLEY_MSVC_VERSION_CHECK(19,0,0) /* Likely goes back further */ #define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ __pragma(warning(disable:4505)) #else #define SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ #endif #if HEDLEY_HAS_WARNING("-Wpass-failed") #define SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_ _Pragma("clang diagnostic ignored \"-Wpass-failed\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_ #endif #if HEDLEY_HAS_WARNING("-Wpadded") #define SIMDE_DIAGNOSTIC_DISABLE_PADDED_ _Pragma("clang diagnostic ignored \"-Wpadded\"") #elif HEDLEY_MSVC_VERSION_CHECK(19,0,0) /* Likely goes back further */ #define SIMDE_DIAGNOSTIC_DISABLE_PADDED_ __pragma(warning(disable:4324)) #else #define SIMDE_DIAGNOSTIC_DISABLE_PADDED_ #endif #if HEDLEY_HAS_WARNING("-Wzero-as-null-pointer-constant") #define SIMDE_DIAGNOSTIC_DISABLE_ZERO_AS_NULL_POINTER_CONSTANT_ _Pragma("clang diagnostic ignored \"-Wzero-as-null-pointer-constant\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_ZERO_AS_NULL_POINTER_CONSTANT_ #endif #if HEDLEY_HAS_WARNING("-Wold-style-cast") #define SIMDE_DIAGNOSTIC_DISABLE_OLD_STYLE_CAST_ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_OLD_STYLE_CAST_ #endif #if HEDLEY_HAS_WARNING("-Wcast-function-type") || HEDLEY_GCC_VERSION_CHECK(8,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_CAST_FUNCTION_TYPE_ _Pragma("GCC diagnostic ignored \"-Wcast-function-type\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_CAST_FUNCTION_TYPE_ #endif /* clang will emit this warning when we use C99 extensions whan not in * C99 mode, even though it does support this. In such cases we check * the compiler and version first, so we know it's not a problem. */ #if HEDLEY_HAS_WARNING("-Wc99-extensions") #define SIMDE_DIAGNOSTIC_DISABLE_C99_EXTENSIONS_ _Pragma("clang diagnostic ignored \"-Wc99-extensions\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_C99_EXTENSIONS_ #endif /* https://github.com/simd-everywhere/simde/issues/277 */ #if defined(HEDLEY_GCC_VERSION) && HEDLEY_GCC_VERSION_CHECK(4,6,0) && !HEDLEY_GCC_VERSION_CHECK(6,4,0) && defined(__cplusplus) #define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE_ _Pragma("GCC diagnostic ignored \"-Wunused-but-set-variable\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE_ #endif /* This is the warning that you normally define _CRT_SECURE_NO_WARNINGS * to silence, but you have to do that before including anything and * that would require reordering includes. */ #if defined(_MSC_VER) #define SIMDE_DIAGNOSTIC_DISABLE_ANNEX_K_ __pragma(warning(disable:4996)) #else #define SIMDE_DIAGNOSTIC_DISABLE_ANNEX_K_ #endif /* Some compilers, such as clang, may use `long long` for 64-bit * integers, but `long long` triggers a diagnostic with * -Wc++98-compat-pedantic which says 'long long' is incompatible with * C++98. */ #if HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") #define SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC_ _Pragma("clang diagnostic ignored \"-Wc++98-compat-pedantic\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC_ #endif /* Some problem as above */ #if HEDLEY_HAS_WARNING("-Wc++11-long-long") #define SIMDE_DIAGNOSTIC_DISABLE_CPP11_LONG_LONG_ _Pragma("clang diagnostic ignored \"-Wc++11-long-long\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_CPP11_LONG_LONG_ #endif /* emscripten emits this whenever stdin/stdout/stderr is used in a * macro. */ #if HEDLEY_HAS_WARNING("-Wdisabled-macro-expansion") #define SIMDE_DIAGNOSTIC_DISABLE_DISABLED_MACRO_EXPANSION_ _Pragma("clang diagnostic ignored \"-Wdisabled-macro-expansion\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_DISABLED_MACRO_EXPANSION_ #endif /* Clang uses C11 generic selections to implement some AltiVec * functions, which triggers this diagnostic when not compiling * in C11 mode */ #if HEDLEY_HAS_WARNING("-Wc11-extensions") #define SIMDE_DIAGNOSTIC_DISABLE_C11_EXTENSIONS_ _Pragma("clang diagnostic ignored \"-Wc11-extensions\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_C11_EXTENSIONS_ #endif /* Clang sometimes triggers this warning in macros in the AltiVec and * NEON headers, or due to missing functions. */ #if HEDLEY_HAS_WARNING("-Wvector-conversion") #define SIMDE_DIAGNOSTIC_DISABLE_VECTOR_CONVERSION_ _Pragma("clang diagnostic ignored \"-Wvector-conversion\"") /* For NEON, the situation with -Wvector-conversion in clang < 10 is * bad enough that we just disable the warning altogether. */ #if defined(SIMDE_ARCH_ARM) && SIMDE_DETECT_CLANG_VERSION_NOT(10,0,0) #define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_VECTOR_CONVERSION_ SIMDE_DIAGNOSTIC_DISABLE_VECTOR_CONVERSION_ #endif #else #define SIMDE_DIAGNOSTIC_DISABLE_VECTOR_CONVERSION_ #endif #if !defined(SIMDE_DIAGNOSTIC_DISABLE_BUGGY_VECTOR_CONVERSION_) #define SIMDE_DIAGNOSTIC_DISABLE_BUGGY_VECTOR_CONVERSION_ #endif /* SLEEF triggers this a *lot* in their headers */ #if HEDLEY_HAS_WARNING("-Wignored-qualifiers") #define SIMDE_DIAGNOSTIC_DISABLE_IGNORED_QUALIFIERS_ _Pragma("clang diagnostic ignored \"-Wignored-qualifiers\"") #elif HEDLEY_GCC_VERSION_CHECK(4,3,0) #define SIMDE_DIAGNOSTIC_DISABLE_IGNORED_QUALIFIERS_ _Pragma("GCC diagnostic ignored \"-Wignored-qualifiers\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_IGNORED_QUALIFIERS_ #endif /* GCC emits this under some circumstances when using __int128 */ #if HEDLEY_GCC_VERSION_CHECK(4,8,0) #define SIMDE_DIAGNOSTIC_DISABLE_PEDANTIC_ _Pragma("GCC diagnostic ignored \"-Wpedantic\"") #else #define SIMDE_DIAGNOSTIC_DISABLE_PEDANTIC_ #endif /* MSVC doesn't like (__assume(0), code) and will warn about code being * unreachable, but we want it there because not all compilers * understand the unreachable macro and will complain if it is missing. * I'm planning on adding a new macro to Hedley to handle this a bit * more elegantly, but until then... */ #if defined(HEDLEY_MSVC_VERSION) #define SIMDE_DIAGNOSTIC_DISABLE_UNREACHABLE_ __pragma(warning(disable:4702)) #else #define SIMDE_DIAGNOSTIC_DISABLE_UNREACHABLE_ #endif #define SIMDE_DISABLE_UNWANTED_DIAGNOSTICS \ SIMDE_DIAGNOSTIC_DISABLE_PSABI_ \ SIMDE_DIAGNOSTIC_DISABLE_NO_EMMS_INSTRUCTION_ \ SIMDE_DIAGNOSTIC_DISABLE_SIMD_PRAGMA_DEPRECATED_ \ SIMDE_DIAGNOSTIC_DISABLE_CONDITIONAL_UNINITIALIZED_ \ SIMDE_DIAGNOSTIC_DISABLE_FLOAT_EQUAL_ \ SIMDE_DIAGNOSTIC_DISABLE_NON_CONSTANT_AGGREGATE_INITIALIZER_ \ SIMDE_DIAGNOSTIC_DISABLE_EXTRA_SEMI_ \ SIMDE_DIAGNOSTIC_DISABLE_VLA_ \ SIMDE_DIAGNOSTIC_DISABLE_USED_BUT_MARKED_UNUSED_ \ SIMDE_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION_ \ SIMDE_DIAGNOSTIC_DISABLE_PASS_FAILED_ \ SIMDE_DIAGNOSTIC_DISABLE_CPP98_COMPAT_PEDANTIC_ \ SIMDE_DIAGNOSTIC_DISABLE_CPP11_LONG_LONG_ \ SIMDE_DIAGNOSTIC_DISABLE_BUGGY_UNUSED_BUT_SET_VARIBALE_ \ SIMDE_DIAGNOSTIC_DISABLE_BUGGY_VECTOR_CONVERSION_ #endif /* !defined(SIMDE_DIAGNOSTIC_H) */
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "coders/coders-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->alpha_trait != BlendPixelTrait) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); if (image->alpha_trait != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->alpha_trait == UndefinedPixelTrait) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; Quantum *p; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image, const unsigned char *blocks,size_t length) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatImageProperty(image,"tiff:XResolution","%*g", GetMagickPrecision(),image->resolution.x); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatImageProperty(image,"tiff:YResolution","%*g", GetMagickPrecision(),image->resolution.y); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) psd_info->has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length) { ssize_t count; count=ReadBlob(image,length,(unsigned char *) p); if ((count == (ssize_t) length) && (image->endian != MSBEndian)) { char *q; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } return(count); } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; Quantum index; index=pixel; if (packet_size == 1) index=(Quantum) ScaleQuantumToChar(index); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) index, exception); if (type == 0) SetPixelIndex(image,index,q); if ((type == 0) && (channels > 1)) return; color=image->colormap+(ssize_t) GetPixelIndex(image,q); if (type != 0) color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case -3: case 1: { SetPixelGreen(image,pixel,q); break; } case -4: case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; const unsigned char *p; Quantum *q; ssize_t x; size_t packet_size; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { unsigned short nibble; p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble)); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < (ssize_t) number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) /* arbitrary number */ { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static void Unpredict8Bit(const Image *image,unsigned char *pixels, const size_t count,const size_t row_size) { unsigned char *p; size_t length, remaining; p=pixels; remaining=count; while (remaining > 0) { length=image->columns; while (--length) { *(p+1)+=*p; p++; } p++; remaining-=row_size; } } static void Unpredict16Bit(const Image *image,unsigned char *pixels, const size_t count,const size_t row_size) { unsigned char *p; size_t length, remaining; p=pixels; remaining=count; while (remaining > 0) { length=image->columns; while (--length) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; p+=2; } p+=2; remaining-=row_size; } } static void Unpredict32Bit(const Image *image,unsigned char *pixels, unsigned char *output_pixels,const size_t row_size) { unsigned char *p, *q; ssize_t y; size_t offset1, offset2, offset3, remaining; unsigned char *start; offset1=image->columns; offset2=2*offset1; offset3=3*offset1; p=pixels; q=output_pixels; for (y=0; y < (ssize_t) image->rows; y++) { start=p; remaining=row_size; while (--remaining) { *(p+1)+=*p; p++; } p=start; remaining=image->columns; while (remaining--) { *(q++)=*p; *(q++)=*(p+offset1); *(q++)=*(p+offset2); *(q++)=*(p+offset3); p++; } p=start+row_size; } } static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; unsigned char *p; size_t count, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { if (packet_size == 1) Unpredict8Bit(image,pixels,count,row_size); else if (packet_size == 2) Unpredict16Bit(image,pixels,count,row_size); else if (packet_size == 4) { unsigned char *output_pixels; output_pixels=(unsigned char *) AcquireQuantumMemory(count, sizeof(*output_pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } Unpredict32Bit(image,pixels,output_pixels,row_size); pixels=(unsigned char *) RelinquishMagickMemory(pixels); pixels=output_pixels; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); (void) SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0)) return(MagickFalse); if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void AttachPSDLayers(Image *image,LayerInfo *layer_info, ssize_t number_layers) { ssize_t i; ssize_t j; for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers == 0) { layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); return; } for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info, const ImageInfo *image_info,const size_t index) { if (psd_info->has_merged_image == MagickFalse) return(MagickFalse); if (image_info->number_scenes == 0) return(MagickFalse); if (index < image_info->scene) return(MagickTrue); if (index > image_info->scene+image_info->number_scenes-1) return(MagickTrue); return(MagickFalse); } static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image) { /* The number of layers cannot be used to determine if the merged image contains an alpha channel. So we enable it when we think we should. */ if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) || ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) || ((psd_info->mode == CMYKMode) && (psd_info->channels > 4))) image->alpha_trait=BlendPixelTrait; } static void ParseAdditionalInfo(LayerInfo *layer_info) { char key[5]; size_t remaining_length; unsigned char *p; unsigned int size; p=GetStringInfoDatum(layer_info->info); remaining_length=GetStringInfoLength(layer_info->info); while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) break; if (LocaleNCompare(key,"luni",sizeof(key)) == 0) { unsigned char *name; unsigned int length; length=(unsigned int) (*p++) << 24; length|=(unsigned int) (*p++) << 16; length|=(unsigned int) (*p++) << 8; length|=(unsigned int) (*p++); if (length * 2 > size - 4) break; if (sizeof(layer_info->name) <= length) break; name=layer_info->name; while (length > 0) { /* Only ASCII strings are supported */ if (*p++ != '\0') break; *name++=*p++; length--; } if (length == 0) *name='\0'; break; } else p+=size; remaining_length-=(size_t) size; } } static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image) { char type[4]; MagickSizeType size; ssize_t count; size=GetPSDSize(psd_info,image); if (size != 0) return(size); (void) ReadBlobLong(image); count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Mt16",4) == 0) || (LocaleNCompare(type,"Mt32",4) == 0) || (LocaleNCompare(type,"Mtrn",4) == 0))) { size=GetPSDSize(psd_info,image); if (size != 0) return(0); image->alpha_trait=BlendPixelTrait; count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); } if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); return(size); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; ssize_t i; ssize_t count, index, j, number_layers; size=GetLayerInfoSize(psd_info,image); if (size == 0) { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,layer_info[i].blendkey,4); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); ParseAdditionalInfo(&layer_info[i]); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping != MagickFalse) { AttachPSDLayers(image,layer_info,number_layers); return(MagickTrue); } status=MagickTrue; index=0; for (i=0; i < number_layers; i++) { if ((layer_info[i].image == (Image *) NULL) || (PSDSkipImage(psd_info, image_info,++index) != MagickFalse)) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } if (status != MagickFalse) AttachPSDLayers(image,layer_info,number_layers); else layer_info=DestroyLayerInfo(layer_info,number_layers); return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickBooleanType status; status=IsRightsAuthorized(CoderPolicyDomain,ReadPolicyRights,"PSD"); if (status == MagickFalse) return(MagickTrue); return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; ssize_t i; if ((image_info->number_scenes != 0) && (image_info->scene != 0)) return(MagickTrue); compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; ssize_t i; size_t image_list_length; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); psd_info.min_channels=3; switch (psd_info.mode) { case LabMode: { (void) SetImageColorspace(image,LabColorspace,exception); break; } case CMYKMode: { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } case BitmapMode: case GrayscaleMode: case DuotoneMode: { if (psd_info.depth != 32) { status=AcquireImageColormap(image,MagickMin((size_t) (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace,exception); break; } case IndexedMode: { psd_info.min_channels=1; break; } case MultichannelMode: { if ((psd_info.channels > 0) && (psd_info.channels < 3)) { psd_info.min_channels=psd_info.channels; (void) SetImageColorspace(image,GRAYColorspace,exception); } break; } } if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. 32 bits per pixel; the colormap is ignored. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); psd_info.has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (psd_info.has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); image_list_length=GetImageListLength(image); if ((psd_info.has_merged_image != MagickFalse) || (image_list_length == 1)) psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage( image_info,image,&psd_info,exception); if ((psd_info.has_merged_image == MagickFalse) && (image_list_length == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } image_list_length=GetImageListLength(image); } if (psd_info.has_merged_image == MagickFalse) { Image *merged; if (image_list_length == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.alpha=(MagickRealType) TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); merged=MergeImageLayers(image,FlattenLayer,exception); if (merged == (Image *) NULL) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; i=0; next=image; while (next != (Image *) NULL) { if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse) (void) SetImageProfile(next,GetStringInfoName(profile),profile, exception); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobLong(image,(unsigned int) size)); return(WriteBlobLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); result=SetPSDSize(psd_info,image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; ssize_t i, j; unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const CompressionType compression, const ssize_t channels) { size_t length; ssize_t i, y; if (compression == RLECompression) { length=(size_t) WriteBlobShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) length=(size_t) WriteBlobShort(image,ZipWithoutPrediction); #endif else length=(size_t) WriteBlobShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; const Quantum *p; ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory( MagickMinBufferExtent,sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) MagickMinBufferExtent; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) MagickMinBufferExtent-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { CompressionType compression; Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; compression=next_image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if ((next_image->storage_class != PseudoClass) || (IsImageGray(next_image) != MagickFalse)) { if (IsImageGray(next_image) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression, (ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if ((next_image->storage_class == PseudoClass) && (IsImageGray(next_image) == MagickFalse)) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,compression, exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=(size_t) WriteBlobShort(image,(const unsigned short) channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size, ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; ssize_t i; size_t layer_count, layer_index, length, name_length, rounded_size, size; status=MagickTrue; base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobShort(image,-(unsigned short) layer_count); else size+=WriteBlobShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobSignedLong(image,(signed int) next_image->page.y); size+=WriteBlobSignedLong(image,(signed int) next_image->page.x); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+ next_image->rows)); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(psd_info,image,-2); size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM"); size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(const unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobLong(image,20); size+=WriteBlobSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(const unsigned char) (mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } /* Write the total size */ if (layers_size != (size_t*) NULL) *layers_size=size; if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } return(status); } ModuleExport MagickBooleanType WritePSDLayers(Image * image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickBooleanType status; status=IsRightsAuthorized(CoderPolicyDomain,WritePolicyRights,"PSD"); if (status == MagickFalse) return(MagickTrue); return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL, exception); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *icc_profile; ImageType type; MagickBooleanType status; PSDInfo psd_info; ssize_t i; size_t length, num_channels; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ type=IdentifyImageCoderType(image,exception); (void) type; if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } if (status != MagickFalse) { const char *option; MagickOffsetType size_offset; size_t size; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); option=GetImageOption(image_info,"psd:write-layers"); if (IsStringFalse(option) != MagickTrue) { status=WritePSDLayersInternal(image,image_info,&psd_info,&size, exception); (void) WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); } } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
ocp_nlp_common.c
/* * Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, * Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, * Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, * Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl * * This file is part of acados. * * The 2-Clause BSD License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.; */ #include "acados/ocp_nlp/ocp_nlp_common.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <math.h> // blasfeo #include "blasfeo/include/blasfeo_common.h" #include "blasfeo/include/blasfeo_d_blas.h" // hpipm #include "hpipm/include/hpipm_d_ocp_qp_dim.h" // acados #include "acados/utils/mem.h" /************************************************ * config ************************************************/ int ocp_nlp_config_calculate_size(int N) { int ii; int size = 0; // self size += sizeof(ocp_nlp_config); // qp solver size += 1 * ocp_qp_xcond_solver_config_calculate_size(); // regularization size += ocp_nlp_reg_config_calculate_size(); // dynamics size += N * sizeof(ocp_nlp_dynamics_config *); for (ii = 0; ii < N; ii++) size += ocp_nlp_dynamics_config_calculate_size(); // cost size += (N + 1) * sizeof(ocp_nlp_cost_config *); for (ii = 0; ii <= N; ii++) size += ocp_nlp_cost_config_calculate_size(); // constraints size += (N + 1) * sizeof(ocp_nlp_constraints_config *); for (ii = 0; ii <= N; ii++) size += ocp_nlp_constraints_config_calculate_size(); return size; } ocp_nlp_config *ocp_nlp_config_assign(int N, void *raw_memory) { int ii; char *c_ptr = (char *) raw_memory; ocp_nlp_config *config = (ocp_nlp_config *) c_ptr; c_ptr += sizeof(ocp_nlp_config); config->N = N; // qp solver config->qp_solver = ocp_qp_xcond_solver_config_assign(c_ptr); c_ptr += ocp_qp_xcond_solver_config_calculate_size(); // regularization config->regularize = ocp_nlp_reg_config_assign(c_ptr); c_ptr += ocp_nlp_reg_config_calculate_size(); // dynamics config->dynamics = (ocp_nlp_dynamics_config **) c_ptr; c_ptr += N * sizeof(ocp_nlp_dynamics_config *); for (ii = 0; ii < N; ii++) { config->dynamics[ii] = ocp_nlp_dynamics_config_assign(c_ptr); c_ptr += ocp_nlp_dynamics_config_calculate_size(); } // cost config->cost = (ocp_nlp_cost_config **) c_ptr; c_ptr += (N + 1) * sizeof(ocp_nlp_cost_config *); for (ii = 0; ii <= N; ii++) { config->cost[ii] = ocp_nlp_cost_config_assign(c_ptr); c_ptr += ocp_nlp_cost_config_calculate_size(); } // constraints config->constraints = (ocp_nlp_constraints_config **) c_ptr; c_ptr += (N + 1) * sizeof(ocp_nlp_constraints_config *); for (ii = 0; ii <= N; ii++) { config->constraints[ii] = ocp_nlp_constraints_config_assign(c_ptr); c_ptr += ocp_nlp_constraints_config_calculate_size(); } return config; } /************************************************ * dims ************************************************/ static int ocp_nlp_dims_calculate_size_self(int N) { int size = 0; size += sizeof(ocp_nlp_dims); // nlp sizes size += 6 * (N + 1) * sizeof(int); // nv, nx, nu, ni, nz, ns // dynamics size += N * sizeof(void *); // cost size += (N + 1) * sizeof(void *); // constraints size += (N + 1) * sizeof(void *); // regularization size += ocp_nlp_reg_dims_calculate_size(N); size += sizeof(ocp_nlp_reg_dims); size += 8; // initial align return size; } int ocp_nlp_dims_calculate_size(void *config_) { ocp_nlp_config *config = config_; int N = config->N; int ii; int size = 0; // self size += ocp_nlp_dims_calculate_size_self(N); // dynamics for (ii = 0; ii < N; ii++) size += config->dynamics[ii]->dims_calculate_size(config->dynamics[ii]); // cost for (ii = 0; ii <= N; ii++) size += config->cost[ii]->dims_calculate_size(config->cost[ii]); // constraints for (ii = 0; ii <= N; ii++) size += config->constraints[ii]->dims_calculate_size(config->constraints[ii]); // qp solver size += config->qp_solver->dims_calculate_size(config->qp_solver, N); return size; } static ocp_nlp_dims *ocp_nlp_dims_assign_self(int N, void *raw_memory) { char *c_ptr = (char *) raw_memory; int ii; // initial align align_char_to(8, &c_ptr); // struct ocp_nlp_dims *dims = (ocp_nlp_dims *) c_ptr; c_ptr += sizeof(ocp_nlp_dims); // nv assign_and_advance_int(N + 1, &dims->nv, &c_ptr); // nx assign_and_advance_int(N + 1, &dims->nx, &c_ptr); // nu assign_and_advance_int(N + 1, &dims->nu, &c_ptr); // ni assign_and_advance_int(N + 1, &dims->ni, &c_ptr); // nz assign_and_advance_int(N + 1, &dims->nz, &c_ptr); // ns assign_and_advance_int(N + 1, &dims->ns, &c_ptr); // dynamics dims->dynamics = (void **) c_ptr; c_ptr += N * sizeof(void *); // cost dims->cost = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); // constraints dims->constraints = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); // regularization dims->regularize = ocp_nlp_reg_dims_assign(N, c_ptr); c_ptr += ocp_nlp_reg_dims_calculate_size(N); /* initialize qp_solver dimensions */ // dims->qp_solver->N = N; // for (ii = 0; ii <= N; ii++) // { // TODO(dimitris): values below are needed for reformulation of QP when soft constraints // are not supported. Make this a bit more transparent as it clushes with nbx/nbu above. // dims->qp_solver->nsbx[ii] = 0; // dims->qp_solver->nsbu[ii] = 0; // dims->qp_solver->nsg[ii] = 0; // } // N dims->N = N; // initialize dimensions to zero by default // nv for(ii=0; ii<=N; ii++) dims->nv[ii] = 0; // nx for(ii=0; ii<=N; ii++) dims->nx[ii] = 0; // nu for(ii=0; ii<=N; ii++) dims->nu[ii] = 0; // ni for(ii=0; ii<=N; ii++) dims->ni[ii] = 0; // nz for(ii=0; ii<=N; ii++) dims->nz[ii] = 0; // ns for(ii=0; ii<=N; ii++) dims->ns[ii] = 0; // TODO initialize dims to zero by default also in modules !!!!!!! // assert assert((char *) raw_memory + ocp_nlp_dims_calculate_size_self(N) >= c_ptr); return dims; } ocp_nlp_dims *ocp_nlp_dims_assign(void *config_, void *raw_memory) { ocp_nlp_config *config = config_; int N = config->N; int ii; char *c_ptr = (char *) raw_memory; // self ocp_nlp_dims *dims = ocp_nlp_dims_assign_self(N, c_ptr); c_ptr += ocp_nlp_dims_calculate_size_self(N); // dynamics for (ii = 0; ii < N; ii++) { dims->dynamics[ii] = config->dynamics[ii]->dims_assign(config->dynamics[ii], c_ptr); c_ptr += config->dynamics[ii]->dims_calculate_size(config->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { dims->cost[ii] = config->cost[ii]->dims_assign(config->cost[ii], c_ptr); c_ptr += config->cost[ii]->dims_calculate_size(config->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { dims->constraints[ii] = config->constraints[ii]->dims_assign(config->constraints[ii], c_ptr); c_ptr += config->constraints[ii]->dims_calculate_size(config->constraints[ii]); } // qp solver dims->qp_solver = config->qp_solver->dims_assign(config->qp_solver, N, c_ptr); c_ptr += config->qp_solver->dims_calculate_size(config->qp_solver, N); // assert assert((char *) raw_memory + ocp_nlp_dims_calculate_size(config_) >= c_ptr); return dims; } void ocp_nlp_dims_set_opt_vars(void *config_, void *dims_, const char *field, const void* value_array) { // to set dimension nx, nu, nz, ns (number of slacks = number of soft constraints) ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; int ii; int N = config->N; int *int_array = (int *) value_array; /* set ocp_nlp dimension */ if (!strcmp(field, "nx")) { // opt var for (ii = 0; ii <= N; ii++) { // set nx dims->nx[ii] = int_array[ii]; // update nv dims->nv[ii] = dims->nu[ii] + dims->nx[ii] + 2 * dims->ns[ii]; } // cost for (int i = 0; i <= N; i++) { config->cost[i]->dims_set(config->cost[i], dims->cost[i], "nx", &int_array[i]); } // dynamics for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nx", &int_array[i]); } for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nx1", &int_array[i+1]); } // constraints for (int i = 0; i <= N; i++) { config->constraints[i]->dims_set(config->constraints[i], dims->constraints[i], "nx", &int_array[i]); } // qp solver for (int i = 0; i <= N; i++) { config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, "nx", &int_array[i]); } // regularization for (ii = 0; ii <= N; ii++) { config->regularize->dims_set(config->regularize, dims->regularize, ii, "nx", &int_array[ii]); } } else if (!strcmp(field, "nu")) { // nlp opt var for (int ii = 0; ii <= N; ii++) { // set nu dims->nu[ii] = int_array[ii]; // update nv dims->nv[ii] = dims->nu[ii] + dims->nx[ii] + 2 * dims->ns[ii]; } // cost for (int i = 0; i <= N; i++) { config->cost[i]->dims_set(config->cost[i], dims->cost[i], "nu", &int_array[i]); } // dynamics for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nu", &int_array[i]); } for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nu1", &int_array[i+1]); } // constraints for (int i = 0; i <= N; i++) { config->constraints[i]->dims_set(config->constraints[i], dims->constraints[i], "nu", &int_array[i]); } // qp solver for (int i = 0; i <= N; i++) { config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, "nu", &int_array[i]); } // regularization for (ii = 0; ii <= N; ii++) { config->regularize->dims_set(config->regularize, dims->regularize, ii, "nu", &int_array[ii]); } } else if (!strcmp(field, "nz")) { // nlp opt var for (int ii = 0; ii <= N; ii++) { // set nz dims->nz[ii] = int_array[ii]; } // cost for (int i = 0; i <= N; i++) { config->cost[i]->dims_set(config->cost[i], dims->cost[i], "nz", &int_array[i]); } // dynamics for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nz", &int_array[i]); } // constraints for (int i = 0; i <= N; i++) { config->constraints[i]->dims_set(config->constraints[i], dims->constraints[i], "nz", &int_array[i]); } } else if (!strcmp(field, "ns")) { // nlp opt var for (int ii = 0; ii <= N; ii++) { // set ns dims->ns[ii] = int_array[ii]; // update nv dims->nv[ii] = dims->nu[ii] + dims->nx[ii] + 2 * dims->ns[ii]; } // cost for (int i = 0; i <= N; i++) { config->cost[i]->dims_set(config->cost[i], dims->cost[i], "ns", &int_array[i]); } // qp solver for (int i = 0; i <= N; i++) { config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, "ns", &int_array[i]); } } else { printf("error: dims type not available in module ocp_nlp: %s", field); exit(1); } #if 0 /* set ocp_nlp submodule dimensions */ if (strcmp(field, "ns")) // dynamics do not contain slack/soft constraints { for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], field, &int_array[i]); } } if (!strcmp(field, "nu")) { for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nu1", &int_array[i+1]); } } if (!strcmp(field, "nx")) { for (int i = 0; i < N; i++) { config->dynamics[i]->dims_set(config->dynamics[i], dims->dynamics[i], "nx1", &int_array[i+1]); } } for (int i = 0; i <= N; i++) // cost { config->cost[i]->dims_set(config->cost[i], dims->cost[i], field, &int_array[i]); } for (int i = 0; i <= N; i++) // constraints { config->constraints[i]->dims_set(config->constraints[i], dims->constraints[i], field, &int_array[i]); } if (strcmp(field, "nz")) // qp_solver does not contain nz { for (int i = 0; i <= N; i++) // qp_solver { config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, field, &int_array[i]); } } #endif return; } void ocp_nlp_dims_set_constraints(void *config_, void *dims_, int stage, const char *field, const void* value_) { // to set dimension nbx, nbu, ng, nh, nq (quadratic over nonlinear) ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; int *int_value = (int *) value_; int i = stage; // set in constraint module config->constraints[i]->dims_set(config->constraints[i], dims->constraints[i], field, int_value); // update ni in ocp_nlp dimensions config->constraints[i]->dims_get(config->constraints[i], dims->constraints[i], "ni", &dims->ni[i]); // update qp_solver dims if ( (!strcmp(field, "nbx")) || (!strcmp(field, "nbu")) ) { // qp solver config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, field, int_value); // regularization config->regularize->dims_set(config->regularize, dims->regularize, i, (char *) field, int_value); } else if ( (!strcmp(field, "nsbx")) || (!strcmp(field, "nsbu")) ) { // qp solver config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, field, int_value); } else if ( (!strcmp(field, "ng")) || (!strcmp(field, "nh")) || (!strcmp(field, "nphi"))) { // update ng_qp_solver in qp_solver int ng_qp_solver; config->constraints[i]->dims_get(config->constraints[i], dims->constraints[i], "ng_qp_solver", &ng_qp_solver); // qp solver config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, "ng", &ng_qp_solver); // regularization config->regularize->dims_set(config->regularize, dims->regularize, i, "ng", &ng_qp_solver); } else if ( (!strcmp(field, "nsg")) || (!strcmp(field, "nsh")) || (!strcmp(field, "nsphi"))) { // update ng_qp_solver in qp_solver int nsg_qp_solver; config->constraints[i]->dims_get(config->constraints[i], dims->constraints[i], "nsg_qp_solver", &nsg_qp_solver); // qp solver config->qp_solver->dims_set(config->qp_solver, dims->qp_solver, i, "nsg", &nsg_qp_solver); } return; } void ocp_nlp_dims_set_cost(void *config_, void *dims_, int stage, const char *field, const void* value_) { // to set dimension ny (output) ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; int *int_value = (int *) value_; config->cost[stage]->dims_set(config->cost[stage], dims->cost[stage], field, int_value); } void ocp_nlp_dims_set_dynamics(void *config_, void *dims_, int stage, const char *field, const void* value) { // mainly for gnsf dimensions ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; int *int_value = (int *) value; config->dynamics[stage]->dims_set(config->dynamics[stage], dims->dynamics[stage], field, int_value); } /************************************************ * in ************************************************/ int ocp_nlp_in_calculate_size_self(int N) { int size = sizeof(ocp_nlp_in); size += N * sizeof(double); // Ts size += N * sizeof(void *); // dynamics size += (N + 1) * sizeof(void *); // cost size += (N + 1) * sizeof(void *); // constraints return size; } int ocp_nlp_in_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims) { int ii; int N = dims->N; int size = ocp_nlp_in_calculate_size_self(N); // dynamics for (ii = 0; ii < N; ii++) { size += config->dynamics[ii]->model_calculate_size(config->dynamics[ii], dims->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { size += config->cost[ii]->model_calculate_size(config->cost[ii], dims->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { size += config->constraints[ii]->model_calculate_size(config->constraints[ii], dims->constraints[ii]); } size += 8; // initial align // make_int_multiple_of(64, &size); return size; } ocp_nlp_in *ocp_nlp_in_assign_self(int N, void *raw_memory) { char *c_ptr = (char *) raw_memory; // initial align align_char_to(8, &c_ptr); // struct ocp_nlp_in *in = (ocp_nlp_in *) c_ptr; c_ptr += sizeof(ocp_nlp_in); // Ts in->Ts = (double *) c_ptr; c_ptr += N * sizeof(double); // dynamics in->dynamics = (void **) c_ptr; c_ptr += N * sizeof(void *); // cost in->cost = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); // constraints in->constraints = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); return in; } ocp_nlp_in *ocp_nlp_in_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, void *raw_memory) { int ii; int N = dims->N; char *c_ptr = (char *) raw_memory; // struct ocp_nlp_in *in = ocp_nlp_in_assign_self(N, c_ptr); c_ptr += ocp_nlp_in_calculate_size_self(N); // dynamics for (ii = 0; ii < N; ii++) { in->dynamics[ii] = config->dynamics[ii]->model_assign(config->dynamics[ii], dims->dynamics[ii], c_ptr); c_ptr += config->dynamics[ii]->model_calculate_size(config->dynamics[ii], dims->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { in->cost[ii] = config->cost[ii]->model_assign(config->cost[ii], dims->cost[ii], c_ptr); c_ptr += config->cost[ii]->model_calculate_size(config->cost[ii], dims->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { in->constraints[ii] = config->constraints[ii]->model_assign(config->constraints[ii], dims->constraints[ii], c_ptr); c_ptr += config->constraints[ii]->model_calculate_size(config->constraints[ii], dims->constraints[ii]); } assert((char *) raw_memory + ocp_nlp_in_calculate_size(config, dims) >= c_ptr); return in; } /************************************************ * out ************************************************/ int ocp_nlp_out_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims) { // extract dims int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; int *nz = dims->nz; int size = sizeof(ocp_nlp_out); size += 4 * (N + 1) * sizeof(struct blasfeo_dvec); // ux, lam, t, z size += 1 * N * sizeof(struct blasfeo_dvec); // pi for (int ii = 0; ii < N; ii++) { size += 1 * blasfeo_memsize_dvec(nv[ii]); // ux size += 1 * blasfeo_memsize_dvec(nz[ii]); // z size += 2 * blasfeo_memsize_dvec(2 * ni[ii]); // lam, t size += 1 * blasfeo_memsize_dvec(nx[ii + 1]); // pi } size += 1 * blasfeo_memsize_dvec(nv[N]); // ux size += 1 * blasfeo_memsize_dvec(nz[N]); // z size += 2 * blasfeo_memsize_dvec(2 * ni[N]); // lam, t size += 8; // initial align size += 8; // blasfeo_struct align size += 64; // blasfeo_mem align // make_int_multiple_of(64, &size); return size; } ocp_nlp_out *ocp_nlp_out_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, void *raw_memory) { // loop index int ii; // extract sizes int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; int *nz = dims->nz; char *c_ptr = (char *) raw_memory; // initial align align_char_to(8, &c_ptr); ocp_nlp_out *out = (ocp_nlp_out *) c_ptr; c_ptr += sizeof(ocp_nlp_out); // blasfeo_struct align align_char_to(8, &c_ptr); // blasfeo_dvec_struct // ux assign_and_advance_blasfeo_dvec_structs(N + 1, &out->ux, &c_ptr); // z assign_and_advance_blasfeo_dvec_structs(N + 1, &out->z, &c_ptr); // pi assign_and_advance_blasfeo_dvec_structs(N, &out->pi, &c_ptr); // lam assign_and_advance_blasfeo_dvec_structs(N + 1, &out->lam, &c_ptr); // t assign_and_advance_blasfeo_dvec_structs(N + 1, &out->t, &c_ptr); // blasfeo_mem align align_char_to(64, &c_ptr); // blasfeo_dvec // ux for (int ii = 0; ii <= N; ++ii) { assign_and_advance_blasfeo_dvec_mem(nv[ii], out->ux + ii, &c_ptr); } // z for (int ii = 0; ii <= N; ++ii) { assign_and_advance_blasfeo_dvec_mem(nz[ii], out->z + ii, &c_ptr); } // pi for (int ii = 0; ii < N; ++ii) { assign_and_advance_blasfeo_dvec_mem(nx[ii + 1], out->pi + ii, &c_ptr); } // lam for (int ii = 0; ii <= N; ++ii) { assign_and_advance_blasfeo_dvec_mem(2 * ni[ii], out->lam + ii, &c_ptr); } // t for (int ii = 0; ii <= N; ++ii) { assign_and_advance_blasfeo_dvec_mem(2 * ni[ii], out->t + ii, &c_ptr); } // zero solution for(ii=0; ii<N; ii++) { blasfeo_dvecse(nv[ii], 0.0, out->ux+ii, 0); blasfeo_dvecse(nz[ii], 0.0, out->z+ii, 0); blasfeo_dvecse(nx[ii+1], 0.0, out->pi+ii, 0); blasfeo_dvecse(2*ni[ii], 0.0, out->lam+ii, 0); blasfeo_dvecse(2*ni[ii], 0.0, out->t+ii, 0); } ii = N; blasfeo_dvecse(nv[ii], 0.0, out->ux+ii, 0); blasfeo_dvecse(nz[ii], 0.0, out->z+ii, 0); blasfeo_dvecse(2*ni[ii], 0.0, out->lam+ii, 0); blasfeo_dvecse(2*ni[ii], 0.0, out->t+ii, 0); assert((char *) raw_memory + ocp_nlp_out_calculate_size(config, dims) >= c_ptr); return out; } /************************************************ * options ************************************************/ int ocp_nlp_opts_calculate_size(void *config_, void *dims_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; int N = dims->N; int size = 0; size += sizeof(ocp_nlp_opts); size += qp_solver->opts_calculate_size(qp_solver, dims->qp_solver); size += config->regularize->opts_calculate_size(); // dynamics size += N * sizeof(void *); for (int ii = 0; ii < N; ii++) { size += dynamics[ii]->opts_calculate_size(dynamics[ii], dims->dynamics[ii]); } // cost size += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { size += cost[ii]->opts_calculate_size(cost[ii], dims->cost[ii]); } // constraints size += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { size += constraints[ii]->opts_calculate_size(constraints[ii], dims->constraints[ii]); } return size; } void *ocp_nlp_opts_assign(void *config_, void *dims_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; int N = dims->N; char *c_ptr = (char *) raw_memory; ocp_nlp_opts *opts = (ocp_nlp_opts *) c_ptr; c_ptr += sizeof(ocp_nlp_opts); opts->qp_solver_opts = qp_solver->opts_assign(qp_solver, dims->qp_solver, c_ptr); c_ptr += qp_solver->opts_calculate_size(qp_solver, dims->qp_solver); opts->regularize = config->regularize->opts_assign(c_ptr); c_ptr += config->regularize->opts_calculate_size(); // dynamics opts->dynamics = (void **) c_ptr; c_ptr += N * sizeof(void *); for (int ii = 0; ii < N; ii++) { opts->dynamics[ii] = dynamics[ii]->opts_assign(dynamics[ii], dims->dynamics[ii], c_ptr); c_ptr += dynamics[ii]->opts_calculate_size(dynamics[ii], dims->dynamics[ii]); } // cost opts->cost = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { opts->cost[ii] = cost[ii]->opts_assign(cost[ii], dims->cost[ii], c_ptr); c_ptr += cost[ii]->opts_calculate_size(cost[ii], dims->cost[ii]); } // constraints opts->constraints = (void **) c_ptr; c_ptr += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { opts->constraints[ii] = constraints[ii]->opts_assign(constraints[ii], dims->constraints[ii], c_ptr); c_ptr += constraints[ii]->opts_calculate_size(constraints[ii], dims->constraints[ii]); } assert((char *) raw_memory + ocp_nlp_opts_calculate_size(config, dims) >= c_ptr); return opts; } void ocp_nlp_opts_initialize_default(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_opts *opts = opts_; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; ocp_nlp_reg_config *regularize = config->regularize; int ii; int N = dims->N; opts->reuse_workspace = 1; #if defined(ACADOS_WITH_OPENMP) opts->num_threads = ACADOS_NUM_THREADS; #endif opts->step_length = 1.0; // submodules opts // qp solver qp_solver->opts_initialize_default(qp_solver, dims->qp_solver, opts->qp_solver_opts); // regularization regularize->opts_initialize_default(regularize, dims->regularize, opts->regularize); // dynamics for (ii = 0; ii < N; ii++) { dynamics[ii]->opts_initialize_default(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { cost[ii]->opts_initialize_default(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { constraints[ii]->opts_initialize_default(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } return; } void ocp_nlp_opts_update(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_opts *opts = opts_; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; int ii; int N = dims->N; qp_solver->opts_update(qp_solver, dims->qp_solver, opts->qp_solver_opts); // dynamics for (ii = 0; ii < N; ii++) { dynamics[ii]->opts_update(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { cost[ii]->opts_update(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { constraints[ii]->opts_update(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } return; } void ocp_nlp_opts_set(void *config_, void *opts_, const char *field, void* value) { ocp_nlp_opts *opts = (ocp_nlp_opts *) opts_; ocp_nlp_config *config = config_; int ii; char module[MAX_STR_LEN]; char *ptr_module = NULL; int module_length = 0; // extract module name, i.e. substring in field before '_' char *char_ = strchr(field, '_'); if (char_!=NULL) { module_length = char_-field; for (ii=0; ii<module_length; ii++) module[ii] = field[ii]; module[module_length] = '\0'; // add end of string ptr_module = module; } // pass options to QP module if ( ptr_module!=NULL && (!strcmp(ptr_module, "qp")) ) { config->qp_solver->opts_set(config->qp_solver, opts->qp_solver_opts, field+module_length+1, value); } // pass options to dynamics module else // nlp opts { if (!strcmp(field, "reuse_workspace")) { int* reuse_workspace = (int *) value; opts->reuse_workspace = *reuse_workspace; } else if (!strcmp(field, "num_threads")) { int* num_threads = (int *) value; opts->num_threads = *num_threads; } else if (!strcmp(field, "step_length")) { double* step_length = (double *) value; opts->step_length = *step_length; } else if (!strcmp(field, "exact_hess")) { int N = config->N; // cost for (ii=0; ii<=N; ii++) config->cost[ii]->opts_set(config->cost[ii], opts->cost[ii], "exact_hess", value); // dynamics for (ii=0; ii<N; ii++) config->dynamics[ii]->opts_set(config->dynamics[ii], opts->dynamics[ii], "compute_hess", value); // constraints TODO disabled for now as prevents convergence !!! // for (ii=0; ii<=N; ii++) // config->constraints[ii]->opts_set(config->constraints[ii], opts->constraints[ii], "compute_hess", value); } else { printf("\nerror: ocp_nlp_opts_set: wrong field: %s\n", field); exit(1); } } return; } void ocp_nlp_opts_set_at_stage(void *config_, void *opts_, int stage, const char *field, void* value) { ocp_nlp_opts *opts = (ocp_nlp_opts *) opts_; ocp_nlp_config *config = config_; int ii; char module[MAX_STR_LEN]; char *ptr_module = NULL; int module_length = 0; // extract module name char *char_ = strchr(field, '_'); if (char_!=NULL) { module_length = char_-field; for (ii=0; ii<module_length; ii++) module[ii] = field[ii]; module[module_length] = '\0'; // add end of string ptr_module = module; } // pass options to dynamics module if ( ptr_module!=NULL && (!strcmp(ptr_module, "dynamics")) ) { config->dynamics[stage]->opts_set( config->dynamics[stage], opts->dynamics[stage], field+module_length+1, value ); } // pass options to cost module else if ( ptr_module!=NULL && (!strcmp(ptr_module, "cost")) ) { config->cost[stage]->opts_set( config->cost[stage], opts->cost[stage], field+module_length+1, value); } // pass options to constraint module else if ( ptr_module!=NULL && (!strcmp(ptr_module, "constraints")) ) { config->constraints[stage]->opts_set( config->constraints[stage], opts->constraints[stage], (char *) field+module_length+1, value); } else { printf("\nerror: ocp_nlp_opts_set_at_stage: wrong field: %s\n", field); exit(1); } return; } /************************************************ * memory ************************************************/ int ocp_nlp_memory_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts) { ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; // extract dims int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; int *nz = dims->nz; int *nu = dims->nu; int *ni = dims->ni; int size = sizeof(ocp_nlp_memory); // qp in size += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // qp out size += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); // qp solver size += qp_solver->memory_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // regularization size += config->regularize->memory_calculate_size(config->regularize, dims->regularize, opts->regularize); // dynamics size += N * sizeof(void *); for (int ii = 0; ii < N; ii++) { size += dynamics[ii]->memory_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost size += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { size += cost[ii]->memory_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints size += (N + 1) * sizeof(void *); for (int ii = 0; ii <= N; ii++) { size += constraints[ii]->memory_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } size += (N+1)*sizeof(bool); // set_sim_guess size += (N+1)*sizeof(struct blasfeo_dmat); // dzduxt size += 6*(N+1)*sizeof(struct blasfeo_dvec); // cost_grad ineq_fun ineq_adj dyn_adj sim_guess z_alg size += 1*N*sizeof(struct blasfeo_dvec); // dyn_fun for (int ii = 0; ii < N; ii++) { size += 1*blasfeo_memsize_dmat(nu[ii]+nx[ii], nz[ii]); // dzduxt size += 1*blasfeo_memsize_dvec(nz[ii]); // z_alg size += 2*blasfeo_memsize_dvec(nv[ii]); // cost_grad ineq_adj size += 1*blasfeo_memsize_dvec(nu[ii] + nx[ii]); // dyn_adj size += 1*blasfeo_memsize_dvec(nx[ii + 1]); // dyn_fun size += 1*blasfeo_memsize_dvec(2 * ni[ii]); // ineq_fun size += 1*blasfeo_memsize_dvec(nx[ii] + nz[ii]); // sim_guess } size += 1*blasfeo_memsize_dmat(nu[N]+nx[N], nz[N]); // dzduxt size += 1*blasfeo_memsize_dvec(nz[N]); // z_alg size += 2*blasfeo_memsize_dvec(nv[N]); // cost_grad ineq_adj size += 1*blasfeo_memsize_dvec(nu[N] + nx[N]); // dyn_adj size += 1*blasfeo_memsize_dvec(2 * ni[N]); // ineq_fun size += 1*blasfeo_memsize_dvec(nx[N] + nz[N]); // sim_guess size += 8; // initial align size += 8; // middle align size += 8; // blasfeo_struct align size += 64; // blasfeo_mem align make_int_multiple_of(8, &size); return size; } ocp_nlp_memory *ocp_nlp_memory_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts, void *raw_memory) { ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; // extract sizes int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; int *nz = dims->nz; int *nu = dims->nu; int *ni = dims->ni; char *c_ptr = (char *) raw_memory; // initial align align_char_to(8, &c_ptr); // struct ocp_nlp_memory *mem = (ocp_nlp_memory *) c_ptr; c_ptr += sizeof(ocp_nlp_memory); // dynamics mem->dynamics = (void **) c_ptr; c_ptr += N*sizeof(void *); // cost mem->cost = (void **) c_ptr; c_ptr += (N+1)*sizeof(void *); // constraints mem->constraints = (void **) c_ptr; c_ptr += (N+1)*sizeof(void *); // middle align align_char_to(8, &c_ptr); // qp in mem->qp_in = ocp_qp_in_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // qp out mem->qp_out = ocp_qp_out_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); // QP solver mem->qp_solver_mem = qp_solver->memory_assign(qp_solver, dims->qp_solver, opts->qp_solver_opts, c_ptr); c_ptr += qp_solver->memory_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // regularization mem->regularize_mem = config->regularize->memory_assign(config->regularize, dims->regularize, opts->regularize, c_ptr); c_ptr += config->regularize->memory_calculate_size(config->regularize, dims->regularize, opts->regularize); // dynamics for (int ii = 0; ii < N; ii++) { mem->dynamics[ii] = dynamics[ii]->memory_assign(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii], c_ptr); c_ptr += dynamics[ii]->memory_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (int ii = 0; ii <= N; ii++) { mem->cost[ii] = cost[ii]->memory_assign(cost[ii], dims->cost[ii], opts->cost[ii], c_ptr); c_ptr += cost[ii]->memory_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (int ii = 0; ii <= N; ii++) { mem->constraints[ii] = constraints[ii]->memory_assign(constraints[ii], dims->constraints[ii], opts->constraints[ii], c_ptr); c_ptr += constraints[ii]->memory_calculate_size( constraints[ii], dims->constraints[ii], opts->constraints[ii]); } // set_sim_guess assign_and_advance_bool(N+1, &mem->set_sim_guess, &c_ptr); for (int ii = 0; ii <= N; ++ii) { mem->set_sim_guess[ii] = false; } // blasfeo_struct align align_char_to(8, &c_ptr); // dzduxt mem->dzduxt = (struct blasfeo_dmat *) c_ptr; c_ptr += (N+1)*sizeof(struct blasfeo_dmat); // z_alg mem->z_alg = (struct blasfeo_dvec *) c_ptr; c_ptr += (N+1)*sizeof(struct blasfeo_dvec); // cost_grad assign_and_advance_blasfeo_dvec_structs(N + 1, &mem->cost_grad, &c_ptr); // ineq_fun assign_and_advance_blasfeo_dvec_structs(N + 1, &mem->ineq_fun, &c_ptr); // ineq_adj assign_and_advance_blasfeo_dvec_structs(N + 1, &mem->ineq_adj, &c_ptr); // dyn_fun assign_and_advance_blasfeo_dvec_structs(N, &mem->dyn_fun, &c_ptr); // dyn_adj assign_and_advance_blasfeo_dvec_structs(N + 1, &mem->dyn_adj, &c_ptr); // sim_guess assign_and_advance_blasfeo_dvec_structs(N + 1, &mem->sim_guess, &c_ptr); // blasfeo_mem align align_char_to(64, &c_ptr); // dzduxt for (int ii=0; ii<=N; ii++) { blasfeo_create_dmat(nu[ii]+nx[ii], nz[ii], mem->dzduxt+ii, c_ptr); c_ptr += blasfeo_memsize_dmat(nu[ii]+nx[ii], nz[ii]); } // z_alg for (int ii=0; ii<=N; ii++) { blasfeo_create_dvec(nz[ii], mem->z_alg+ii, c_ptr); c_ptr += blasfeo_memsize_dvec(nz[ii]); } // cost_grad for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(nv[ii], mem->cost_grad + ii, &c_ptr); } // ineq_fun for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(2 * ni[ii], mem->ineq_fun + ii, &c_ptr); } // ineq_adj for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(nv[ii], mem->ineq_adj + ii, &c_ptr); } // dyn_fun for (int ii = 0; ii < N; ii++) { assign_and_advance_blasfeo_dvec_mem(nx[ii + 1], mem->dyn_fun + ii, &c_ptr); } // dyn_adj for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(nu[ii] + nx[ii], mem->dyn_adj + ii, &c_ptr); } // sim_guess for (int ii = 0; ii <= N; ++ii) { assign_and_advance_blasfeo_dvec_mem(nx[ii] + nz[ii], mem->sim_guess + ii, &c_ptr); // set to 0; blasfeo_dvecse(nx[ii] + nz[ii], 0.0, mem->sim_guess+ii, 0); // printf("sim_guess ii %d: %p\n", ii, mem->sim_guess+ii); } // printf("created memory %p\n", mem); return mem; } /************************************************ * workspace ************************************************/ int ocp_nlp_workspace_calculate_size(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts) { ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; int ii; int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; int size = 0; int size_tmp = 0; int tmp; // nlp size += sizeof(ocp_nlp_workspace); // tmp_nlp_out size += ocp_nlp_out_calculate_size(config, dims); // weights_nlp_out size += ocp_nlp_out_calculate_size(config, dims); // array of pointers // cost size += (N+1)*sizeof(void *); // dynamics size += N*sizeof(void *); // constraints size += (N+1)*sizeof(void *); // module workspace if (opts->reuse_workspace) { #if defined(ACADOS_WITH_OPENMP) // qp solver size += qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // dynamics for (ii = 0; ii < N; ii++) { size += dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { size += cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { size += constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } #else // qp solver tmp = qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); size_tmp = tmp > size_tmp ? tmp : size_tmp; // dynamics for (ii = 0; ii < N; ii++) { tmp = dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } // cost for (ii = 0; ii <= N; ii++) { tmp = cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } // constraints for (ii = 0; ii <= N; ii++) { tmp = constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } size += size_tmp; #endif } else { // qp solver size += qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // dynamics for (ii = 0; ii < N; ii++) { size += dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (ii = 0; ii <= N; ii++) { size += cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (ii = 0; ii <= N; ii++) { size += constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } } return size; } ocp_nlp_workspace *ocp_nlp_workspace_assign(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_opts *opts, ocp_nlp_memory *mem, void *raw_memory) { ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_dynamics_config **dynamics = config->dynamics; ocp_nlp_cost_config **cost = config->cost; ocp_nlp_constraints_config **constraints = config->constraints; int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; char *c_ptr = (char *) raw_memory; ocp_nlp_workspace *work = (ocp_nlp_workspace *) c_ptr; c_ptr += sizeof(ocp_nlp_workspace); // tmp_nlp_out work->tmp_nlp_out = ocp_nlp_out_assign(config, dims, c_ptr); c_ptr += ocp_nlp_out_calculate_size(config, dims); // weights_nlp_out work->weights_nlp_out = ocp_nlp_out_assign(config, dims, c_ptr); c_ptr += ocp_nlp_out_calculate_size(config, dims); // array of pointers // work->dynamics = (void **) c_ptr; c_ptr += N*sizeof(void *); // work->cost = (void **) c_ptr; c_ptr += (N+1)*sizeof(void *); // work->constraints = (void **) c_ptr; c_ptr += (N+1)*sizeof(void *); if (opts->reuse_workspace) { #if defined(ACADOS_WITH_OPENMP) // qp solver work->qp_work = (void *) c_ptr; c_ptr += qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // dynamics for (int ii = 0; ii < N; ii++) { work->dynamics[ii] = c_ptr; c_ptr += dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (int ii = 0; ii <= N; ii++) { work->cost[ii] = c_ptr; c_ptr += cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (int ii = 0; ii <= N; ii++) { work->constraints[ii] = c_ptr; c_ptr += constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } #else int size_tmp = 0; int tmp; // qp solver work->qp_work = (void *) c_ptr; tmp = qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); size_tmp = tmp > size_tmp ? tmp : size_tmp; // dynamics for (int ii = 0; ii < N; ii++) { work->dynamics[ii] = c_ptr; tmp = dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } // cost for (int ii = 0; ii <= N; ii++) { work->cost[ii] = c_ptr; tmp = cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } // constraints for (int ii = 0; ii <= N; ii++) { work->constraints[ii] = c_ptr; tmp = constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); size_tmp = tmp > size_tmp ? tmp : size_tmp; } c_ptr += size_tmp; #endif } else { // qp solver work->qp_work = (void *) c_ptr; c_ptr += qp_solver->workspace_calculate_size(qp_solver, dims->qp_solver, opts->qp_solver_opts); // dynamics for (int ii = 0; ii < N; ii++) { work->dynamics[ii] = c_ptr; c_ptr += dynamics[ii]->workspace_calculate_size(dynamics[ii], dims->dynamics[ii], opts->dynamics[ii]); } // cost for (int ii = 0; ii <= N; ii++) { work->cost[ii] = c_ptr; c_ptr += cost[ii]->workspace_calculate_size(cost[ii], dims->cost[ii], opts->cost[ii]); } // constraints for (int ii = 0; ii <= N; ii++) { work->constraints[ii] = c_ptr; c_ptr += constraints[ii]->workspace_calculate_size(constraints[ii], dims->constraints[ii], opts->constraints[ii]); } } assert((char *) work + ocp_nlp_workspace_calculate_size(config, dims, opts) >= c_ptr); return work; } /************************************************ * functions ************************************************/ void ocp_nlp_initialize_qp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int ii; int N = dims->N; #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (ii = 0; ii <= N; ii++) { // cost config->cost[ii]->initialize(config->cost[ii], dims->cost[ii], in->cost[ii], opts->cost[ii], mem->cost[ii], work->cost[ii]); // dynamics if (ii < N) config->dynamics[ii]->initialize(config->dynamics[ii], dims->dynamics[ii], in->dynamics[ii], opts->dynamics[ii], mem->dynamics[ii], work->dynamics[ii]); // constraints config->constraints[ii]->initialize(config->constraints[ii], dims->constraints[ii], in->constraints[ii], opts->constraints[ii], mem->constraints[ii], work->constraints[ii]); } return; } void ocp_nlp_approximate_qp_matrices(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; int *nu = dims->nu; int *ni = dims->ni; /* stage-wise multiple shooting lagrangian evaluation */ #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i = 0; i <= N; i++) { // init Hessian to 0 blasfeo_dgese(nu[i] + nx[i], nu[i] + nx[i], 0.0, mem->qp_in->RSQrq+i, 0, 0); // dynamics if (i < N) config->dynamics[i]->update_qp_matrices(config->dynamics[i], dims->dynamics[i], in->dynamics[i], opts->dynamics[i], mem->dynamics[i], work->dynamics[i]); // cost config->cost[i]->update_qp_matrices(config->cost[i], dims->cost[i], in->cost[i], opts->cost[i], mem->cost[i], work->cost[i]); // constraints config->constraints[i]->update_qp_matrices(config->constraints[i], dims->constraints[i], in->constraints[i], opts->constraints[i], mem->constraints[i], work->constraints[i]); } /* collect stage-wise evaluations */ #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i=0; i <= N; i++) { // nlp mem: cost_grad struct blasfeo_dvec *cost_grad = config->cost[i]->memory_get_grad_ptr(mem->cost[i]); blasfeo_dveccp(nv[i], cost_grad, 0, mem->cost_grad + i, 0); // nlp mem: dyn_fun if (i < N) { struct blasfeo_dvec *dyn_fun = config->dynamics[i]->memory_get_fun_ptr(mem->dynamics[i]); blasfeo_dveccp(nx[i + 1], dyn_fun, 0, mem->dyn_fun + i, 0); } // nlp mem: dyn_adj if (i < N) { struct blasfeo_dvec *dyn_adj = config->dynamics[i]->memory_get_adj_ptr(mem->dynamics[i]); blasfeo_dveccp(nu[i] + nx[i], dyn_adj, 0, mem->dyn_adj + i, 0); } else { blasfeo_dvecse(nu[N] + nx[N], 0.0, mem->dyn_adj + N, 0); } if (i > 0) { struct blasfeo_dvec *dyn_adj = config->dynamics[i-1]->memory_get_adj_ptr(mem->dynamics[i-1]); blasfeo_daxpy(nx[i], 1.0, dyn_adj, nu[i-1]+nx[i-1], mem->dyn_adj+i, nu[i], mem->dyn_adj+i, nu[i]); } // nlp mem: ineq_fun struct blasfeo_dvec *ineq_fun = config->constraints[i]->memory_get_fun_ptr(mem->constraints[i]); blasfeo_dveccp(2 * ni[i], ineq_fun, 0, mem->ineq_fun + i, 0); // nlp mem: ineq_adj struct blasfeo_dvec *ineq_adj = config->constraints[i]->memory_get_adj_ptr(mem->constraints[i]); blasfeo_dveccp(nv[i], ineq_adj, 0, mem->ineq_adj + i, 0); } for (i = 0; i <= N; i++) { // TODO(rien) where should the update happen??? move to qp update ??? // TODO(all): fix and move where appropriate // if (i<N) // { // ocp_nlp_dynamics_opts *dynamics_opts = opts->dynamics[i]; // sim_opts *opts = dynamics_opts->sim_solver; // if (opts->scheme != NULL && opts->scheme->type != exact) // { // for (int_t j = 0; j < nx; j++) // BLASFEO_DVECEL(nlp_mem->cost_grad+i, nu+j) += work->sim_out[i]->grad[j]; // for (int_t j = 0; j < nu; j++) // BLASFEO_DVECEL(nlp_mem->cost_grad+i, j) += work->sim_out[i]->grad[nx+j]; // } // } } return; } // update QP rhs for SQP (step prim var, abs dual var) // TODO(all): move in dynamics, cost, constraints modules ??? void ocp_nlp_approximate_qp_vectors_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i = 0; i <= N; i++) { // g blasfeo_dveccp(nv[i], mem->cost_grad + i, 0, mem->qp_in->rqz + i, 0); // b if (i < N) blasfeo_dveccp(nx[i + 1], mem->dyn_fun + i, 0, mem->qp_in->b + i, 0); // d blasfeo_dveccp(2 * ni[i], mem->ineq_fun + i, 0, mem->qp_in->d + i, 0); } return; } void ocp_nlp_embed_initial_value(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int *ni = dims->ni; // constraints config->constraints[0]->bounds_update(config->constraints[0], dims->constraints[0], in->constraints[0], opts->constraints[0], mem->constraints[0], work->constraints[0]); // nlp mem: ineq_fun struct blasfeo_dvec *ineq_fun = config->constraints[0]->memory_get_fun_ptr(mem->constraints[0]); blasfeo_dveccp(2 * ni[0], ineq_fun, 0, mem->ineq_fun, 0); // d blasfeo_dveccp(2 * ni[0], mem->ineq_fun, 0, mem->qp_in->d, 0); return; } double ocp_nlp_evaluate_merit_fun(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int i, j; int N = dims->N; int *nx = dims->nx; int *ni = dims->ni; double merit_fun = 0.0; // compute fun value #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i=0; i<=N; i++) { // cost config->cost[i]->compute_fun(config->cost[i], dims->cost[i], in->cost[i], opts->cost[i], mem->cost[i], work->cost[i]); } #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i=0; i<N; i++) { // cost config->dynamics[i]->compute_fun(config->dynamics[i], dims->dynamics[i], in->dynamics[i], opts->dynamics[i], mem->dynamics[i], work->dynamics[i]); } #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i=0; i<=N; i++) { // constr config->constraints[i]->compute_fun(config->constraints[i], dims->constraints[i], in->constraints[i], opts->constraints[i], mem->constraints[i], work->constraints[i]); } double *tmp_fun; double tmp; struct blasfeo_dvec *tmp_fun_vec; double cost_fun = 0.0; for(i=0; i<=N; i++) { tmp_fun = config->cost[i]->memory_get_fun_ptr(mem->cost[i]); cost_fun += *tmp_fun; } double dyn_fun = 0.0; for(i=0; i<N; i++) { // printf("\ni %d\n", i); tmp_fun_vec = config->dynamics[i]->memory_get_fun_ptr(mem->dynamics[i]); // blasfeo_print_exp_tran_dvec(nx[i+1], tmp_fun_vec, 0); // blasfeo_print_exp_tran_dvec(nx[i+1], work->weights_nlp_out->pi+i, 0); for(j=0; j<nx[i+1]; j++) { // printf("\n%e %e\n", fabs(BLASFEO_DVECEL(work->weights_nlp_out->pi+i, j)), fabs(BLASFEO_DVECEL(tmp_fun_vec, j))); dyn_fun += fabs(BLASFEO_DVECEL(work->weights_nlp_out->pi+i, j)) * fabs(BLASFEO_DVECEL(tmp_fun_vec, j)); } } double constr_fun = 0.0; for(i=0; i<=N; i++) { // printf("\ni %d\n", i); tmp_fun_vec = config->constraints[i]->memory_get_fun_ptr(mem->constraints[i]); // blasfeo_print_exp_tran_dvec(2*ni[i], tmp_fun_vec, 0); // blasfeo_print_exp_tran_dvec(2*ni[i], work->weights_nlp_out->lam+i, 0); for(j=0; j<2*ni[i]; j++) { tmp = BLASFEO_DVECEL(tmp_fun_vec, j); tmp = tmp>0.0 ? tmp : 0.0; // printf("\n%e %e\n", fabs(BLASFEO_DVECEL(work->weights_nlp_out->pi+i, j)), fabs(BLASFEO_DVECEL(tmp_fun_vec, j))); constr_fun += fabs(BLASFEO_DVECEL(work->weights_nlp_out->lam+i, j)) * tmp; } } merit_fun = cost_fun + dyn_fun + constr_fun; printf("\n%e %e %e %e\n", merit_fun, cost_fun, dyn_fun, constr_fun); return merit_fun; } void ocp_nlp_update_variables_sqp(ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_opts *opts, ocp_nlp_memory *mem, ocp_nlp_workspace *work) { int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; int *nu = dims->nu; int *ni = dims->ni; int *nz = dims->nz; // ocp_nlp_config *config = (ocp_nlp_config *) config_; // (fixed) step length double alpha = opts->step_length; #if 0 // XXX test piece of code double tmp0, tmp1; // current point for (i = 0; i <= N; i++) blasfeo_dveccp(nv[i], out->ux+i, 0, work->tmp_nlp_out->ux+i, 0); for (i = 0; i < N; i++) blasfeo_dveccp(nx[i+1], out->pi+i, 0, work->tmp_nlp_out->pi+i, 0); for (i = 0; i <= N; i++) blasfeo_dveccp(2*ni[i], out->lam+i, 0, work->tmp_nlp_out->lam+i, 0); // linear update of algebraic variables using state and input sensitivity // if (i < N) // { // blasfeo_dgemv_t(nu[i]+nx[i], nz[i], alpha, mem->dzduxt+i, 0, 0, mem->qp_out->ux+i, 0, 1.0, mem->z_alg+i, 0, out->z+i, 0); // } // initialize weights if(mem->sqp_iter[0]==0) { for (i = 0; i < N; i++) blasfeo_dveccp(nx[i+1], out->pi+i, 0, work->weights_nlp_out->pi+i, 0); for (i = 0; i <= N; i++) blasfeo_dveccp(2*ni[i], out->lam+i, 0, work->weights_nlp_out->lam+i, 0); } // update weigths for (i = 0; i < N; i++) { for(j=0; j<nx[i+1]; j++) { tmp0 = fabs(BLASFEO_DVECEL(work->weights_nlp_out->pi+i, j)); tmp1 = 0.5 * (tmp0 + fabs(BLASFEO_DVECEL(mem->qp_out->pi+i, j))); BLASFEO_DVECEL(work->weights_nlp_out->pi+i, j) = tmp0>tmp1 ? tmp0 : tmp1; } } for (i = 0; i <= N; i++) { for(j=0; j<2*ni[i]; j++) { tmp0 = fabs(BLASFEO_DVECEL(work->weights_nlp_out->lam+i, j)); tmp1 = 0.5 * (tmp0 + fabs(BLASFEO_DVECEL(mem->qp_out->lam+i, j))); BLASFEO_DVECEL(work->weights_nlp_out->lam+i, j) = tmp0>tmp1 ? tmp0 : tmp1; } } printf("\n\nmerit fun value\n"); double merit_fun0 = ocp_nlp_evaluate_merit_fun(config, dims, in, out, opts, mem, work); double alpha_min = 0.2; for (j=0; j<10 & alpha>alpha_min; j++) { for (i = 0; i <= N; i++) blasfeo_daxpy(nv[i], alpha, mem->qp_out->ux+i, 0, out->ux+i, 0, work->tmp_nlp_out->ux+i, 0); printf("\n%d tmp merit fun value\n", j); double merit_fun1 = ocp_nlp_evaluate_merit_fun(config, dims, in, out, opts, mem, work); if(merit_fun1 < merit_fun0) { break; } else { alpha *= 0.7; } } printf("\nalpha %f\n", alpha); #endif #if defined(ACADOS_WITH_OPENMP) #pragma omp parallel for #endif for (i = 0; i <= N; i++) { // (full) step in primal variables blasfeo_daxpy(nv[i], alpha, mem->qp_out->ux + i, 0, out->ux + i, 0, out->ux + i, 0); // update dual variables if (i < N) { blasfeo_dvecsc(nx[i+1], 1.0-alpha, out->pi+i, 0); blasfeo_daxpy(nx[i+1], alpha, mem->qp_out->pi+i, 0, out->pi+i, 0, out->pi+i, 0); } blasfeo_dvecsc(2*ni[i], 1.0-alpha, out->lam+i, 0); blasfeo_daxpy(2*ni[i], alpha, mem->qp_out->lam+i, 0, out->lam+i, 0, out->lam+i, 0); // update slack values blasfeo_dvecsc(2*ni[i], 1.0-alpha, out->t+i, 0); blasfeo_daxpy(2*ni[i], alpha, mem->qp_out->t+i, 0, out->t+i, 0, out->t+i, 0); // linear update of algebraic variables using state and input sensitivity if (i < N) { blasfeo_dgemv_t(nu[i]+nx[i], nz[i], alpha, mem->dzduxt+i, 0, 0, mem->qp_out->ux+i, 0, 1.0, mem->z_alg+i, 0, out->z+i, 0); } } return; } /************************************************ * residuals ************************************************/ int ocp_nlp_res_calculate_size(ocp_nlp_dims *dims) { // extract dims int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; int size = sizeof(ocp_nlp_res); size += 3 * (N + 1) * sizeof(struct blasfeo_dvec); // res_g res_d res_m size += 1 * N * sizeof(struct blasfeo_dvec); // res_b for (int ii = 0; ii < N; ii++) { size += 1 * blasfeo_memsize_dvec(nv[ii]); // res_g size += 1 * blasfeo_memsize_dvec(nx[ii + 1]); // res_b size += 2 * blasfeo_memsize_dvec(2 * ni[ii]); // res_d res_m } size += 1 * blasfeo_memsize_dvec(nv[N]); // res_g size += 2 * blasfeo_memsize_dvec(2 * ni[N]); // res_d res_m size += 8; // initial align size += 8; // blasfeo_struct align size += 64; // blasfeo_mem align // make_int_multiple_of(64, &size); return size; } ocp_nlp_res *ocp_nlp_res_assign(ocp_nlp_dims *dims, void *raw_memory) { char *c_ptr = (char *) raw_memory; // extract sizes int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; // initial align align_char_to(8, &c_ptr); // struct ocp_nlp_res *res = (ocp_nlp_res *) c_ptr; c_ptr += sizeof(ocp_nlp_res); // blasfeo_struct align align_char_to(8, &c_ptr); // res_g assign_and_advance_blasfeo_dvec_structs(N + 1, &res->res_g, &c_ptr); // res_b assign_and_advance_blasfeo_dvec_structs(N, &res->res_b, &c_ptr); // res_d assign_and_advance_blasfeo_dvec_structs(N + 1, &res->res_d, &c_ptr); // res_m assign_and_advance_blasfeo_dvec_structs(N + 1, &res->res_m, &c_ptr); // blasfeo_mem align align_char_to(64, &c_ptr); // res_g for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(nv[ii], res->res_g + ii, &c_ptr); } // res_b for (int ii = 0; ii < N; ii++) { assign_and_advance_blasfeo_dvec_mem(nx[ii + 1], res->res_b + ii, &c_ptr); } // res_d for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(2 * ni[ii], res->res_d + ii, &c_ptr); } // res_m for (int ii = 0; ii <= N; ii++) { assign_and_advance_blasfeo_dvec_mem(2 * ni[ii], res->res_m + ii, &c_ptr); } res->memsize = ocp_nlp_res_calculate_size(dims); return res; } void ocp_nlp_res_compute(ocp_nlp_dims *dims, ocp_nlp_in *in, ocp_nlp_out *out, ocp_nlp_res *res, ocp_nlp_memory *mem) { // extract dims int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; int *nu = dims->nu; int *ni = dims->ni; double tmp_res; // res_g res->inf_norm_res_g = 0.0; for (int ii = 0; ii <= N; ii++) { blasfeo_daxpy(nv[ii], -1.0, mem->ineq_adj + ii, 0, mem->cost_grad + ii, 0, res->res_g + ii, 0); blasfeo_daxpy(nu[ii] + nx[ii], -1.0, mem->dyn_adj + ii, 0, res->res_g + ii, 0, res->res_g + ii, 0); blasfeo_dvecnrm_inf(nv[ii], res->res_g + ii, 0, &tmp_res); res->inf_norm_res_g = tmp_res > res->inf_norm_res_g ? tmp_res : res->inf_norm_res_g; } // res_b res->inf_norm_res_b = 0.0; for (int ii = 0; ii < N; ii++) { blasfeo_dveccp(nx[ii + 1], mem->dyn_fun + ii, 0, res->res_b + ii, 0); blasfeo_dvecnrm_inf(nx[ii + 1], res->res_b + ii, 0, &tmp_res); res->inf_norm_res_b = tmp_res > res->inf_norm_res_b ? tmp_res : res->inf_norm_res_b; } // res_d res->inf_norm_res_d = 0.0; for (int ii = 0; ii <= N; ii++) { blasfeo_daxpy(2 * ni[ii], 1.0, out->t + ii, 0, mem->ineq_fun + ii, 0, res->res_d + ii, 0); blasfeo_dvecnrm_inf(2 * ni[ii], res->res_d + ii, 0, &tmp_res); res->inf_norm_res_d = tmp_res > res->inf_norm_res_d ? tmp_res : res->inf_norm_res_d; } // res_m res->inf_norm_res_m = 0.0; for (int ii = 0; ii <= N; ii++) { blasfeo_dvecmul(2 * ni[ii], out->lam + ii, 0, out->t + ii, 0, res->res_m + ii, 0); blasfeo_dvecnrm_inf(2 * ni[ii], res->res_m + ii, 0, &tmp_res); res->inf_norm_res_m = tmp_res > res->inf_norm_res_m ? tmp_res : res->inf_norm_res_m; } return; }
syrk.c
/** * syrk.c: This file was adapted from PolyBench/GPU 1.0 test suite * to run on GPU with OpenMP 4.0 pragmas and OpenCL driver. * * http://www.cse.ohio-state.edu/~pouchet/software/polybench/GPU * * Contacts: Marcio M Pereira <mpereira@ic.unicamp.br> * Rafael Cardoso F Sousa <rafael.cardoso@students.ic.unicamp.br> * Luís Felipe Mattos <ra107822@students.ic.unicamp.br> */ #include "BenchmarksUtil.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> // define the error threshold for the results "not matching" #define ERROR_THRESHOLD 0.05 #ifdef RUN_TEST #define SIZE 1100 #elif RUN_BENCHMARK #define SIZE 9600 #else #define SIZE 1000 #endif /* Problem size */ #define N SIZE #define M SIZE /* Declared constant values for alpha and beta */ /* (same as values in PolyBench 2.0) */ #define alpha 12435 #define beta 4546 /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void init_arrays(DATA_TYPE *A, DATA_TYPE *C, DATA_TYPE *D) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { A[i * M + j] = ((DATA_TYPE)i * j) / N; } for (j = 0; j < M; j++) { C[i * M + j] = ((DATA_TYPE)i * j + 2) / N; D[i * M + j] = ((DATA_TYPE)i * j + 2) / N; } } } int compareResults(DATA_TYPE *C, DATA_TYPE *D) { int i, j, fail; fail = 0; // Compare C with D for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { if (percentDiff(C[i * M + j], D[i * M + j]) > ERROR_THRESHOLD) { fail++; } } } // print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", ERROR_THRESHOLD, fail); return fail; } void syrk(DATA_TYPE *A, DATA_TYPE *C) { int i, j, k; for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { C[i * M + j] *= beta; } } for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { for (k = 0; k < M; k++) { C[i * N + j] += alpha * A[i * M + k] * A[j * M + k]; } } } } void syrkGPU(DATA_TYPE *A, DATA_TYPE *Dinit, DATA_TYPE *D1, DATA_TYPE *D2) { double t_start, t_end; t_start = rtclock(); #pragma omp target teams map(to : A[ : N *M], Dinit[ : N *M]) map(tofrom : D1[ : N *M], D2[ : N *M]) device(DEVICE_ID) { #pragma omp distribute parallel for collapse(2) for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { D1[i * M + j] = Dinit[i * M + j] * beta; } } #pragma omp distribute parallel for collapse(2) for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { D2[i * N + j] = D1[i * N + j]; for (int k = 0; k < M; k++) { D2[i * N + j] += alpha * A[i * M + k] * A[j * M + k]; } } } } t_end = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end - t_start); } int main() { double t_start, t_end; int fail = 0; DATA_TYPE *A; DATA_TYPE *C; DATA_TYPE *Dinit; DATA_TYPE *D1; DATA_TYPE *D2; A = (DATA_TYPE *)malloc(N * M * sizeof(DATA_TYPE)); C = (DATA_TYPE *)malloc(N * M * sizeof(DATA_TYPE)); Dinit = (DATA_TYPE *)malloc(N * M * sizeof(DATA_TYPE)); D1 = (DATA_TYPE *)calloc(N * M, sizeof(DATA_TYPE)); D2 = (DATA_TYPE *)calloc(N * M, sizeof(DATA_TYPE)); fprintf(stdout, "<< Symmetric rank-k operations >>\n"); init_arrays(A, C, Dinit); syrkGPU(A, Dinit, D1, D2); #ifdef RUN_TEST t_start = rtclock(); syrk(A, C); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); fail = compareResults(C, D2); #endif free(A); free(C); free(Dinit); return fail; }
iter_helper.h
#pragma once #include "util/graph/graph.h" #include "util/timer.h" #include "util/log/log.h" #include "util/search/search_util.h" #include "util/stat.h" #include "pkt_support_update_utils.h" #include "parallel_all_edge_cnc.h" #include "iter_stat_helper.h" #include "extern_variables.h" #define V_BUFF_SIZE (4096) #define MAX_LEVEL (20000) class IterHelper { public: vector<uint32_t> histogram_; int omp_num_threads_; graph_t *g; eid_t *compact_num_edges_; vid_t *compact_adj_; eid_t *compact_eid_; size_t num_edges_; // num_edges_ is changed during the shrinking. int n_; public: #ifdef BMP_PROCESSED BoolArray<word_type> processed_; #else bool *processed_; #endif // Origin Edge Offset. eid_t *edge_off_org_; eid_t *level_start_pos_; eid_t *edge_offsets_level_; int level_size_; // Bucket Related. BoolArray<word_type> bucket_removed_indicator_; int bucket_level_end_ = 0; bool *in_bucket_window_; eid_t *bucket_buf_; size_t window_bucket_buf_size_ = 0; size_t total_size_ = 0; // Queue Related. (curr_/next_). long curr_tail_; long next_tail_; eid_t *curr_; #ifdef BMP_QUEUE BoolArray<word_type> in_curr_; #else bool *in_curr_; #endif eid_t *next_; #ifdef BMP_QUEUE BoolArray<word_type> in_next_; #else bool *in_next_; #endif // For Graph Shrink. bool *is_vertex_updated_; eid_t *off_end_; vid_t *global_v_buffer_; public: // View (edge list and edge support) int **edge_sup_ptr_; Edge **edge_lst_ptr_; // Shrink Related Extra Memory. eid_t *edge_off_org_shrink_; int *edge_support_shrink_; Edge *edge_lst_shrink_; eid_t *bucket_buf_shrink_; uint32_t *edge_lst_relative_off_; // // prefix-sum inclusive uint32_t *bucket_relative_off_; // prefix-sum inclusive public: // BSR. vector<vector<int>> partition_id_lst; vector<vector<bmp_word_type>> bitmap_in_partition_lst; void FreeBSR(); public: IterHelper(graph_t *g, int **edge_sup_ptr, Edge **edge_lst_ptr); void MemSetIterVariables(int max_omp_threads); void ComputeTriSupport(IterStatTLS &iter_stat_tls); void SCANGraph(int level); void ShrinkCSREID(volatile eid_t *global_buffer_size, vid_t *local_buffer); void CompactCSREID(); void ShrinkEdgeList(); void MarkProcessed(); void SwapCurNextQueue(); void ProcessSupportZeros(); ~IterHelper(); }; void TriCntDetailSubLevel(graph_t *g, eid_t *curr, #ifndef BMP_QUEUE bool *InCurr, #else BoolArray<word_type> &InCurr, #endif long currTail, int *EdgeSupport, int level, eid_t *next, #ifndef BMP_QUEUE bool *InNext, #else BoolArray<word_type> &InNext, #endif long *nextTail, #ifdef BMP_PROCESSED BoolArray<word_type> &processed_, #else bool *processed_, #endif Edge *edgeIdtoEdge, eid_t *off_end, bool *is_vertex_updated, IterHelper &iter_helper, volatile eid_t &global_v_buff_size ); /* * F requires a callable or a functor with signature `void (int)` */ template<typename F> void AbstractPKT(graph_t *g, int *&EdgeSupport, Edge *&edgeIdToEdge, IterHelper &iter_helper, F f) { Timer malloc_timer; long numEdges = g->m / 2; auto max_omp_threads = omp_get_max_threads(); log_info("Max Threads: %d", max_omp_threads); #pragma omp parallel num_threads(max_omp_threads) { iter_helper.MemSetIterVariables(max_omp_threads); } log_info("Malloc & MemSet Time: %.6lfs", malloc_timer.elapsed()); vector<double> shrink_time_lst; Timer iter_timer; Timer comp_timer; size_t iter_num = 0; size_t local_iter_num = 0; volatile eid_t global_v_buff_size = 0; size_t num_of_shrinks = 0; vector<int> tc_level; vector<double> tc_level_time; double init_tc_time = 0; double penalty_tc_time = 0; #ifdef PAPER_FIGURE { stringstream ss; ss << pretty_print_array(g->num_edges, g->n + 1); log_info("CSR-off: %s", ss.str().c_str()); reset(ss); ss << pretty_print_array(g->adj, g->m); log_info("CSR-adj: %s", ss.str().c_str()); reset(ss); ss << pretty_print_array(g->eid, g->m); log_info("Map-eid: %s", ss.str().c_str()); vector<int> src; vector<int> dst; for (int i = 0; i < g->m / 2; i++) { src.emplace_back(edgeIdToEdge[i].u); dst.emplace_back(edgeIdToEdge[i].v); } reset(ss); ss << src; log_info("Edge-src: %s", ss.str().c_str()); reset(ss); ss << dst; log_info("Edge-dst: %s", ss.str().c_str()); } #endif #pragma omp parallel { size_t acc_process_num = 0; double acc_time = 0; // TC. IterStatTLS iter_stat_tls; iter_helper.ComputeTriSupport(iter_stat_tls); #pragma omp single { #ifdef PAPER_FIGURE if (g->m < 40) { stringstream ss; ss << pretty_print_array(EdgeSupport, g->m / 2); vector<pair<pair<int, int>, int>> edge_list; for (auto i = 0; i < g->m / 2; i++) { edge_list.emplace_back(make_pair(edgeIdToEdge[i].u, edgeIdToEdge[i].v), EdgeSupport[i]); } ss << edge_list << endl; log_info("Edge Support Array: %s", ss.str().c_str()); } #endif init_tc_time = iter_stat_tls.triTime; iter_timer.reset(); log_info("TC time: %.9lfs", init_tc_time); } // Compute Truss. auto *local_buffer = (vid_t *) malloc(sizeof(vid_t) * V_BUFF_SIZE); int level = 0; long acc_deleted = 0; long todo = numEdges; while (todo > 0) { // 1st: Synchronization. #pragma omp single { iter_stat_tls.PrintIterStat(iter_timer, todo, numEdges, level, iter_num, local_iter_num); } iter_stat_tls.ResetLocalTime(); iter_stat_tls.RecordSyncTime(); // 2nd: Scanning the graph to fetch the level. iter_helper.SCANGraph(level); iter_stat_tls.RecordSCANTime(); #ifdef SHRINK_EDGE_LIST #pragma omp single { iter_helper.level_start_pos_[level + 1] = iter_helper.level_start_pos_[level]; } #endif // 3rd: Processing the graph (shrinking and updating supports). while (iter_helper.curr_tail_ > 0) { // Map the curr_ to result array. #ifdef PAPER_FIGURE #pragma omp single { stringstream ss; vector<pair<int, int>> edge_lst; for (auto i = 0; i < iter_helper.curr_tail_; i++) { auto edge = (*iter_helper.edge_lst_ptr_)[iter_helper.curr_[i]]; edge_lst.emplace_back(edge.u, edge.v); } sort(edge_lst.begin(), edge_lst.end()); ss << edge_lst; log_info("Curr Queue: %s", ss.str().c_str()); } #endif #ifdef SHRINK_EDGE_LIST #pragma omp for for (auto i = 0; i < max_omp_threads; i++) { auto avg = iter_helper.curr_tail_ / max_omp_threads; auto iter_beg = avg * i; auto iter_end = (i == max_omp_threads - 1) ? iter_helper.curr_tail_ : avg * (i + 1); auto pos_off = iter_helper.level_start_pos_[level + 1]; for (auto iter = iter_beg; iter < iter_end; iter++) { // map operation. iter_helper.edge_offsets_level_[pos_off + iter] = iter_helper.edge_off_org_[iter_helper.curr_[iter]]; } } #pragma omp single { iter_helper.level_start_pos_[level + 1] += iter_helper.curr_tail_; } #endif todo = todo - iter_helper.curr_tail_; iter_stat_tls.RecordQueueSize(iter_helper.curr_tail_); #ifndef WITHOUT_FIRST_LAST_LEVEL_OPT // All of them being the last level. if (todo == 0) { // No need to process but need to copy the results back. level = level + 1; break; } #endif #ifndef NO_SHRINK_GRAPH // 3.1: Optional shrinking graph. (Move to here to maximally shrink the graph). if (acc_deleted > numEdges / graph_compaction_threshold) { #pragma omp barrier Timer shrink_timer; iter_helper.ShrinkCSREID(&global_v_buff_size, local_buffer); #ifdef COMPACT_CSR iter_helper.CompactCSREID(); #endif #ifdef SHRINK_EDGE_LIST iter_helper.ShrinkEdgeList(); #endif acc_deleted = 0; #pragma omp single { iter_stat_tls.RecordShrinkNum(num_of_shrinks); shrink_time_lst.emplace_back(shrink_timer.elapsed()); } } #endif iter_stat_tls.RecordShrinkTime(); // 3.2: Real Processing (updating supports). #ifndef WITHOUT_FIRST_LAST_LEVEL_OPT if (level == 0) { iter_helper.ProcessSupportZeros(); } else { #endif #ifdef NO_TC_OPT { auto to_delete = iter_helper.curr_tail_; f(level); acc_deleted += to_delete; } #else size_t task_size = iter_helper.curr_tail_ * (size_t) (level + 1); size_t left_edge_size = todo; double estimated_tc_time = left_edge_size / (g->m / 2.0) * init_tc_time + penalty_tc_time; double estimated_peel_time = task_size / estimated_process_throughput; if (estimated_tc_time > estimated_peel_time) { auto to_delete = iter_helper.curr_tail_; f(level); acc_process_num += task_size; acc_deleted += to_delete; } else { #pragma omp single { log_info("Estimated TC Time: %.9lfs, Peel Time: %.9lfs", estimated_tc_time, estimated_peel_time); tc_level.emplace_back(level); log_info("!!!TriCnt!!!, Task-Size: %'zu, TC-Cnt/50: %'zu", task_size, tc_cnt / 50); } Timer tc_timer; TriCntDetailSubLevel(g, iter_helper.curr_, iter_helper.in_curr_, iter_helper.curr_tail_, *iter_helper.edge_sup_ptr_, level, iter_helper.next_, iter_helper.in_next_, &iter_helper.next_tail_, iter_helper.processed_, *iter_helper.edge_lst_ptr_, iter_helper.off_end_, iter_helper.is_vertex_updated_, iter_helper, global_v_buff_size); acc_deleted = 0; #pragma omp single { auto cost = tc_timer.elapsed(); if (estimated_tc_time * 1.2 < cost) { penalty_tc_time += cost - estimated_tc_time; log_info("Penalty TC-Time: %.9lfs", penalty_tc_time); } tc_level_time.emplace_back(cost); } } #endif #ifndef WITHOUT_FIRST_LAST_LEVEL_OPT } #endif // 3.3: Swap Queues. #pragma omp single { iter_helper.SwapCurNextQueue(); iter_stat_tls.RecordIterNum(iter_num, local_iter_num); #ifdef PAPER_FIGURE if (g->m < 40) { stringstream ss; ss << pretty_print_array(EdgeSupport, g->m / 2); vector<pair<pair<int, int>, int>> edge_list; for (auto i = 0; i < g->m / 2; i++) { edge_list.emplace_back(make_pair(edgeIdToEdge[i].u, edgeIdToEdge[i].v), EdgeSupport[i]); } ss << edge_list << endl; log_info("Edge Support Array: %s", ss.str().c_str()); } #endif } #pragma omp barrier iter_stat_tls.RecordProcessTime(); } level = level + 1; #pragma omp barrier // End of Iterative Peeling for this Level. } // The end. #pragma omp single { iter_helper.level_size_ = level; #ifdef SHRINK_EDGE_LIST assert(iter_helper.level_start_pos_[iter_helper.level_size_ - 1] == numEdges); #endif log_info("Total Levels: %d", iter_helper.level_size_); log_trace("Last Level Finished: %d, Elapsed Time: %.9lfs, Left/Total: %'lld/%'lld, " "Local/Global-Iter#: %zu/%zu", level - 1, iter_timer.elapsed_and_reset(), todo, numEdges, local_iter_num, iter_num); iter_stat_tls.PrintFinalStat(level, num_of_shrinks); stringstream ss; ss << tc_level << ", Time: " << tc_level_time; log_trace("TC-levels: %s", ss.str().c_str()); stringstream ss2; ss2 << shrink_time_lst; log_trace("Shrink Time List: %s", ss2.str().c_str()); } free(local_buffer); } //End of parallel region log_info("Total computation cost: %.9lfs", comp_timer.elapsed_and_reset()); // Copy Back to Edge Support. #ifdef SHRINK_EDGE_LIST for (auto i = 0; i < iter_helper.level_size_ - 1; i++) { #pragma omp for nowait for (auto j = iter_helper.level_start_pos_[i]; j < iter_helper.level_start_pos_[i + 1]; j++) { EdgeSupport[iter_helper.edge_offsets_level_[j]] = i; } } log_info("Result Copy Time: %.9lfs ", comp_timer.elapsed()); #endif }
GB_binop__div_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__div_int16 // A.*B function (eWiseMult): GB_AemultB__div_int16 // A*D function (colscale): GB_AxD__div_int16 // D*A function (rowscale): GB_DxB__div_int16 // C+=B function (dense accum): GB_Cdense_accumB__div_int16 // C+=b function (dense accum): GB_Cdense_accumb__div_int16 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__div_int16 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__div_int16 // C=scalar+B GB_bind1st__div_int16 // C=scalar+B' GB_bind1st_tran__div_int16 // C=A+scalar GB_bind2nd__div_int16 // C=A'+scalar GB_bind2nd_tran__div_int16 // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = GB_IDIV_SIGNED (aij, bij, 16) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IDIV_SIGNED (x, y, 16) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_DIV || GxB_NO_INT16 || GxB_NO_DIV_INT16) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__div_int16 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__div_int16 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__div_int16 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__div_int16 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__div_int16 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *GB_RESTRICT Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__div_int16 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *GB_RESTRICT Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__div_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__div_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__div_int16 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = Bx [p] ; Cx [p] = GB_IDIV_SIGNED (x, bij, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__div_int16 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = Ax [p] ; Cx [p] = GB_IDIV_SIGNED (aij, y, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_SIGNED (x, aij, 16) ; \ } GrB_Info GB_bind1st_tran__div_int16 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_SIGNED (aij, y, 16) ; \ } GrB_Info GB_bind2nd_tran__div_int16 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
elemwise_binary_scalar_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file elemwise_binary_scalar_op.h * \brief Function definition of elementwise binary scalar operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_ #include <mxnet/operator_util.h> #include <vector> #include <utility> #include "../mshadow_op.h" #include "../elemwise_op_common.h" #include "elemwise_unary_op.h" namespace mxnet { namespace op { class BinaryScalarOp : public UnaryOp { /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType> static void ComputeExDenseResultRsp(mshadow::Stream<cpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { const double alpha = nnvm::get<double>(attrs.parsed); CHECK_EQ(output.shape(), input.shape()); const int64_t row_count = output.shape()[0]; const int64_t items_per_row = output.shape().Size() / row_count; const DType result_for_zero = OP::Map(DType(0), DType(alpha)); mshadow::Tensor<cpu, 1, DType> input_data = input.data().FlatTo1D<cpu, DType>(stream); mshadow::Tensor<cpu, 1, DType> output_data = output.data().FlatTo1D<cpu, DType>(stream); const int64_t sparse_row_count = input.aux_shape(rowsparse::kIdx).Size(); if (sparse_row_count != row_count) { mshadow::Tensor<cpu, 1, IType> row_indexes = input.aux_data( rowsparse::kIdx).FlatTo1D<cpu, IType>(stream); int64_t input_iter = 0; int64_t output_row = 0; IType next_input_row = 0; while (output_row < row_count) { next_input_row = input_iter < sparse_row_count ? int64_t(row_indexes[input_iter]) : row_count; // Split up into blocks of contiguous data and do those together // Do contiguous dense blocks const int64_t dense_block_count = next_input_row - output_row; if (dense_block_count > 0) { MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<OpBase::SetToScalar<Req>, cpu>::Launch( stream, items_per_row * dense_block_count, output_data.dptr_ + items_per_row * output_row, result_for_zero); }); output_row += dense_block_count; continue; } // Do contiguous sparse blocks int64_t next_non_contiguous_sparse = input_iter; while (next_non_contiguous_sparse < sparse_row_count - 1) { if (row_indexes[next_non_contiguous_sparse + 1] != row_indexes[next_non_contiguous_sparse] + 1) { break; } ++next_non_contiguous_sparse; } const int64_t sparse_block_count = next_non_contiguous_sparse - input_iter + 1; if (sparse_block_count > 0) { MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch( stream, items_per_row * sparse_block_count, &output_data.dptr_[items_per_row * output_row], &input_data.dptr_[items_per_row * input_iter], DType(alpha)); }); output_row += sparse_block_count; input_iter += sparse_block_count; continue; } } } else { // All rows exist (eventually we don't have to do complex // things to call GPU kernels because we don't need to access row indices) MXNET_ASSIGN_REQ_SWITCH(req, Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, cpu>::Launch( stream, items_per_row * row_count, output_data.dptr_, input_data.dptr_, DType(alpha)); }); } } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType> static void ComputeExDenseResultRsp(mshadow::Stream<gpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { LOG(FATAL) << "NOT IMPLEMENTED"; } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType, typename CType> static void ComputeExDenseResultCsr(mshadow::Stream<cpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { CHECK_EQ(output.shape(), input.shape()); const double alpha = nnvm::get<double>(attrs.parsed); const DType dense_fill_val = OP::Map(DType(0), DType(alpha)); const TBlob column_indexes = input.aux_data(csr::kIdx); const size_t item_count = column_indexes.Size(); // Pre-fill dense with 0-input/output value FillDense<cpu, DType>(stream, output.shape().Size(), dense_fill_val, req, output.data().dptr<DType>()); mshadow::Tensor<cpu, 2, DType> out = AsRowise2D<DType>(stream, output.data()); if (item_count) { const DType *in = input.data().dptr<DType>(); const IType *column_indexes_ptr = column_indexes.dptr<IType>(); const auto row_count = static_cast<size_t>(input.shape()[0]); const TBlob row_starts = input.aux_data(csr::kIndPtr); const CType *row_starts_ptr = row_starts.dptr<CType>(); #pragma omp parallel for for (int i = 0; i < static_cast<int>(row_count); ++i) { const bool last_row = i == static_cast<int>(row_count) - 1; // Split up into blocks of contiguous data and do those together const size_t row_item_start_iter = row_starts_ptr[i]; const size_t input_items_this_row = !last_row ? static_cast<size_t>(row_starts_ptr[i + 1]) - row_item_start_iter : item_count - row_item_start_iter; if (input_items_this_row) { const IType *this_row_column_indexes = column_indexes_ptr + row_item_start_iter; const DType *row_data_start = in + row_item_start_iter; DType *output_this_row = out[i].dptr_; // More overhead to use OMP for small loops, so don't if (input_items_this_row > 1000) { #pragma omp parallel for for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) { const IType col = this_row_column_indexes[j]; const DType val = row_data_start[j]; output_this_row[col] = OP::Map(val, DType(alpha)); } } else { for (CType j = 0; j < static_cast<CType>(input_items_this_row); ++j) { const IType col = this_row_column_indexes[j]; const DType val = row_data_start[j]; output_this_row[col] = OP::Map(val, DType(alpha)); } } } } } } /*! \brief Tensor operation against a scalar with a dense result */ template<typename OP, typename DType, typename IType, typename CType> static void ComputeExDenseResultCsr(mshadow::Stream<gpu> *stream, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray &output) { LOG(FATAL) << "NOT IMPLEMENTED"; } template<typename xpu, typename OP, typename DType, typename IType> static void ComputeExDenseResult(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &input, const OpReqType req, const NDArray output) { mshadow::Stream<xpu> *stream = ctx.get_stream<xpu>(); CHECK_EQ(output.storage_type(), kDefaultStorage); switch (input.storage_type()) { case kRowSparseStorage: { ComputeExDenseResultRsp<OP, DType, IType>(stream, attrs, ctx, input, req, output); break; } case kCSRStorage: { MSHADOW_IDX_TYPE_SWITCH(input.aux_data(csr::kIndPtr).type_flag_, CType, { ComputeExDenseResultCsr<OP, DType, IType, CType>(stream, attrs, ctx, input, req, output); }); break; } default: CHECK(false) << "Unsupported sparse storage type"; break; } } public: template<typename xpu, typename OP> static void Compute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { DCHECK_EQ(inputs.size(), 1); DCHECK_EQ(outputs.size(), 1); using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.get_stream<xpu>(); const double alpha = nnvm::get<double>(attrs.parsed); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { mxnet_op::Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, inputs[0].Size(), outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), DType(alpha)); }); }); } template<typename xpu, typename OP> static void ComputeEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { DCHECK_EQ(inputs.size(), 1); DCHECK_EQ(outputs.size(), 1); const auto in_stype = inputs[0].storage_type(); const auto out_stype = outputs[0].storage_type(); if (req[0] == kNullOp) { return; } if ((in_stype == kRowSparseStorage && out_stype == kRowSparseStorage) || (in_stype == kCSRStorage && out_stype == kCSRStorage)) { // csr -> csr, or rsp -> rsp UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Compute<xpu, OP>); } else if (out_stype == kDefaultStorage && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { MSHADOW_TYPE_SWITCH(outputs[0].data().type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(inputs[0].aux_type(rowsparse::kIdx), IType, { ComputeExDenseResult<xpu, OP, DType, IType>(attrs, ctx, inputs[0], req[0], outputs[0]); }); }); } else { LOG(FATAL) << "Not implemented: " << operator_string(attrs, ctx, inputs, req, outputs); } } template<typename xpu, typename OP> static void Backward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.get_stream<xpu>(); const double alpha = nnvm::get<double>(attrs.parsed); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Tensor<xpu, 1, DType> igrad = outputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> ograd = inputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> lhs = inputs[1].FlatTo1D<xpu, DType>(s); ASSIGN_DISPATCH(igrad, req[0], ograd * F<OP>(lhs, scalar<DType>(DType(alpha)))); }); } }; #define MXNET_OPERATOR_REGISTER_BINARY_SCALAR(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(1) \ .set_num_outputs(1) \ .set_attr_parser([](NodeAttrs* attrs) { \ attrs->parsed = std::stod(attrs->dict["scalar"]); \ }) \ .set_attr<nnvm::FInferShape>("FInferShape", ElemwiseShape<1, 1>) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<1, 1>) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}}; \ }) \ .add_argument("data", "NDArray-or-Symbol", "source input") \ .add_argument("scalar", "float", "scalar input") } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_SCALAR_OP_H_
6809.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4000. */ #include "atax.h" /* Array initialization. */ static void init_array (int nx, int ny, DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny), DATA_TYPE POLYBENCH_1D(x,NY,ny)) { int i, j; for (i = 0; i < ny; i++) x[i] = i * M_PI; for (i = 0; i < nx; i++) for (j = 0; j < ny; j++) A[i][j] = ((DATA_TYPE) i*(j+1)) / nx; } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int nx, DATA_TYPE POLYBENCH_1D(y,NX,nx)) { int i; for (i = 0; i < nx; i++) { fprintf (stderr, DATA_PRINTF_MODIFIER, y[i]); if (i % 20 == 0) fprintf (stderr, "\n"); } fprintf (stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_atax(int nx, int ny, DATA_TYPE POLYBENCH_2D(A,NX,NY,nx,ny), DATA_TYPE POLYBENCH_1D(x,NY,ny), DATA_TYPE POLYBENCH_1D(y,NY,ny), DATA_TYPE POLYBENCH_1D(tmp,NX,nx)) { int i, j; #pragma scop #pragma omp parallel num_threads(1) { #pragma omp for schedule(static, 16) for (i = 0; i < _PB_NY; i++) y[i] = 0; #pragma omp for private (j) schedule(static, 16) for (i = 0; i < _PB_NX; i++) { tmp[i] = 0; for (j = 0; j < _PB_NY; j++) tmp[i] = tmp[i] + A[i][j] * x[j]; for (j = 0; j < _PB_NY; j++) y[j] = y[j] + A[i][j] * tmp[i]; } } #pragma endscop } int main(int argc, char** argv) { /* Retrieve problem size. */ int nx = NX; int ny = NY; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NX, NY, nx, ny); POLYBENCH_1D_ARRAY_DECL(x, DATA_TYPE, NY, ny); POLYBENCH_1D_ARRAY_DECL(y, DATA_TYPE, NY, ny); POLYBENCH_1D_ARRAY_DECL(tmp, DATA_TYPE, NX, nx); /* Initialize array(s). */ init_array (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_atax (nx, ny, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(x), POLYBENCH_ARRAY(y), POLYBENCH_ARRAY(tmp)); /* Stop and print timer. */ polybench_stop_instruments; polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(nx, POLYBENCH_ARRAY(y))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(x); POLYBENCH_FREE_ARRAY(y); POLYBENCH_FREE_ARRAY(tmp); return 0; }
matProduct1.c
/****************************************************************************** * FILE: omp_mm.c * DESCRIPTION: * OpenMp Example - Matrix Multiply - C Version * Demonstrates a matrix multiply using OpenMP. Threads share row iterations * according to a predefined chunk size. * AUTHOR: Blaise Barney * LAST REVISED: 06/28/05 ******************************************************************************/ /** * This program performs the multiplication of two matrix's. * Online source: * https://computing.llnl.gov/tutorials/openMP/samples/C/omp_mm.c **/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #ifdef _CIVL #define NRA 4 /* number of rows in matrix A */ #define NCA 4 /* number of columns in matrix A */ #define NCB 4 /* number of columns in matrix B */ #else #define NRA 8 /* number of rows in matrix A */ #define NCA 8 /* number of columns in matrix A */ #define NCB 8 /* number of columns in matrix B */ #endif int main (int argc, char *argv[]) { int tid, nthreads, i, j, k, chunk; double a[NRA][NCA], /* matrix A to be multiplied */ b[NCA][NCB], /* matrix B to be multiplied */ c[NRA][NCB]; /* result matrix C */ chunk = 10; /* set loop iteration chunk size */ /*** Spawn a parallel region explicitly scoping all variables ***/ #pragma omp parallel shared(a,b,c,nthreads,chunk) private(tid,i,j,k) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); printf("Starting matrix multiple example with %d threads\n",nthreads); printf("Initializing matrices...\n"); } /*** Initialize matrices ***/ #pragma omp for schedule (static, chunk) for (i=0; i<NRA; i++) for (j=0; j<NCA; j++) a[i][j]= i+j; #pragma omp for schedule (static, chunk) for (i=0; i<NCA; i++) for (j=0; j<NCB; j++) b[i][j]= i*j; #pragma omp for schedule (static, chunk) for (i=0; i<NRA; i++) for (j=0; j<NCB; j++) c[i][j]= 0; /*** Do matrix multiply sharing iterations on outer loop ***/ /*** Display who does which iterations for demonstration purposes ***/ printf("Thread %d starting matrix multiply...\n",tid); #pragma omp for schedule (static, chunk) for (i=0; i<NRA; i++) { printf("Thread=%d did row=%d\n",tid,i); for(j=0; j<NCB; j++) for (k=0; k<NCA; k++) c[i][j] += a[i][k] * b[k][j]; } } /*** End of parallel region ***/ /*** Print results ***/ printf("******************************************************\n"); printf("Result Matrix:\n"); for (i=0; i<NRA; i++) { for (j=0; j<NCB; j++) printf("%6.2f ", c[i][j]); printf("\n"); } printf("******************************************************\n"); printf ("Done.\n"); }
ConvolutionFFTImageFilter.h
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef BK_CONVOLUTIONFFTIMAGEFILTER_H #define BK_CONVOLUTIONFFTIMAGEFILTER_H #include <algorithm> #ifdef BK_EMIT_PROGRESS #include <bk/Progress> #include <bk/Localization> #endif #include <bkDataset/image/filter/FFTImageFilter.h> #include <bkDataset/image/filter/IFFTImageFilter.h> #include <bkDataset/image/filter/FFTShiftImageFilter.h> #include <bkDataset/lib/bkDataset_export.h> namespace bk { class BKDATASET_EXPORT ConvolutionFFTImageFilter { //==================================================================================================== //===== DEFINITIONS //==================================================================================================== using self_type = ConvolutionFFTImageFilter; //==================================================================================================== //===== MEMBERS //==================================================================================================== unsigned int _num_iterations; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== public: /// @{ -------------------------------------------------- CTOR constexpr ConvolutionFFTImageFilter() : ConvolutionFFTImageFilter(1) { /* do nothing */ } constexpr ConvolutionFFTImageFilter(const self_type&) = default; constexpr ConvolutionFFTImageFilter(self_type&&) noexcept = default; constexpr ConvolutionFFTImageFilter(unsigned int numIterations) : _num_iterations(numIterations) { /* do nothing */ } /// @} /// @{ -------------------------------------------------- DTOR ~ConvolutionFFTImageFilter() = default; /// @} //==================================================================================================== //===== GETTER //==================================================================================================== /// @{ -------------------------------------------------- GET NUM ITERATIONS [[nodiscard]] constexpr unsigned int num_iterations() const { return _num_iterations; } /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = [[maybe_unused]] constexpr auto operator=(const self_type& other) -> self_type& = default; [[maybe_unused]] constexpr auto operator=(self_type&& other) noexcept -> self_type& = default; /// @} /// @{ -------------------------------------------------- SET NUM ITERATIONS constexpr void set_num_iterations(unsigned int numIterations) { _num_iterations = numIterations; } /// @} //==================================================================================================== //===== FUNCTIONS //==================================================================================================== /// @{ -------------------------------------------------- APPLY template<typename TImage, typename TKernel> [[nodiscard]] static TImage apply(const TImage& img, const TKernel& kernel, unsigned int numIterations) { if (numIterations == 0) { return img; } #ifdef BK_EMIT_PROGRESS Progress& prog = bk_progress.emplace_task(numIterations + 2 * 3, ___("Image convolution filtering")); #endif FFTImageFilter filter_fft; auto img_fft = filter_fft.apply(img); #ifdef BK_EMIT_PROGRESS prog.increment(2); #endif auto size_fft = img_fft.size(); typename TImage::template self_template_type<double> kernel_img; kernel_img.set_size(size_fft); const unsigned int nDims = img.num_dimensions(); auto offset = size_fft; for (unsigned int dimId = 0; dimId < nDims; ++dimId) { offset[dimId] /= 2; offset[dimId] -= kernel.size()[dimId] / 2; } for (unsigned int i = 0; i < kernel.num_values(); ++i) { auto gid_kernel = bk::list_to_grid_id(kernel.size(), i); auto gid_kernel_img = gid_kernel; for (unsigned int dimId = 0; dimId < nDims; ++dimId) { gid_kernel_img[dimId] += offset[dimId]; } kernel_img(gid_kernel_img) = kernel[i]; } kernel_img = FFTShiftImageFilter::apply(kernel_img); FFTImageFilter filter_fft_kernel; filter_fft_kernel.set_normalization_enabled(false); auto kernel_fft = filter_fft_kernel.apply(kernel_img); #ifdef BK_EMIT_PROGRESS prog.increment(2); #endif const unsigned int numValues = img_fft.num_values(); for (unsigned int iterId = 0; iterId < numIterations; ++iterId) { #pragma omp parallel for for (unsigned int i = 0; i < numValues; ++i) { img_fft[i] *= kernel_fft[i]; } #ifdef BK_EMIT_PROGRESS prog.increment(1); #endif } // for iterId IFFTImageFilter filter_ifft(filter_fft); auto res = filter_ifft.apply(img_fft); #ifdef BK_EMIT_PROGRESS prog.set_finished(); #endif return res; } template<typename TImage, typename TKernel> [[nodiscard]] TImage apply(const TImage& img, const TKernel& kernel) const { return apply(img, kernel, num_iterations()); } /// @} }; // class ConvolutionFFTImageFilter } // namespace bk #endif //BK_CONVOLUTIONFFTIMAGEFILTER_H
DRACC_OMP_033_MxV_Partially_outdated_Data_yes.c
/* Matrix Vector multiplication without complitly copying back the result c. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define C 512 int *a; int *b; int *c; int init(){ for(int i=0; i<C; i++){ for(int j=0; j<C; j++){ b[j+i*C]=1; } a[i]=1; c[i]=0; } return 0; } int Mult(){ #pragma omp target map(to:a[0:C],b[0:C*C]) map(tofrom:c[0:C/2]) device(0) { #pragma omp teams distribute parallel for for(int i=0; i<C; i++){ for(int j=0; j<C; j++){ c[i]+=b[j+i*C]*a[j]; } } } return 0; } int check(){ bool test = false; for(int i=0; i<C; i++){ if(c[i]!=C){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ a = malloc(C*sizeof(int)); b = malloc(C*C*sizeof(int)); c = malloc(C*sizeof(int)); init(); Mult(); check(); free(a); free(b); free(c); return 0; }
DRB020-privatemissing-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* tmp should be put as private to avoid race condition Data race pair: tmp@65 vs. tmp@66 */ #include <stdlib.h> int main(int argc, char* argv[]) { int i; int tmp; int len=100; if (argc>1) len = atoi(argv[1]); int a[len]; for (i=0;i<len;i++) a[i]=i; #pragma omp parallel for for (i=0;i<len;i++) { tmp =a[i]+i; a[i] = tmp; } return 0; }
stream.c
/*-----------------------------------------------------------------------*/ /* Program: STREAM */ /* Revision: $Id: stream_mpi.c,v 1.7 2014/10/22 00:13:21 mccalpin Exp mccalpin $ */ /* Original code developed by John D. McCalpin */ /* Programmers: John D. McCalpin */ /* Joe R. Zagar */ /* */ /* This program measures memory transfer rates in MB/s for simple */ /* computational kernels coded in C. */ /*-----------------------------------------------------------------------*/ /* Copyright 1991-2013: John D. McCalpin */ /*-----------------------------------------------------------------------*/ /* License: */ /* 1. You are free to use this program and/or to redistribute */ /* this program. */ /* 2. You are free to modify this program for your own use, */ /* including commercial use, subject to the publication */ /* restrictions in item 3. */ /* 3. You are free to publish results obtained from running this */ /* program, or from works that you derive from this program, */ /* with the following limitations: */ /* 3a. In order to be referred to as "STREAM benchmark results", */ /* published results must be in conformance to the STREAM */ /* Run Rules, (briefly reviewed below) published at */ /* http://www.cs.virginia.edu/stream/ref.html */ /* and incorporated herein by reference. */ /* As the copyright holder, John McCalpin retains the */ /* right to determine conformity with the Run Rules. */ /* 3b. Results based on modified source code or on runs not in */ /* accordance with the STREAM Run Rules must be clearly */ /* labelled whenever they are published. Examples of */ /* proper labelling include: */ /* "tuned STREAM benchmark results" */ /* "based on a variant of the STREAM benchmark code" */ /* Other comparable, clear, and reasonable labelling is */ /* acceptable. */ /* 3c. Submission of results to the STREAM benchmark web site */ /* is encouraged, but not required. */ /* 4. Use of this program or creation of derived works based on this */ /* program constitutes acceptance of these licensing restrictions. */ /* 5. Absolutely no warranty is expressed or implied. */ /*-----------------------------------------------------------------------*/ #include <hpcc.h> #include <float.h> #include <limits.h> #ifdef _OPENMP #include <omp.h> #endif #define TUNED 1 #define VERBOSE 1 /* INSTRUCTIONS: * * 1) STREAM requires different amounts of memory to run on different * systems, depending on both the system cache size(s) and the * granularity of the system timer. * You should adjust the value of 'STREAM_ARRAY_SIZE' (below) * to meet *both* of the following criteria: * (a) Each array must be at least 4 times the size of the * available cache memory. I don't worry about the difference * between 10^6 and 2^20, so in practice the minimum array size * is about 3.8 times the cache size. * Example 1: One Xeon E3 with 8 MB L3 cache * STREAM_ARRAY_SIZE should be >= 4 million, giving * an array size of 30.5 MB and a total memory requirement * of 91.5 MB. * Example 2: Two Xeon E5's with 20 MB L3 cache each (using OpenMP) * STREAM_ARRAY_SIZE should be >= 20 million, giving * an array size of 153 MB and a total memory requirement * of 458 MB. * (b) The size should be large enough so that the 'timing calibration' * output by the program is at least 20 clock-ticks. * Example: most versions of Windows have a 10 millisecond timer * granularity. 20 "ticks" at 10 ms/tic is 200 milliseconds. * If the chip is capable of 10 GB/s, it moves 2 GB in 200 msec. * This means the each array must be at least 1 GB, or 128M elements. * * Version 5.10 increases the default array size from 2 million * elements to 10 million elements in response to the increasing * size of L3 caches. The new default size is large enough for caches * up to 20 MB. * Version 5.10 changes the loop index variables from "register int" * to "ssize_t", which allows array indices >2^32 (4 billion) * on properly configured 64-bit systems. Additional compiler options * (such as "-mcmodel=medium") may be required for large memory runs. * * Array size can be set at compile time without modifying the source * code for the (many) compilers that support preprocessor definitions * on the compile line. E.g., * gcc -O -DSTREAM_ARRAY_SIZE=100000000 stream.c -o stream.100M * will override the default size of 10M with a new size of 100M elements * per array. */ /* 2) STREAM runs each kernel "NTIMES" times and reports the *best* result * for any iteration after the first, therefore the minimum value * for NTIMES is 2. * There are no rules on maximum allowable values for NTIMES, but * values larger than the default are unlikely to noticeably * increase the reported performance. * NTIMES can also be set on the compile line without changing the source * code using, for example, "-DNTIMES=7". */ static int array_elements; # define N 2000000 # define NTIMES 10 /* // Make the scalar coefficient modifiable at compile time. // The old value of 3.0 cause floating-point overflows after a relatively small // number of iterations. The new default of 0.42 allows over 2000 iterations for // 32-bit IEEE arithmetic and over 18000 iterations for 64-bit IEEE arithmetic. // The growth in the solution can be eliminated (almost) completely by setting // the scalar value to 0.41421445, but this also means that the error checking // code no longer triggers an error if the code does not actually execute the // correct number of iterations! */ #ifndef SCALAR #define SCALAR 0.42 #endif /* // ----------------------- !!! NOTE CHANGE IN DEFINITION !!! ------------------ // The OFFSET preprocessor variable is not used in this version of the benchmark. // The user must change the code at or after the "posix_memalign" array allocations // to change the relative alignment of the pointers. // ----------------------- !!! NOTE CHANGE IN DEFINITION !!! ------------------ */ # define OFFSET 0 /* * 3) Compile the code with optimization. Many compilers generate * unreasonably bad code before the optimizer tightens things up. * If the results are unreasonably good, on the other hand, the * optimizer might be too smart for me! * * For a simple single-core version, try compiling with: * cc -O stream.c -o stream * This is known to work on many, many systems.... * * To use multiple cores, you need to tell the compiler to obey the OpenMP * directives in the code. This varies by compiler, but a common example is * gcc -O -fopenmp stream.c -o stream_omp * The environment variable OMP_NUM_THREADS allows runtime control of the * number of threads/cores used when the resulting "stream_omp" program * is executed. * * To run with single-precision variables and arithmetic, simply add * -DSTREAM_TYPE=float * to the compile line. * Note that this changes the minimum array sizes required --- see (1) above. * * The preprocessor directive "TUNED" does not do much -- it simply causes the * code to call separate functions to execute each kernel. Trivial versions * of these functions are provided, but they are *not* tuned -- they just * provide predefined interfaces to be replaced with tuned code. * * * 4) Optional: Mail the results to mccalpin@cs.virginia.edu * Be sure to include info that will help me understand: * a) the computer hardware configuration (e.g., processor model, memory type) * b) the compiler name/version and compilation flags * c) any run-time information (such as OMP_NUM_THREADS) * d) all of the output from the test case. * * Thanks! * *-----------------------------------------------------------------------*/ # define HLINE "-------------------------------------------------------------\n" /* Some compilers require an extra keyword to recognize the "restrict" qualifier. */ static double * restrict a, * restrict b, * restrict c; static double avgtime[4] = {0}, maxtime[4] = {0}, mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX}; static char *label[4] = {"Copy: ", "Scale: ", "Add: ", "Triad: "}; static double bytes[4] = { 2 * sizeof(double), 2 * sizeof(double), 3 * sizeof(double), 3 * sizeof(double) }; #ifdef TUNED extern void tuned_STREAM_Copy(void); extern void tuned_STREAM_Scale(double scalar); extern void tuned_STREAM_Add(void); extern void tuned_STREAM_Triad(double scalar); #endif static void checkSTREAMresults(FILE *outFile, int doIO, double *AvgErrByRank, int numranks, int *failure) { double aj,bj,cj,scalar; double aSumErr,bSumErr,cSumErr; double aAvgErr,bAvgErr,cAvgErr; double epsilon; int j, k, ierr, err; /* Repeat the computation of aj, bj, cj */ /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = SCALAR; for (k=0; k<NTIMES; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } /* Compute the average of the average errors contributed by each MPI rank */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (k=0; k<numranks; k++) { aSumErr += AvgErrByRank[3*k + 0]; bSumErr += AvgErrByRank[3*k + 1]; cSumErr += AvgErrByRank[3*k + 2]; } aAvgErr = aSumErr / (double) numranks; bAvgErr = bSumErr / (double) numranks; cAvgErr = cSumErr / (double) numranks; if (sizeof(double) == 4) { epsilon = 1.e-6; } else if (sizeof(double) == 8) { epsilon = 1.e-13; } else if (sizeof(double) == 10) { epsilon = 1.e-23; } else { if (doIO) fprintf( outFile, "WEIRD: sizeof(double) = %lu\n",sizeof(double)); epsilon = 1.e-6; } *failure = 1; err = 0; if (fabs(aAvgErr/aj) > epsilon) { err++; if (doIO) { fprintf( outFile, "Failed Validation on array a[], AvgRelAbsErr > epsilon (%e)\n",epsilon); fprintf( outFile, " Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",aj,aAvgErr,fabs(aAvgErr)/aj); } ierr = 0; for (j=0; j<array_elements; j++) { if (fabs(a[j]/aj-1.0) > epsilon) { ierr++; } } if (ierr > 0) if (doIO) fprintf( outFile, " For array a[], %d errors were found.\n",ierr); } if (fabs(bAvgErr/bj) > epsilon) { err++; if (doIO) { fprintf( outFile, "Failed Validation on array b[], AvgRelAbsErr > epsilon (%e)\n",epsilon); fprintf( outFile, " Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",bj,bAvgErr,fabs(bAvgErr)/bj); fprintf( outFile, " AvgRelAbsErr > Epsilon (%e)\n",epsilon); } ierr = 0; for (j=0; j<array_elements; j++) { if (fabs(b[j]/bj-1.0) > epsilon) { ierr++; } } if (ierr > 0) if (doIO) fprintf( outFile, " For array b[], %d errors were found.\n",ierr); } if (fabs(cAvgErr/cj) > epsilon) { err++; if (doIO) { fprintf( outFile, "Failed Validation on array c[], AvgRelAbsErr > epsilon (%e)\n",epsilon); fprintf( outFile, " Expected Value: %e, AvgAbsErr: %e, AvgRelAbsErr: %e\n",cj,cAvgErr,fabs(cAvgErr)/cj); fprintf( outFile, " AvgRelAbsErr > Epsilon (%e)\n",epsilon); } ierr = 0; for (j=0; j<array_elements; j++) { if (fabs(c[j]/cj-1.0) > epsilon) { ierr++; } } if (ierr > 0) if (doIO) fprintf( outFile, " For array c[], %d errors were found.\n",ierr); } if (err == 0) { *failure = 0; if (doIO) fprintf( outFile, "Solution Validates: avg error less than %e on all three arrays\n",epsilon); } } # define M 20 static int checktick() { int i, minDelta, Delta; double t1, t2, timesfound[M]; /* Collect a sequence of M unique time values from the system. */ for (i = 0; i < M; i++) { t1 = MPI_Wtime(); while( ((t2=MPI_Wtime()) - t1) < 1.0E-6 ) ; timesfound[i] = t1 = t2; } /* * Determine the minimum difference between these M values. * This result will be our estimate (in microseconds) for the * clock granularity. */ minDelta = 1000000; for (i = 1; i < M; i++) { Delta = (int)( 1.0E6 * (timesfound[i]-timesfound[i-1])); minDelta = Mmin(minDelta, Mmax(Delta,0)); } return(minDelta); } #undef M /* For the MPI code I separate the computation of errors from the error reporting output functions (which are handled by MPI rank 0). */ void computeSTREAMerrors(double *aAvgErr, double *bAvgErr, double *cAvgErr) { double aj,bj,cj,scalar; double aSumErr,bSumErr,cSumErr; int j; int k; /* reproduce initialization */ aj = 1.0; bj = 2.0; cj = 0.0; /* a[] is modified during timing check */ aj = 2.0E0 * aj; /* now execute timing loop */ scalar = SCALAR; for (k=0; k<NTIMES; k++) { cj = aj; bj = scalar*cj; cj = aj+bj; aj = bj+scalar*cj; } /* accumulate deltas between observed and expected results */ aSumErr = 0.0; bSumErr = 0.0; cSumErr = 0.0; for (j=0; j<array_elements; j++) { aSumErr += fabs(a[j] - aj); bSumErr += fabs(b[j] - bj); cSumErr += fabs(c[j] - cj); } *aAvgErr = aSumErr / (double) array_elements; *bAvgErr = bSumErr / (double) array_elements; *cAvgErr = cSumErr / (double) array_elements; } int HPCC_Stream(HPCC_Params *params, int doIO, MPI_Comm comm, int world_rank, double *copyGBs, double *scaleGBs, double *addGBs, double *triadGBs, int *failure) { int quantum, BytesPerWord, numranks, myrank; int j, k; double scalar, t, t0, t1, times[4][NTIMES], times_copy[4][NTIMES]; FILE *outFile; double GiBs = 1024.0 * 1024.0 * 1024.0, curGBs; double AvgError[3] = {0.0,0.0,0.0}; double *AvgErrByRank; if (doIO) { outFile = fopen( params->outFname, "a" ); if (! outFile) { outFile = stderr; fprintf( outFile, "Cannot open output file.\n" ); return 1; } } t0 = MPI_Wtime(); MPI_Comm_size( comm, &numranks ); MPI_Comm_rank( comm, &myrank ); array_elements = HPCC_LocalVectorSize( params, 3, sizeof(double), 0 ); /* Need 3 vectors */ params->StreamVectorSize = array_elements; a = HPCC_XMALLOC( double, array_elements ); b = HPCC_XMALLOC( double, array_elements ); c = HPCC_XMALLOC( double, array_elements ); if (!a || !b || !c) { if (c) HPCC_free(c); if (b) HPCC_free(b); if (a) HPCC_free(a); if (doIO) { fprintf( outFile, "Failed to allocate memory (%d).\n", array_elements ); fflush( outFile ); fclose( outFile ); } /* FIXME: must be made global */ return 1; } /* --- SETUP --- determine precision and check timing --- */ if (doIO) { fprintf( outFile, HLINE); BytesPerWord = sizeof(double); fprintf( outFile, "This system uses %d bytes per DOUBLE PRECISION word.\n", BytesPerWord); fprintf( outFile, HLINE); fprintf( outFile, "Array size = %d, Offset = %d\n" , array_elements, OFFSET); fprintf( outFile, "Total memory required = %.4f GiB.\n", (3.0 * BytesPerWord) * ( (double) array_elements / GiBs)); fprintf( outFile, "Each test is run %d times.\n", NTIMES ); fprintf( outFile, " The *best* time for each kernel (excluding the first iteration)\n" ); fprintf( outFile, " will be used to compute the reported bandwidth.\n"); fprintf( outFile, "The SCALAR value used for this run is %f\n", SCALAR ); } #ifdef _OPENMP if (doIO) fprintf( outFile, HLINE); #pragma omp parallel private(k) { #pragma omp single nowait { k = omp_get_num_threads(); if (doIO) fprintf( outFile, "Number of Threads requested = %i\n",k); params->StreamThreads = k; } } #endif /* --- SETUP --- initialize arrays and estimate precision of timer --- */ #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) { a[j] = 1.0; b[j] = 2.0; c[j] = 0.0; } /* Rank 0 needs to allocate arrays to hold error data and timing data from all ranks for analysis and output. Allocate and instantiate the arrays here -- after the primary arrays have been instantiated -- so there is no possibility of having these auxiliary arrays mess up the NUMA placement of the primary arrays. */ /* There are 3 average error values for each rank (using double). */ AvgErrByRank = HPCC_XMALLOC( double, 3 * numranks ); /* There are 4*NTIMES timing values for each rank (always doubles) */ if (AvgErrByRank == NULL) { if (doIO) fprintf( outFile, "Ooops -- allocation of arrays to collect timing data on MPI rank %d failed\n", world_rank); MPI_Abort(comm, 3); /* FIXME: handle failure more gracefully */ } /* FIXME: replace with loop to use floating-point data */ memset(AvgErrByRank,0,3*sizeof(double)*numranks); if (doIO) fprintf( outFile, HLINE); if ( (quantum = checktick()) >= 1) { if (doIO) fprintf( outFile, "Your clock granularity/precision appears to be " "%d microseconds.\n", quantum); } else { if (doIO) fprintf( outFile, "Your clock granularity appears to be " "less than one microsecond.\n"); } /* Get initial timing estimate to compare to timer granularity. All ranks need to run this code since it changes the values in array `a' */ t = MPI_Wtime(); #ifdef _OPENMP #pragma omp parallel for #endif for (j = 0; j < array_elements; j++) a[j] = 2.0E0 * a[j]; t = 1.0E6 * (MPI_Wtime() - t); if (doIO) { fprintf( outFile, "Each test below will take on the order" " of %d microseconds.\n", (int) t ); fprintf( outFile, " (= %d clock ticks)\n", (int) (t/quantum) ); fprintf( outFile, "Increase the size of the arrays if this shows that\n"); fprintf( outFile, "you are not getting at least 20 clock ticks per test.\n"); fprintf( outFile, HLINE); fprintf( outFile, "WARNING -- The above is only a rough guideline.\n"); fprintf( outFile, "For best results, please be sure you know the\n"); fprintf( outFile, "precision of your system timer.\n"); fprintf( outFile, HLINE); t1 = MPI_Wtime(); fprintf( outFile, "VERBOSE: total setup time for rank 0 = %f seconds\n",t1-t0); fprintf( outFile, HLINE); } /* --- MAIN LOOP --- repeat test cases NTIMES times --- */ /* This code has more barriers and timing calls than are actually needed, but this should not cause a problem for arrays that are large enough to satisfy the STREAM run rules. */ scalar = SCALAR; for (k=0; k<NTIMES; k++) { /* kernel 1: Copy */ MPI_Barrier( comm ); times[0][k] = MPI_Wtime(); #ifdef TUNED tuned_STREAM_Copy(); #else #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) c[j] = a[j]; #endif MPI_Barrier( comm ); times[0][k] = MPI_Wtime() - times[0][k]; /* kernel 2: Scale */ MPI_Barrier( comm ); times[1][k] = MPI_Wtime(); #ifdef TUNED tuned_STREAM_Scale(scalar); #else #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) b[j] = scalar*c[j]; #endif MPI_Barrier( comm ); times[1][k] = MPI_Wtime() - times[1][k]; /* kernel 3: Add */ MPI_Barrier( comm ); times[2][k] = MPI_Wtime(); #ifdef TUNED tuned_STREAM_Add(); #else #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) c[j] = a[j]+b[j]; #endif MPI_Barrier( comm ); times[2][k] = MPI_Wtime() - times[2][k]; /* kernel 4: Triad */ MPI_Barrier( comm ); times[3][k] = MPI_Wtime(); #ifdef TUNED tuned_STREAM_Triad(scalar); #else #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) a[j] = b[j]+scalar*c[j]; #endif MPI_Barrier( comm ); times[3][k] = MPI_Wtime() - times[3][k]; } t0 = MPI_Wtime(); /* --- SUMMARY --- */ /* Because of the MPI_Barrier() calls, the timings from any thread are equally valid. The best estimate of the maximum performance is the minimum of the "outside the barrier" timings across all the MPI ranks. */ memcpy(times_copy, times, sizeof times_copy ); /* for each iteration and each kernel, collect the minimum time across all MPI ranks */ MPI_Allreduce( times_copy, times, 4*NTIMES, MPI_DOUBLE, MPI_MIN, comm ); /* Back to the original code, but now using the minimum global timing across all ranks */ for (k=1; k<NTIMES; k++) /* note -- skip first iteration */ { for (j=0; j<4; j++) { avgtime[j] = avgtime[j] + times[j][k]; mintime[j] = Mmin(mintime[j], times[j][k]); maxtime[j] = Mmax(maxtime[j], times[j][k]); } } if (doIO) fprintf( outFile, "Function Rate (GB/s) Avg time Min time Max time\n"); for (j=0; j<4; j++) { avgtime[j] /= (double)(NTIMES - 1); /* note -- skip first iteration */ /* make sure no division by zero */ curGBs = (mintime[j] > 0.0 ? 1.0 / mintime[j] : -1.0); curGBs *= 1e-9 * bytes[j] * array_elements; if (doIO) fprintf( outFile, "%s%11.4f %11.4f %11.4f %11.4f\n", label[j], curGBs, avgtime[j], mintime[j], maxtime[j]); switch (j) { case 0: *copyGBs = curGBs; break; case 1: *scaleGBs = curGBs; break; case 2: *addGBs = curGBs; break; case 3: *triadGBs = curGBs; break; } } if (doIO) fprintf( outFile, HLINE); /* --- Every Rank Checks its Results --- */ computeSTREAMerrors(&AvgError[0], &AvgError[1], &AvgError[2]); /* --- Collect the Average Errors for Each Array on Rank 0 --- */ MPI_Gather(AvgError, 3, MPI_DOUBLE, AvgErrByRank, 3, MPI_DOUBLE, 0, comm); /* -- Combined averaged errors and report on Rank 0 only --- */ if (myrank == 0) { checkSTREAMresults( outFile, doIO, AvgErrByRank, numranks, failure ); if (doIO) fprintf( outFile, HLINE); } HPCC_free(AvgErrByRank); HPCC_free(c); HPCC_free(b); HPCC_free(a); if (doIO) { fflush( outFile ); fclose( outFile ); } return 0; } void tuned_STREAM_Copy() { int j; #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) c[j] = a[j]; } void tuned_STREAM_Scale(double scalar) { int j; #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) b[j] = scalar*c[j]; } void tuned_STREAM_Add() { int j; #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) c[j] = a[j]+b[j]; } void tuned_STREAM_Triad(double scalar) { int j; #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<array_elements; j++) a[j] = b[j]+scalar*c[j]; }
GB_emult_02.c
//------------------------------------------------------------------------------ // GB_emult_02: C = A.*B where A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C = A.*B where A is sparse/hyper and B is bitmap/full constructs C with // the same sparsity structure as A. This method can also be called with // the two input matrices swapped, with flipxy true, to handle the case // where A is bitmap/full and B is sparse/hyper. // When no mask is present, or the mask is applied later, this method handles // the following cases: // ------------------------------------------ // C = A .* B // ------------------------------------------ // sparse . sparse bitmap // sparse . sparse full // sparse . bitmap sparse // sparse . full sparse // If M is sparse/hyper and complemented, it is not passed here: // ------------------------------------------ // C <!M>= A .* B // ------------------------------------------ // sparse sparse sparse bitmap (mask later) // sparse sparse sparse full (mask later) // sparse sparse bitmap sparse (mask later) // sparse sparse full sparse (mask later) // If M is present, it is bitmap/full: // ------------------------------------------ // C <M> = A .* B // ------------------------------------------ // sparse bitmap sparse bitmap // sparse bitmap sparse full // sparse bitmap bitmap sparse // sparse bitmap full sparse // ------------------------------------------ // C <M> = A .* B // ------------------------------------------ // sparse full sparse bitmap // sparse full sparse full // sparse full bitmap sparse // sparse full full sparse // ------------------------------------------ // C <!M> = A .* B // ------------------------------------------ // sparse bitmap sparse bitmap // sparse bitmap sparse full // sparse bitmap bitmap sparse // sparse bitmap full sparse // ------------------------------------------ // C <!M> = A .* B // ------------------------------------------ // sparse full sparse bitmap // sparse full sparse full // sparse full bitmap sparse // sparse full full sparse #include "GB_ewise.h" #include "GB_emult.h" #include "GB_binop.h" #include "GB_unused.h" #ifndef GBCOMPACT #include "GB_binop__include.h" #endif #define GB_FREE_WORKSPACE \ { \ GB_WERK_POP (Work, int64_t) ; \ GB_WERK_POP (A_ek_slicing, int64_t) ; \ } #define GB_FREE_ALL \ { \ GB_FREE_WORKSPACE ; \ GB_phbix_free (C) ; \ } GrB_Info GB_emult_02 // C=A.*B when A is sparse/hyper, B bitmap/full ( GrB_Matrix C, // output matrix, static header const GrB_Type ctype, // type of output matrix C const bool C_is_csc, // format of output matrix C const GrB_Matrix M, // optional mask, unused if NULL const bool Mask_struct, // if true, use the only structure of M const bool Mask_comp, // if true, use !M const GrB_Matrix A, // input A matrix (sparse/hyper) const GrB_Matrix B, // input B matrix (bitmap/full) GrB_BinaryOp op, // op to perform C = op (A,B) bool flipxy, // if true use fmult(y,x) else fmult(x,y) GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT (C != NULL && C->static_header) ; ASSERT_MATRIX_OK_OR_NULL (M, "M for emult_02", GB0) ; ASSERT_MATRIX_OK (A, "A for emult_02", GB0) ; ASSERT_MATRIX_OK (B, "B for emult_02", GB0) ; ASSERT_BINARYOP_OK (op, "op for emult_02", GB0) ; ASSERT_TYPE_OK (ctype, "ctype for emult_02", GB0) ; ASSERT (GB_IS_SPARSE (A) || GB_IS_HYPERSPARSE (A)) ; ASSERT (!GB_PENDING (A)) ; ASSERT (GB_JUMBLED_OK (A)) ; ASSERT (!GB_ZOMBIES (A)) ; ASSERT (GB_IS_BITMAP (B) || GB_IS_FULL (B)) ; ASSERT (M == NULL || GB_IS_BITMAP (B) || GB_IS_FULL (B)) ; int C_sparsity = GB_sparsity (A) ; if (M == NULL) { GBURBLE ("emult_02:(%s=%s.*%s)", GB_sparsity_char (C_sparsity), GB_sparsity_char_matrix (A), GB_sparsity_char_matrix (B)) ; } else { GBURBLE ("emult_02:(%s<%s%s%s>=%s.*%s) ", GB_sparsity_char (C_sparsity), Mask_comp ? "!" : "", GB_sparsity_char_matrix (M), Mask_struct ? ",struct" : "", GB_sparsity_char_matrix (A), GB_sparsity_char_matrix (B)) ; } //-------------------------------------------------------------------------- // revise the operator to handle flipxy //-------------------------------------------------------------------------- // Replace the ANY operator with SECOND. ANY and SECOND give the same // result if flipxy is false. However, SECOND is changed to FIRST if // flipxy is true. This ensures that the results do not depend on the // sparsity structures of A and B. if (op->opcode == GB_ANY_binop_code) { switch (op->xtype->code) { case GB_BOOL_code : op = GrB_SECOND_BOOL ; break ; case GB_INT8_code : op = GrB_SECOND_INT8 ; break ; case GB_INT16_code : op = GrB_SECOND_INT16 ; break ; case GB_INT32_code : op = GrB_SECOND_INT32 ; break ; case GB_INT64_code : op = GrB_SECOND_INT64 ; break ; case GB_UINT8_code : op = GrB_SECOND_UINT8 ; break ; case GB_UINT16_code : op = GrB_SECOND_UINT16 ; break ; case GB_UINT32_code : op = GrB_SECOND_UINT32 ; break ; case GB_UINT64_code : op = GrB_SECOND_UINT64 ; break ; case GB_FP32_code : op = GrB_SECOND_FP32 ; break ; case GB_FP64_code : op = GrB_SECOND_FP64 ; break ; case GB_FC32_code : op = GxB_SECOND_FC32 ; break ; case GB_FC64_code : op = GxB_SECOND_FC64 ; break ; default: ; } } if (flipxy) { bool handled ; op = GB_flip_op (op, &handled) ; if (handled) flipxy = false ; } ASSERT_BINARYOP_OK (op, "final op for emult_02", GB0) ; //-------------------------------------------------------------------------- // declare workspace //-------------------------------------------------------------------------- GB_WERK_DECLARE (Work, int64_t) ; int64_t *restrict Wfirst = NULL ; int64_t *restrict Wlast = NULL ; int64_t *restrict Cp_kfirst = NULL ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; //-------------------------------------------------------------------------- // get M, A, and B //-------------------------------------------------------------------------- const int8_t *restrict Mb = (M == NULL) ? NULL : M->b ; const GB_void *restrict Mx = (M == NULL || Mask_struct) ? NULL : (const GB_void *) M->x ; const size_t msize = (M == NULL) ? 0 : M->type->size ; const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const int64_t vlen = A->vlen ; const int64_t vdim = A->vdim ; const int64_t nvec = A->nvec ; const int64_t anz = GB_nnz (A) ; const int8_t *restrict Bb = B->b ; const bool B_is_bitmap = GB_IS_BITMAP (B) ; //-------------------------------------------------------------------------- // check if C is iso and compute its iso value if it is //-------------------------------------------------------------------------- const size_t csize = ctype->size ; GB_void cscalar [GB_VLA(csize)] ; bool C_iso = GB_iso_emult (cscalar, ctype, A, B, op) ; //-------------------------------------------------------------------------- // allocate C->p and C->h //-------------------------------------------------------------------------- GB_OK (GB_new (&C, true, // sparse or hyper (same as A), static header ctype, vlen, vdim, GB_Ap_calloc, C_is_csc, C_sparsity, A->hyper_switch, nvec, Context)) ; int64_t *restrict Cp = C->p ; //-------------------------------------------------------------------------- // slice the input matrix A //-------------------------------------------------------------------------- int A_nthreads, A_ntasks ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; GB_SLICE_MATRIX (A, 8, chunk) ; //-------------------------------------------------------------------------- // count entries in C //-------------------------------------------------------------------------- C->nvec_nonempty = A->nvec_nonempty ; C->nvec = nvec ; const bool C_has_pattern_of_A = !B_is_bitmap && (M == NULL) ; if (!C_has_pattern_of_A) { //---------------------------------------------------------------------- // allocate workspace //---------------------------------------------------------------------- GB_WERK_PUSH (Work, 3*A_ntasks, int64_t) ; if (Work == NULL) { // out of memory GB_FREE_ALL ; return (GrB_OUT_OF_MEMORY) ; } Wfirst = Work ; Wlast = Work + A_ntasks ; Cp_kfirst = Work + A_ntasks * 2 ; //---------------------------------------------------------------------- // count entries in C //---------------------------------------------------------------------- // This phase is very similar to GB_select_phase1 (GB_ENTRY_SELECTOR). if (M == NULL) { //------------------------------------------------------------------ // Method2(a): C = A.*B where A is sparse/hyper and B is bitmap //------------------------------------------------------------------ ASSERT (B_is_bitmap) ; int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; for (int64_t k = kfirst ; k <= klast ; k++) { // count the entries in C(:,j) int64_t j = GBH (Ah, k) ; int64_t pB_start = j * vlen ; int64_t pA, pA_end ; GB_get_pA (&pA, &pA_end, tid, k, kfirst, klast, pstart_Aslice, Ap, vlen) ; int64_t cjnz = 0 ; for ( ; pA < pA_end ; pA++) { cjnz += Bb [pB_start + Ai [pA]] ; } if (k == kfirst) { Wfirst [tid] = cjnz ; } else if (k == klast) { Wlast [tid] = cjnz ; } else { Cp [k] = cjnz ; } } } } else { //------------------------------------------------------------------ // Method2(c): C<#M> = A.*B; M, B bitmap/full, A is sparse/hyper //------------------------------------------------------------------ ASSERT (M != NULL) ; int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; Wfirst [tid] = 0 ; Wlast [tid] = 0 ; for (int64_t k = kfirst ; k <= klast ; k++) { // count the entries in C(:,j) int64_t j = GBH (Ah, k) ; int64_t pB_start = j * vlen ; int64_t pA, pA_end ; GB_get_pA (&pA, &pA_end, tid, k, kfirst, klast, pstart_Aslice, Ap, vlen) ; int64_t cjnz = 0 ; for ( ; pA < pA_end ; pA++) { int64_t i = Ai [pA] ; int64_t pB = pB_start + i ; bool mij = GBB (Mb, pB) && GB_mcast (Mx, pB, msize) ; mij = mij ^ Mask_comp ; cjnz += (mij && GBB (Bb, pB)) ; } if (k == kfirst) { Wfirst [tid] = cjnz ; } else if (k == klast) { Wlast [tid] = cjnz ; } else { Cp [k] = cjnz ; } } } } //---------------------------------------------------------------------- // finalize Cp, cumulative sum of Cp and compute Cp_kfirst //---------------------------------------------------------------------- GB_ek_slice_merge1 (Cp, Wfirst, Wlast, A_ek_slicing, A_ntasks) ; GB_ek_slice_merge2 (&(C->nvec_nonempty), Cp_kfirst, Cp, nvec, Wfirst, Wlast, A_ek_slicing, A_ntasks, A_nthreads, Context) ; } //-------------------------------------------------------------------------- // allocate C->i and C->x //-------------------------------------------------------------------------- int64_t cnz = (C_has_pattern_of_A) ? anz : Cp [nvec] ; // set C->iso = C_iso OK GB_OK (GB_bix_alloc (C, cnz, GxB_SPARSE, false, true, C_iso, Context)) ; //-------------------------------------------------------------------------- // copy pattern into C //-------------------------------------------------------------------------- // TODO: could make these components of C shallow instead of memcpy if (GB_IS_HYPERSPARSE (A)) { // copy A->h into C->h GB_memcpy (C->h, Ah, nvec * sizeof (int64_t), A_nthreads) ; } if (C_has_pattern_of_A) { // Method2(b): B is full and no mask present, so the pattern of C is // the same as the pattern of A GB_memcpy (Cp, Ap, (nvec+1) * sizeof (int64_t), A_nthreads) ; GB_memcpy (C->i, Ai, cnz * sizeof (int64_t), A_nthreads) ; } C->jumbled = A->jumbled ; C->magic = GB_MAGIC ; //-------------------------------------------------------------------------- // get the opcode //-------------------------------------------------------------------------- // if flipxy was true on input and the op is positional, FIRST, SECOND, or // PAIR, the op has already been flipped, so these tests do not have to // consider that case. GB_Opcode opcode = op->opcode ; bool op_is_positional = GB_OPCODE_IS_POSITIONAL (opcode) ; bool op_is_first = (opcode == GB_FIRST_binop_code) ; bool op_is_second = (opcode == GB_SECOND_binop_code) ; bool op_is_pair = (opcode == GB_PAIR_binop_code) ; GB_Type_code ccode = ctype->code ; //-------------------------------------------------------------------------- // check if the values of A and/or B are ignored //-------------------------------------------------------------------------- // With C = ewisemult (A,B), only the intersection of A and B is used. // If op is SECOND or PAIR, the values of A are never accessed. // If op is FIRST or PAIR, the values of B are never accessed. // If op is PAIR, the values of A and B are never accessed. // Contrast with ewiseadd. // A is passed as x, and B as y, in z = op(x,y) bool A_is_pattern = op_is_second || op_is_pair || op_is_positional ; bool B_is_pattern = op_is_first || op_is_pair || op_is_positional ; //-------------------------------------------------------------------------- // using a built-in binary operator (except for positional operators) //-------------------------------------------------------------------------- #define GB_PHASE_2_OF_2 bool done = false ; if (C_iso) { //---------------------------------------------------------------------- // C is iso //---------------------------------------------------------------------- // Cx [0] = cscalar = op (A,B) GB_BURBLE_MATRIX (C, "(iso emult) ") ; memcpy (C->x, cscalar, csize) ; // pattern of C = set intersection of pattern of A and B // flipxy is ignored since the operator is not applied #define GB_ISO_EMULT #include "GB_emult_02_template.c" done = true ; } else { #ifndef GBCOMPACT //------------------------------------------------------------------ // define the worker for the switch factory //------------------------------------------------------------------ #define GB_AemultB_02(mult,xname) GB (_AemultB_02_ ## mult ## xname) #define GB_BINOP_WORKER(mult,xname) \ { \ info = GB_AemultB_02(mult,xname) (C, \ M, Mask_struct, Mask_comp, A, B, flipxy, \ Cp_kfirst, A_ek_slicing, A_ntasks, A_nthreads) ; \ done = (info != GrB_NO_VALUE) ; \ } \ break ; //------------------------------------------------------------------ // launch the switch factory //------------------------------------------------------------------ GB_Type_code xcode, ycode, zcode ; if (!op_is_positional && GB_binop_builtin (A->type, A_is_pattern, B->type, B_is_pattern, op, false, &opcode, &xcode, &ycode, &zcode) && ccode == zcode) { #define GB_NO_PAIR #include "GB_binop_factory.c" } #endif } //-------------------------------------------------------------------------- // generic worker //-------------------------------------------------------------------------- if (!done) { GB_BURBLE_MATRIX (C, "(generic emult_02: %s) ", op->name) ; int ewise_method = flipxy ? GB_EMULT_METHOD3 : GB_EMULT_METHOD2 ; GB_ewise_generic (C, op, NULL, 0, 0, NULL, NULL, NULL, C_sparsity, ewise_method, Cp_kfirst, NULL, 0, 0, A_ek_slicing, A_ntasks, A_nthreads, NULL, 0, 0, M, Mask_struct, Mask_comp, A, B, Context) ; } //-------------------------------------------------------------------------- // remove empty vectors from C, if hypersparse //-------------------------------------------------------------------------- GB_OK (GB_hypermatrix_prune (C, Context)) ; //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORKSPACE ; ASSERT_MATRIX_OK (C, "C output for emult_02", GB0) ; return (GrB_SUCCESS) ; }
oddEvenSort.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> /* This program allows you to sort an array of different sizes. This algorithm is optimized as it avoids contention by using two variables for exchanges. A thread enters the parallel section only if these two fields are reset */ void oddEvenSort(int *a, int size); int main(){ int size, i; int *a; printf("Enter the size of the vector: "); scanf("%d", &size); a = (int *)malloc(size*sizeof(int)); srand(time(NULL)); for(i=0; i<size; i++) { a[i]=1+rand()%100; printf("[%d]\t", a[i]); } oddEvenSort(a, size); printf("\n"); for(i=0; i<size; i++) { printf("[%d]\t", a[i]); } free(a); return 0; } void oddEvenSort(int *a, int size) { //sw0 and sw1 are variables to control exchanges int sw0=0, sw1 = 0, i = 0, t= 0, temp; //It runs the loop only if the odd part is completely sorted while(!sw1) { sw0=1; sw1=1; #pragma omp parallel shared(a, size, sw0, sw1, t) private(temp, i) { //Even part #pragma omp for for(i=0; i<size-1; i+=2) { if(a[i]>a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; sw0=0; } } /* If you have traded on the even side, then you do the odd side as well and if this is the first time the loop has run */ if(!sw0 || !t) { #pragma omp for for(i=1; i<size -1; i+=2) { if(a[i] > a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; sw1=0; } } //Sets that the cycle has run at least once. t = 1; } } } }
omp-master.c
#include <stdio.h> int main() { #pragma omp parallel { #pragma omp master printf("this should be thread 0: %d\n", omp_get_thread_num()); printf("all threads: %d\n", omp_get_thread_num()); } return 0; }
simulation_context.h
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \file simulation_context.h * * \brief Contains definition and implementation of Simulation_parameters and Simulation_context classes. */ #ifndef __SIMULATION_CONTEXT_H__ #define __SIMULATION_CONTEXT_H__ #include "simulation_parameters.h" #include "mpi_grid.hpp" #include "step_function.h" #include "real_space_prj.h" #include "version.h" #include "augmentation_operator.h" #include "radial_integrals.h" #ifdef __GPU extern "C" void generate_phase_factors_gpu(int num_gvec_loc__, int num_atoms__, int const* gvec__, double const* atom_pos__, cuDoubleComplex* phase_factors__); #endif namespace sirius { /// Simulation context is a set of parameters and objects describing a single simulation. /** The order of initialization of the simulation context is the following: first, the default parameter * values are set in the constructor, then (optionally) import() method is called and the parameters are * overwritten with the those from the input file, and finally, the user sets the values with set_...() metods. * Then the unit cell can be populated and the context can be initialized. */ class Simulation_context: public Simulation_parameters { private: /// Communicator for this simulation. Communicator const& comm_; /// Unit cell of the simulation. Unit_cell unit_cell_; /// MPI grid for this simulation. std::unique_ptr<MPI_grid> mpi_grid_; /// 2D BLACS grid for distributed linear algebra operations. std::unique_ptr<BLACS_grid> blacs_grid_; /// Fine-grained FFT for density and potential. /** This is the FFT driver to transform periodic functions such as density and potential on the fine-grained * FFT grid. The transformation is parallel. */ std::unique_ptr<FFT3D> fft_; /// Coarse-grained FFT for application of local potential and density summation. std::unique_ptr<FFT3D> fft_coarse_; /// Step function is used in full-potential methods. std::unique_ptr<Step_function> step_function_; /// G-vectors within the Gmax cutoff. Gvec gvec_; /// G-vectors within the 2 * |Gmax^{WF}| cutoff. Gvec gvec_coarse_; std::vector<Augmentation_operator> augmentation_op_; std::unique_ptr<Real_space_prj> real_space_prj_; /// Creation time of the context. timeval start_time_; std::string start_time_tag_; ev_solver_t std_evp_solver_type_{ev_lapack}; ev_solver_t gen_evp_solver_type_{ev_lapack}; mdarray<double_complex, 3> phase_factors_; #ifdef __GPU mdarray<int, 2> gvec_coord_; std::vector<mdarray<double, 2>> atom_coord_; #endif std::unique_ptr<Radial_integrals> radial_integrals_; mdarray<char, 1> memory_buffer_; double time_active_; bool initialized_{false}; void init_fft(); /* copy constructor is forbidden */ Simulation_context(Simulation_context const&) = delete; void start() { gettimeofday(&start_time_, NULL); tm const* ptm = localtime(&start_time_.tv_sec); char buf[100]; strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", ptm); start_time_tag_ = std::string(buf); } public: Simulation_context(std::string const& fname__, Communicator const& comm__) : comm_(comm__), unit_cell_(*this, comm_) { PROFILE("sirius::Simulation_context::Simulation_context"); start(); import(fname__); unit_cell_.import(unit_cell_input_section_); } Simulation_context(Communicator const& comm__) : comm_(comm__), unit_cell_(*this, comm_) { PROFILE("sirius::Simulation_context::Simulation_context"); start(); } ~Simulation_context() { PROFILE("sirius::Simulation_context::~Simulation_context"); //time_active_ += runtime::wtime(); //if (mpi_comm_world().rank() == 0 && initialized_) { // printf("Simulation_context active time: %.4f sec.\n", time_active_); //} } /// Initialize the similation (can only be called once). void initialize(); void print_info(); Unit_cell& unit_cell() { return unit_cell_; } Unit_cell const& unit_cell() const { return unit_cell_; } Step_function const& step_function() const { return *step_function_; } inline FFT3D& fft() const { return *fft_; } inline FFT3D& fft_coarse() const { return *fft_coarse_; } Gvec const& gvec() const { return gvec_; } Gvec const& gvec_coarse() const { return gvec_coarse_; } BLACS_grid const& blacs_grid() const { return *blacs_grid_; } /// Total communicator of the context. Communicator const& comm() const { return comm_; } /// Communicator between k-points. Communicator const& comm_k() const { /* 3rd dimension of the MPI grid is used for k-point distribution */ return mpi_grid_->communicator(1 << 2); } /// Band and BLACS grid communicator. Communicator const& comm_band() const { /* 1st and 2nd dimensions of the MPI grid are used for parallelization inside k-point */ return mpi_grid_->communicator(1 << 0 | 1 << 1); } /// Communicator of the dense FFT grid. Communicator const& comm_fft() const { /* 1st dimension of MPI grid is used */ return mpi_grid_->communicator(1 << 0); } /// Communicator of the coarse FFT grid. Communicator const& comm_fft_coarse() const { if (control_input_section_.fft_mode_ == "serial") { return mpi_comm_self(); } else { return comm_fft(); } } inline int num_fv_states() const { return num_fv_states_; } inline int num_bands() const { return num_spins() * num_fv_states_; } void create_storage_file() const { if (comm_.rank() == 0) { /* create new hdf5 file */ HDF5_tree fout(storage_file_name, true); fout.create_node("parameters"); fout.create_node("effective_potential"); fout.create_node("effective_magnetic_field"); fout.create_node("density"); fout.create_node("magnetization"); fout["parameters"].write("num_spins", num_spins()); fout["parameters"].write("num_mag_dims", num_mag_dims()); fout["parameters"].write("num_bands", num_bands()); mdarray<int, 2> gv(3, gvec_.num_gvec()); for (int ig = 0; ig < gvec_.num_gvec(); ig++) { auto G = gvec_.gvec(ig); for (int x: {0, 1, 2}) gv(x, ig) = G[x]; } fout["parameters"].write("num_gvec", gvec_.num_gvec()); fout["parameters"].write("gvec", gv); } comm_.barrier(); } Real_space_prj& real_space_prj() const { return *real_space_prj_; } inline std::string const& start_time_tag() const { return start_time_tag_; } inline void set_iterative_solver_tolerance(double tolerance__) { iterative_solver_input_section_.energy_tolerance_ = tolerance__; } inline double iterative_solver_tolerance() const { return iterative_solver_input_section_.energy_tolerance_; } inline ev_solver_t std_evp_solver_type() const { return std_evp_solver_type_; } inline ev_solver_t gen_evp_solver_type() const { return gen_evp_solver_type_; } inline Augmentation_operator const& augmentation_op(int iat__) const { return augmentation_op_[iat__]; } inline double_complex gvec_phase_factor(vector3d<int> G__, int ia__) const { return phase_factors_(0, G__[0], ia__) * phase_factors_(1, G__[1], ia__) * phase_factors_(2, G__[2], ia__); } /// Phase factors \f$ e^{i {\bf G} {\bf r}_{\alpha}} \f$ inline double_complex gvec_phase_factor(int ig__, int ia__) const { return gvec_phase_factor(gvec_.gvec(ig__), ia__); } inline int gvec_count() const { return gvec_.gvec_count(comm_.rank()); } inline int gvec_offset() const { return gvec_.gvec_offset(comm_.rank()); } #ifdef __GPU inline mdarray<int, 2> const& gvec_coord() const { return gvec_coord_; } inline mdarray<double, 2> const& atom_coord(int iat__) const { return atom_coord_[iat__]; } #endif inline void generate_phase_factors(int iat__, mdarray<double_complex, 2>& phase_factors__) const { int na = unit_cell_.atom_type(iat__).num_atoms(); switch (processing_unit_) { case CPU: { #pragma omp parallel for for (int igloc = 0; igloc < gvec_count(); igloc++) { int ig = gvec_offset() + igloc; for (int i = 0; i < na; i++) { int ia = unit_cell_.atom_type(iat__).atom_id(i); phase_factors__(igloc, i) = gvec_phase_factor(ig, ia); } } break; } case GPU: { #ifdef __GPU generate_phase_factors_gpu(gvec_count(), na, gvec_coord().at<GPU>(), atom_coord(iat__).at<GPU>(), phase_factors__.at<GPU>()); #else TERMINATE_NO_GPU #endif break; } } } Radial_integrals const& radial_integrals() const { return *radial_integrals_; } /// Return pointer to already allocated temporary memory buffer. inline void* memory_buffer(size_t size__) { if (memory_buffer_.size() < size__) { memory_buffer_ = mdarray<char, 1>(size__); } return memory_buffer_.at<CPU>(); } }; inline void Simulation_context::init_fft() { auto rlv = unit_cell_.reciprocal_lattice_vectors(); int npr = control_input_section_.mpi_grid_dims_[0]; int npc = control_input_section_.mpi_grid_dims_[1]; if (!(control_input_section_.fft_mode_ == "serial" || control_input_section_.fft_mode_ == "parallel")) { TERMINATE("wrong FFT mode"); } /* create FFT driver for dense mesh (density and potential) */ fft_ = std::unique_ptr<FFT3D>(new FFT3D(find_translations(pw_cutoff(), rlv), comm_fft(), processing_unit())); /* create a list of G-vectors for dense FFT grid; G-vectors are divided between all available MPI ranks.*/ gvec_ = Gvec(rlv, pw_cutoff(), comm(), comm_fft(), control_input_section_.reduce_gvec_); /* prepare fine-grained FFT driver for the entire simulation */ fft_->prepare(gvec_.partition()); /* create FFT driver for coarse mesh */ fft_coarse_ = std::unique_ptr<FFT3D>(new FFT3D(find_translations(2 * gk_cutoff(), rlv), comm_fft_coarse(), processing_unit())); /* create a list of G-vectors for corase FFT grid */ gvec_coarse_ = Gvec(rlv, gk_cutoff() * 2, comm(), comm_fft_coarse(), control_input_section_.reduce_gvec_); } inline void Simulation_context::initialize() { PROFILE("sirius::Simulation_context::initialize"); /* can't initialize twice */ if (initialized_) { TERMINATE("Simulation context is already initialized."); } /* get processing unit */ std::string pu = control_input_section_.processing_unit_; if (pu == "") { #ifdef __GPU pu = "gpu"; #else pu = "cpu"; #endif } if (pu == "cpu") { processing_unit_ = CPU; } else if (pu == "gpu") { processing_unit_ = GPU; } else { TERMINATE("wrong processing unit"); } /* check if we can use a GPU device */ if (processing_unit() == GPU) { #ifndef __GPU TERMINATE_NO_GPU #endif } /* check MPI grid dimensions and set a default grid if needed */ if (!control_input_section_.mpi_grid_dims_.size()) { control_input_section_.mpi_grid_dims_ = {1, 1}; } if (control_input_section_.mpi_grid_dims_.size() != 2) { TERMINATE("wrong MPI grid"); } int npr = control_input_section_.mpi_grid_dims_[0]; int npc = control_input_section_.mpi_grid_dims_[1]; int npb = npr * npc; int npk = comm_.size() / npb; if (npk * npb != comm_.size()) { std::stringstream s; s << "Can't divide " << comm_.size() << " ranks into groups of size " << npb; TERMINATE(s); } /* setup MPI grid */ mpi_grid_ = std::unique_ptr<MPI_grid>(new MPI_grid({npr, npc, npk}, comm_)); /* setup BLACS grid */ blacs_grid_ = std::unique_ptr<BLACS_grid>(new BLACS_grid(comm_band(), npr, npc)); /* can't use reduced G-vectors in LAPW code */ if (full_potential()) { control_input_section_.reduce_gvec_ = false; } if (!iterative_solver_input_section_.type_.size()) { if (full_potential()) { iterative_solver_input_section_.type_ = "exact"; } else { iterative_solver_input_section_.type_ = "davidson"; } } /* initialize variables, related to the unit cell */ unit_cell_.initialize(); /* find the cutoff for G+k vectors (derived from rgkmax (aw_cutoff here) and minimum MT radius) */ if (full_potential()) { set_gk_cutoff(aw_cutoff() / unit_cell_.min_mt_radius()); } if (esm_type() == electronic_structure_method_t::pseudopotential) { lmax_rho_ = unit_cell_.lmax() * 2; lmax_pot_ = unit_cell_.lmax() * 2; } /* initialize FFT interface */ init_fft(); if (comm_.rank() == 0 && control().print_memory_usage_) { MEMORY_USAGE_INFO(); } if (unit_cell_.num_atoms() != 0) { unit_cell_.symmetry().check_gvec_symmetry(gvec_, comm_); if (!full_potential()) { unit_cell_.symmetry().check_gvec_symmetry(gvec_coarse_, comm_); } } auto& fft_grid = fft().grid(); std::pair<int, int> limits(0, 0); for (int x: {0, 1, 2}) { limits.first = std::min(limits.first, fft_grid.limits(x).first); limits.second = std::max(limits.second, fft_grid.limits(x).second); } phase_factors_ = mdarray<double_complex, 3>(3, limits, unit_cell().num_atoms()); #pragma omp parallel for for (int i = limits.first; i <= limits.second; i++) { for (int ia = 0; ia < unit_cell_.num_atoms(); ia++) { auto pos = unit_cell_.atom(ia).position(); for (int x: {0, 1, 2}) { phase_factors_(x, i, ia) = std::exp(double_complex(0.0, twopi * (i * pos[x]))); } } } if (full_potential()) { step_function_ = std::unique_ptr<Step_function>(new Step_function(unit_cell_, fft_.get(), gvec_, comm_)); } /* take 10% of empty non-magnetic states */ if (num_fv_states_ < 0) { num_fv_states_ = static_cast<int>(1e-8 + unit_cell_.num_valence_electrons() / 2.0) + std::max(10, static_cast<int>(0.1 * unit_cell_.num_valence_electrons())); } if (num_fv_states() < static_cast<int>(unit_cell_.num_valence_electrons() / 2.0)) { std::stringstream s; s << "not enough first-variational states : " << num_fv_states(); TERMINATE(s); } /* setup the cyclic block size */ if (cyclic_block_size() < 0) { double a = std::min(std::log2(double(num_fv_states_) / blacs_grid_->num_ranks_col()), std::log2(double(num_fv_states_) / blacs_grid_->num_ranks_row())); if (a < 1) { control_input_section_.cyclic_block_size_ = 2; } else { control_input_section_.cyclic_block_size_ = static_cast<int>(std::min(128.0, std::pow(2.0, static_cast<int>(a))) + 1e-12); } } std::string evsn[] = {std_evp_solver_name(), gen_evp_solver_name()}; if (comm_band().size() == 1) { if (evsn[0] == "") { #if defined(__GPU) && defined(__MAGMA) evsn[0] = "magma"; #else evsn[0] = "lapack"; #endif } if (evsn[1] == "") { #if defined(__GPU) && defined(__MAGMA) evsn[1] = "magma"; #else evsn[1] = "lapack"; #endif } } else { if (evsn[0] == "") { #ifdef __SCALAPACK evsn[0] = "scalapack"; #endif #ifdef __ELPA evsn[0] = "elpa1"; #endif } if (evsn[1] == "") { #ifdef __SCALAPACK evsn[1] = "scalapack"; #endif #ifdef __ELPA evsn[1] = "elpa1"; #endif } } ev_solver_t* evst[] = {&std_evp_solver_type_, &gen_evp_solver_type_}; std::map<std::string, ev_solver_t> str_to_ev_solver_t; str_to_ev_solver_t["lapack"] = ev_lapack; str_to_ev_solver_t["scalapack"] = ev_scalapack; str_to_ev_solver_t["elpa1"] = ev_elpa1; str_to_ev_solver_t["elpa2"] = ev_elpa2; str_to_ev_solver_t["magma"] = ev_magma; str_to_ev_solver_t["plasma"] = ev_plasma; str_to_ev_solver_t["rs_cpu"] = ev_rs_cpu; str_to_ev_solver_t["rs_gpu"] = ev_rs_gpu; for (int i: {0, 1}) { auto name = evsn[i]; if (str_to_ev_solver_t.count(name) == 0) { std::stringstream s; s << "wrong eigen value solver " << name; TERMINATE(s); } *evst[i] = str_to_ev_solver_t[name]; } if (control().verbosity_ > 0 && comm_.rank() == 0) { print_info(); } radial_integrals_ = std::unique_ptr<Radial_integrals>(new Radial_integrals(*this, unit_cell())); if (esm_type() == electronic_structure_method_t::pseudopotential) { /* create augmentation operator Q_{xi,xi'}(G) here */ for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { augmentation_op_.push_back(std::move(Augmentation_operator(comm_, unit_cell_.atom_type(iat), gvec_, unit_cell_.omega(), *radial_integrals_))); } } if (processing_unit() == GPU) { #ifdef __GPU gvec_coord_ = mdarray<int, 2>(gvec_count(), 3, memory_t::host | memory_t::device, "gvec_coord_"); for (int igloc = 0; igloc < gvec_count(); igloc++) { int ig = gvec_offset() + igloc; auto G = gvec_.gvec(ig); for (int x: {0, 1, 2}) { gvec_coord_(igloc, x) = G[x]; } } gvec_coord_.copy_to_device(); for (int iat = 0; iat < unit_cell_.num_atom_types(); iat++) { int nat = unit_cell_.atom_type(iat).num_atoms(); atom_coord_.push_back(std::move(mdarray<double, 2>(nat, 3, memory_t::host | memory_t::device))); for (int i = 0; i < nat; i++) { int ia = unit_cell_.atom_type(iat).atom_id(i); for (int x: {0, 1, 2}) { atom_coord_.back()(i, x) = unit_cell_.atom(ia).position()[x]; } } atom_coord_.back().copy_to_device(); } #endif } //time_active_ = -runtime::wtime(); initialized_ = true; } inline void Simulation_context::print_info() { tm const* ptm = localtime(&start_time_.tv_sec); char buf[100]; strftime(buf, sizeof(buf), "%a, %e %b %Y %H:%M:%S", ptm); printf("\n"); printf("SIRIUS version : %2i.%02i\n", major_version, minor_version); printf("git hash : %s\n", git_hash); printf("build date : %s\n", build_date); printf("start time : %s\n", buf); printf("\n"); printf("number of MPI ranks : %i\n", comm_.size()); printf("MPI grid :"); for (int i = 0; i < mpi_grid_->num_dimensions(); i++) { printf(" %i", mpi_grid_->dimension_size(i)); } printf("\n"); printf("maximum number of OMP threads : %i\n", omp_get_max_threads()); printf("\n"); printf("FFT context for density and potential\n"); printf("=====================================\n"); printf(" comm size : %i\n", comm_fft().size()); printf(" plane wave cutoff : %f\n", pw_cutoff()); auto fft_grid = fft_->grid(); printf(" grid size : %i %i %i total : %i\n", fft_grid.size(0), fft_grid.size(1), fft_grid.size(2), fft_grid.size()); printf(" grid limits : %i %i %i %i %i %i\n", fft_grid.limits(0).first, fft_grid.limits(0).second, fft_grid.limits(1).first, fft_grid.limits(1).second, fft_grid.limits(2).first, fft_grid.limits(2).second); printf(" number of G-vectors within the cutoff : %i\n", gvec_.num_gvec()); printf(" local number of G-vectors : %i\n", gvec_.gvec_count(0)); printf(" number of G-shells : %i\n", gvec_.num_shells()); printf("\n"); printf("FFT context for coarse grid\n"); printf("===========================\n"); printf(" comm size : %i\n", comm_fft_coarse().size()); printf(" plane wave cutoff : %f\n", 2 * gk_cutoff()); fft_grid = fft_coarse_->grid(); printf(" grid size : %i %i %i total : %i\n", fft_grid.size(0), fft_grid.size(1), fft_grid.size(2), fft_grid.size()); printf(" grid limits : %i %i %i %i %i %i\n", fft_grid.limits(0).first, fft_grid.limits(0).second, fft_grid.limits(1).first, fft_grid.limits(1).second, fft_grid.limits(2).first, fft_grid.limits(2).second); printf(" number of G-vectors within the cutoff : %i\n", gvec_coarse_.num_gvec()); printf(" number of G-shells : %i\n", gvec_coarse_.num_shells()); printf("\n"); unit_cell_.print_info(control().verbosity_); for (int i = 0; i < unit_cell_.num_atom_types(); i++) { unit_cell_.atom_type(i).print_info(); } printf("\n"); printf("total nuclear charge : %i\n", unit_cell_.total_nuclear_charge()); printf("number of core electrons : %f\n", unit_cell_.num_core_electrons()); printf("number of valence electrons : %f\n", unit_cell_.num_valence_electrons()); printf("total number of electrons : %f\n", unit_cell_.num_electrons()); printf("total number of aw basis functions : %i\n", unit_cell_.mt_aw_basis_size()); printf("total number of lo basis functions : %i\n", unit_cell_.mt_lo_basis_size()); printf("number of first-variational states : %i\n", num_fv_states()); printf("number of bands : %i\n", num_bands()); printf("number of spins : %i\n", num_spins()); printf("number of magnetic dimensions : %i\n", num_mag_dims()); printf("lmax_apw : %i\n", lmax_apw()); printf("lmax_pw : %i\n", lmax_pw()); printf("lmax_rho : %i\n", lmax_rho()); printf("lmax_pot : %i\n", lmax_pot()); printf("lmax_rf : %i\n", unit_cell_.lmax()); printf("smearing width : %f\n", smearing_width()); printf("cyclic block size : %i\n", cyclic_block_size()); printf("|G+k| cutoff : %f\n", gk_cutoff()); std::string reln[] = {"valence relativity : ", "core relativity : "}; relativity_t relt[] = {valence_relativity_, core_relativity_}; for (int i = 0; i < 2; i++) { printf("%s", reln[i].c_str()); switch (relt[i]) { case relativity_t::none: { printf("none\n"); break; } case relativity_t::koelling_harmon: { printf("Koelling-Harmon\n"); break; } case relativity_t::zora: { printf("zora\n"); break; } case relativity_t::iora: { printf("iora\n"); break; } case relativity_t::dirac: { printf("Dirac\n"); break; } } } std::string evsn[] = {"standard eigen-value solver : ", "generalized eigen-value solver : "}; ev_solver_t evst[] = {std_evp_solver_type_, gen_evp_solver_type_}; for (int i = 0; i < 2; i++) { printf("%s", evsn[i].c_str()); switch (evst[i]) { case ev_lapack: { printf("LAPACK\n"); break; } #ifdef __SCALAPACK case ev_scalapack: { printf("ScaLAPACK\n"); break; } case ev_elpa1: { printf("ELPA1\n"); break; } case ev_elpa2: { printf("ELPA2\n"); break; } case ev_rs_gpu: { printf("RS_gpu\n"); break; } case ev_rs_cpu: { printf("RS_cpu\n"); break; } #endif case ev_magma: { printf("MAGMA\n"); break; } case ev_plasma: { printf("PLASMA\n"); break; } default: { TERMINATE("wrong eigen-value solver"); } } } printf("processing unit : "); switch (processing_unit()) { case CPU: { printf("CPU\n"); break; } case GPU: { printf("GPU\n"); break; } } if (processing_unit() == GPU) { #ifdef __GPU cuda_device_info(); #endif } int i{1}; printf("\n"); printf("XC functionals\n"); printf("==============\n"); for (auto& xc_label: xc_functionals()) { XC_functional xc(xc_label, num_spins()); printf("%i) %s: %s\n", i, xc_label.c_str(), xc.name().c_str()); printf("%s\n", xc.refs().c_str()); i++; } } } // namespace #endif
EPI_fmt_plug.c
/* * EPiServer module for john 1.7.2 (and possibly later) * Uses hashes/salts found in the tblSID of an EPiServer database installation * * Created by Johannes Gumbel (johannes [at] iforge.cc) * * If you have any questions as to how a function incorporates with john, please refer to formats.h of john * * version 0.1 released on 10 jan 2007 * * See doc/README.format-epi for information on the input file format. * * Updated Dec, 2014, JimF. Added OMP, and allowed more than one hash to be * processed at once (OMP_SCALE stuff). */ #if FMT_EXTERNS_H extern struct fmt_main fmt_EPI; #elif FMT_REGISTERS_H john_register_one(&fmt_EPI); #else #include <string.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "sha.h" #ifdef _OPENMP #include <omp.h> #ifdef __MIC__ #ifndef OMP_SCALE #define OMP_SCALE 8192 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 32768 // Tuned, K8-dual HT #endif #endif // __MIC__ #endif #include "memdbg.h" #define CIPHERTEXT_LENGTH 105 #define PLAINTEXT_LENGTH 125 #define BINARY_LENGTH 20 #define BINARY_ALIGN sizeof(uint32_t) #define SALT_LENGTH 30 #define SALT_ALIGN 4 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static int (*key_len); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_LENGTH / 4]; static char global_salt[SALT_LENGTH+1]; static struct fmt_tests global_tests[] = { {"0x5F1D84A6DE97E2BEFB637A3CB5318AFEF0750B856CF1836BD1D4470175BE 0x4D5EFDFA143EDF74193076F174AC47CEBF2F417F", "Abc.!23"}, // new tests from pass_gen.pl {"0x4F5233704337716F63526A7066344B52784F7A6363316750516A72335668 0x7346DA02479E55973E052FC9A173A3FEA4644FF8","test1"}, {"0x76706335715834565A55784662304F3367756350684F634447777A313642 0xDBD3D2764A376673164962E3EE2AE95AB6ED2759","thatsworking"}, {"0x6F724166466172354A7431316A4842746878434B6632744945574A37524A 0xE1ADE625160BB27C16184795715F1C9EF30C45B0","test3"}, {NULL} }; static void init(struct fmt_main *self) { #if defined (_OPENMP) int omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif key_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*key_len)); saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); MEM_FREE(key_len); } /* * Expects ciphertext of format: 0xHEX*60 0xHEX*40 */ static int valid(char *ciphertext, struct fmt_main *self) { unsigned int len, n; if (!ciphertext) return 0; len = strnlen(ciphertext, CIPHERTEXT_LENGTH + 1); if (len != CIPHERTEXT_LENGTH) return 0; // check fixed positions if (ciphertext[0] != '0' || ciphertext[1] != 'x' || ciphertext[62] != ' ' || ciphertext[63] != '0' || ciphertext[64] != 'x') return 0; for (n = 2; n < 62 && atoi16u[ARCH_INDEX(ciphertext[n])] != 0x7F; ++n); if (n < 62) return 0; for (n = 65; n < CIPHERTEXT_LENGTH && atoi16u[ARCH_INDEX(ciphertext[n])] != 0x7F; ++n); return n == len; } static void _tobin(char* dst, char *src, unsigned int len) { unsigned int n; if (src[0] == '0' && src[1] == 'x') src += sizeof(char)*2; for (n = 0; n < len; ++n) dst[n] = atoi16[ARCH_INDEX(src[n*2])]<<4 | atoi16[ARCH_INDEX(src[n*2+1])]; } static void* get_binary(char *ciphertext) { static ARCH_WORD bin[(BINARY_LENGTH + sizeof(ARCH_WORD) - 1) / sizeof(ARCH_WORD)]; _tobin((char*)bin, (char*)(ciphertext+65), BINARY_LENGTH); return bin; } static void* get_salt(char *ciphertext) { static ARCH_WORD salt[(SALT_LENGTH + sizeof(ARCH_WORD) - 1) / sizeof(ARCH_WORD)]; _tobin((char*)salt, (char*)(ciphertext+2), sizeof(salt)); return salt; } static void set_salt(void *salt) { memcpy(global_salt, salt, SALT_LENGTH); } static void set_key(char *key, int index) { if (!key) return; key_len[index] = strlen(key) + 1; strcpy(saved_key[index], key); } static char* get_key(int index) { return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int i=0; #ifdef _OPENMP #pragma omp parallel for private(i) shared(global_salt, saved_key, key_len, crypt_out) #endif #if defined (_OPENMP) || MAX_KEYS_PER_CRYPT>1 for (i = 0; i < count; ++i) #endif { SHA_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, (unsigned char*)global_salt, SALT_LENGTH-1); SHA1_Update(&ctx, saved_key[i], key_len[i]); SHA1_Final((unsigned char*)crypt_out[i], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if ( ((uint32_t*)binary)[0] == crypt_out[index][0] ) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_LENGTH); } static int cmp_exact(char *source, int index) { return 1; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int salt_hash(void *salt) { return *(uint32_t*)salt & (SALT_HASH_SIZE - 1); } // Define john integration struct fmt_main fmt_EPI = { { // fmt_params "EPI", "EPiServer SID", "SHA1 32/" ARCH_BITS_STR, "", // benchmark comment 0, // benchmark length 0, PLAINTEXT_LENGTH, BINARY_LENGTH, BINARY_ALIGN, SALT_LENGTH, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { NULL }, { NULL }, global_tests }, { // fmt_methods init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
LJFunctor.h
/** * @file LJFunctor.h * * @date 17 Jan 2018 * @author tchipevn */ #pragma once #include <array> #include "ParticlePropertiesLibrary.h" #include "autopas/iterators/SingleCellIterator.h" #include "autopas/pairwiseFunctors/Functor.h" #include "autopas/utils/AlignedAllocator.h" #include "autopas/utils/ArrayMath.h" #include "autopas/utils/WrapOpenMP.h" #include "autopas/utils/inBox.h" #if defined(AUTOPAS_CUDA) #include "autopas/molecularDynamics/LJFunctorCuda.cuh" #include "autopas/molecularDynamics/LJFunctorCudaGlobals.cuh" #include "autopas/utils/CudaDeviceVector.h" #include "autopas/utils/CudaStreamHandler.h" #else #include "autopas/utils/ExceptionHandler.h" #endif namespace autopas { /** * A functor to handle lennard-jones interactions between two particles (molecules). * @tparam Particle The type of particle. * @tparam ParticleCell The type of particlecell. * @tparam applyShift Switch for the lj potential to be truncated shifted. * @tparam useMixing Switch for the functor to be used with multiple particle types. * If set to false, _epsilon and _sigma need to be set and the constructor with PPL can be omitted. * @tparam useNewton3 Switch for the functor to support newton3 on, off or both. See FunctorN3Modes for possible values. * @tparam calculateGlobals Defines whether the global values are to be calculated (energy, virial). * @tparam relevantForTuning Whether or not the auto-tuner should consider this functor. */ template <class Particle, class ParticleCell, bool applyShift = false, bool useMixing = false, FunctorN3Modes useNewton3 = FunctorN3Modes::Both, bool calculateGlobals = false, bool relevantForTuning = true> class LJFunctor : public Functor< Particle, ParticleCell, typename Particle::SoAArraysType, LJFunctor<Particle, ParticleCell, applyShift, useMixing, useNewton3, calculateGlobals, relevantForTuning>> { using SoAArraysType = typename Particle::SoAArraysType; using SoAFloatPrecision = typename Particle::ParticleSoAFloatPrecision; public: /** * Deleted default constructor */ LJFunctor() = delete; private: /** * Internal, actual constructor. * @param cutoff * @param duplicatedCalculation Defines whether duplicated calculations are happening across processes / over the * simulation boundary. e.g. eightShell: false, fullShell: true. * @param dummy unused, only there to make the signature different from the public constructor. */ explicit LJFunctor(double cutoff, bool duplicatedCalculation, void * /*dummy*/) : Functor< Particle, ParticleCell, SoAArraysType, LJFunctor<Particle, ParticleCell, applyShift, useMixing, useNewton3, calculateGlobals, relevantForTuning>>( cutoff), _cutoffsquare{cutoff * cutoff}, _upotSum{0.}, _virialSum{0., 0., 0.}, _aosThreadData(), _duplicatedCalculations{duplicatedCalculation}, _postProcessed{false} { if constexpr (calculateGlobals) { _aosThreadData.resize(autopas_get_max_threads()); } } public: /** * Constructor for Functor with mixing disabled. When using this functor it is necessary to call * setParticleProperties() to set internal constants because it does not use a particle properties library. * * @note Only to be used with mixing == false. * * @param cutoff * @param duplicatedCalculation Defines whether duplicated calculations are happening across processes / over the * simulation boundary. e.g. eightShell: false, fullShell: true. */ explicit LJFunctor(double cutoff, bool duplicatedCalculation = true) : LJFunctor(cutoff, duplicatedCalculation, nullptr) { static_assert(not useMixing, "Mixing without a ParticlePropertiesLibrary is not possible! Use a different constructor or set " "mixing to false."); } /** * Constructor for Functor with mixing active. This functor takes a ParticlePropertiesLibrary to look up (mixed) * properties like sigma, epsilon and shift. * @param cutoff * @param particlePropertiesLibrary * @param duplicatedCalculation Defines whether duplicated calculations are happening across processes / over the * simulation boundary. e.g. eightShell: false, fullShell: true. */ explicit LJFunctor(double cutoff, ParticlePropertiesLibrary<double, size_t> &particlePropertiesLibrary, bool duplicatedCalculation = true) : LJFunctor(cutoff, duplicatedCalculation, nullptr) { static_assert(useMixing, "Not using Mixing but using a ParticlePropertiesLibrary is not allowed! Use a different constructor " "or set mixing to true."); _PPLibrary = &particlePropertiesLibrary; } bool isRelevantForTuning() override { return relevantForTuning; } bool allowsNewton3() override { return useNewton3 == FunctorN3Modes::Newton3Only or useNewton3 == FunctorN3Modes::Both; } bool allowsNonNewton3() override { return useNewton3 == FunctorN3Modes::Newton3Off or useNewton3 == FunctorN3Modes::Both; } bool isAppropriateClusterSize(unsigned int clusterSize, DataLayoutOption::Value dataLayout) const override { if (dataLayout == DataLayoutOption::cuda) { #if defined(AUTOPAS_CUDA) return _cudawrapper.isAppropriateClusterSize(clusterSize); #endif return false; } else { return dataLayout == DataLayoutOption::aos; // LJFunctor does not yet support soa for clusters. // The reason for this is that the owned state is not handled correctly, see #396. } } void AoSFunctor(Particle &i, Particle &j, bool newton3) override { auto sigmasquare = _sigmasquare; auto epsilon24 = _epsilon24; auto shift6 = _shift6; if constexpr (useMixing) { sigmasquare = _PPLibrary->mixingSigmaSquare(i.getTypeId(), j.getTypeId()); epsilon24 = _PPLibrary->mixing24Epsilon(i.getTypeId(), j.getTypeId()); if constexpr (applyShift) { shift6 = _PPLibrary->mixingShift6(i.getTypeId(), j.getTypeId()); } } auto dr = utils::ArrayMath::sub(i.getR(), j.getR()); double dr2 = utils::ArrayMath::dot(dr, dr); if (dr2 > _cutoffsquare) return; double invdr2 = 1. / dr2; double lj6 = sigmasquare * invdr2; lj6 = lj6 * lj6 * lj6; double lj12 = lj6 * lj6; double lj12m6 = lj12 - lj6; double fac = epsilon24 * (lj12 + lj12m6) * invdr2; auto f = utils::ArrayMath::mulScalar(dr, fac); i.addF(f); if (newton3) { // only if we use newton 3 here, we want to j.subF(f); } if (calculateGlobals) { auto virial = utils::ArrayMath::mul(dr, f); double upot = epsilon24 * lj12m6 + shift6; const int threadnum = autopas_get_thread_num(); if (_duplicatedCalculations) { // for non-newton3 the division is in the post-processing step. if (newton3) { upot *= 0.5; virial = utils::ArrayMath::mulScalar(virial, (double)0.5); } if (i.isOwned()) { _aosThreadData[threadnum].upotSum += upot; _aosThreadData[threadnum].virialSum = utils::ArrayMath::add(_aosThreadData[threadnum].virialSum, virial); } // for non-newton3 the second particle will be considered in a separate calculation if (newton3 and j.isOwned()) { _aosThreadData[threadnum].upotSum += upot; _aosThreadData[threadnum].virialSum = utils::ArrayMath::add(_aosThreadData[threadnum].virialSum, virial); } } else { // for non-newton3 we divide by 2 only in the postprocess step! _aosThreadData[threadnum].upotSum += upot; _aosThreadData[threadnum].virialSum = utils::ArrayMath::add(_aosThreadData[threadnum].virialSum, virial); } } } /** * @copydoc Functor::SoAFunctor(SoAView<SoAArraysType> soa, bool newton3) * This functor ignores will use a newton3 like traversing of the soa, however, it still needs to know about newton3 * to use it correctly for the global values. */ void SoAFunctor(SoAView<SoAArraysType> soa, bool newton3) override { if (soa.getNumParticles() == 0) return; const auto *const __restrict__ xptr = soa.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict__ yptr = soa.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict__ zptr = soa.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict__ ownedPtr = soa.template begin<Particle::AttributeNames::owned>(); SoAFloatPrecision *const __restrict__ fxptr = soa.template begin<Particle::AttributeNames::forceX>(); SoAFloatPrecision *const __restrict__ fyptr = soa.template begin<Particle::AttributeNames::forceY>(); SoAFloatPrecision *const __restrict__ fzptr = soa.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict__ typeptr = soa.template begin<Particle::AttributeNames::typeId>(); // the local redeclaration of the following values helps the SoAFloatPrecision-generation of various compilers. const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision shift6 = _shift6; SoAFloatPrecision sigmasquare = _sigmasquare; SoAFloatPrecision epsilon24 = _epsilon24; if (calculateGlobals) { // Checks if the cell is a halo cell, if it is, we skip it. bool isHaloCell = ownedPtr[0] ? false : true; if (isHaloCell) { return; } } SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; for (unsigned int i = 0; i < soa.getNumParticles(); ++i) { SoAFloatPrecision fxacc = 0.; SoAFloatPrecision fyacc = 0.; SoAFloatPrecision fzacc = 0.; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> sigmaSquares; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> epsilon24s; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> shift6s; if constexpr (useMixing) { // preload all sigma and epsilons for next vectorized region sigmaSquares.resize(soa.getNumParticles()); epsilon24s.resize(soa.getNumParticles()); // if no mixing or mixing but no shift shift6 is constant therefore we do not need this vector. if constexpr (applyShift) { shift6s.resize(soa.getNumParticles()); } for (unsigned int j = 0; j < soa.getNumParticles(); ++j) { sigmaSquares[j] = _PPLibrary->mixingSigmaSquare(typeptr[i], typeptr[j]); epsilon24s[j] = _PPLibrary->mixing24Epsilon(typeptr[i], typeptr[j]); if constexpr (applyShift) { shift6s[j] = _PPLibrary->mixingShift6(typeptr[i], typeptr[j]); } } } // icpc vectorizes this. // g++ only with -ffast-math or -funsafe-math-optimizations #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) for (unsigned int j = i + 1; j < soa.getNumParticles(); ++j) { if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } const SoAFloatPrecision drx = xptr[i] - xptr[j]; const SoAFloatPrecision dry = yptr[i] - yptr[j]; const SoAFloatPrecision drz = zptr[i] - zptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; const SoAFloatPrecision mask = (dr2 > cutoffsquare) ? 0. : 1.; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = epsilon24 * (lj12 + lj12m6) * invdr2 * mask; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; // newton 3 fxptr[j] -= fx; fyptr[j] -= fy; fzptr[j] -= fz; if (calculateGlobals) { const SoAFloatPrecision virialx = drx * fx; const SoAFloatPrecision virialy = dry * fy; const SoAFloatPrecision virialz = drz * fz; const SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6) * mask; // these calculations assume that this functor is not called for halo cells! upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } } fxptr[i] += fxacc; fyptr[i] += fyacc; fzptr[i] += fzacc; } if (calculateGlobals) { const int threadnum = autopas_get_thread_num(); // we assume newton3 to be enabled in this functor call, thus we multiply by two if the value of newton3 is false, // since for newton3 disabled we divide by two later on. _aosThreadData[threadnum].upotSum += upotSum * (newton3 ? 1. : 2.); _aosThreadData[threadnum].virialSum[0] += virialSumX * (newton3 ? 1. : 2.); _aosThreadData[threadnum].virialSum[1] += virialSumY * (newton3 ? 1. : 2.); _aosThreadData[threadnum].virialSum[2] += virialSumZ * (newton3 ? 1. : 2.); } } /** * @copydoc Functor::SoAFunctor(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, bool newton3) */ void SoAFunctor(SoAView<SoAArraysType> soa1, SoAView<SoAArraysType> soa2, const bool newton3) override { if (soa1.getNumParticles() == 0 || soa2.getNumParticles() == 0) return; const auto *const __restrict__ x1ptr = soa1.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict__ y1ptr = soa1.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict__ z1ptr = soa1.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict__ x2ptr = soa2.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict__ y2ptr = soa2.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict__ z2ptr = soa2.template begin<Particle::AttributeNames::posZ>(); const auto *const __restrict__ ownedPtr1 = soa1.template begin<Particle::AttributeNames::owned>(); const auto *const __restrict__ ownedPtr2 = soa2.template begin<Particle::AttributeNames::owned>(); auto *const __restrict__ fx1ptr = soa1.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict__ fy1ptr = soa1.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict__ fz1ptr = soa1.template begin<Particle::AttributeNames::forceZ>(); auto *const __restrict__ fx2ptr = soa2.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict__ fy2ptr = soa2.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict__ fz2ptr = soa2.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict__ typeptr1 = soa1.template begin<Particle::AttributeNames::typeId>(); [[maybe_unused]] auto *const __restrict__ typeptr2 = soa2.template begin<Particle::AttributeNames::typeId>(); bool isHaloCell1 = false; bool isHaloCell2 = false; // Checks whether the cells are halo cells. if (calculateGlobals) { isHaloCell1 = ownedPtr1[0] ? false : true; isHaloCell2 = ownedPtr2[0] ? false : true; // This if is commented out because the AoS vs SoA test would fail otherwise. Even though it is physically // correct! /*if(_duplicatedCalculations and isHaloCell1 and isHaloCell2){ return; }*/ } SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision shift6 = _shift6; SoAFloatPrecision sigmasquare = _sigmasquare; SoAFloatPrecision epsilon24 = _epsilon24; for (unsigned int i = 0; i < soa1.getNumParticles(); ++i) { SoAFloatPrecision fxacc = 0; SoAFloatPrecision fyacc = 0; SoAFloatPrecision fzacc = 0; // preload all sigma and epsilons for next vectorized region std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> sigmaSquares; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> epsilon24s; std::vector<SoAFloatPrecision, AlignedAllocator<SoAFloatPrecision>> shift6s; if constexpr (useMixing) { sigmaSquares.resize(soa2.getNumParticles()); epsilon24s.resize(soa2.getNumParticles()); // if no mixing or mixing but no shift shift6 is constant therefore we do not need this vector. if constexpr (applyShift) { shift6s.resize(soa2.getNumParticles()); } for (unsigned int j = 0; j < soa2.getNumParticles(); ++j) { sigmaSquares[j] = _PPLibrary->mixingSigmaSquare(typeptr1[i], typeptr2[j]); epsilon24s[j] = _PPLibrary->mixing24Epsilon(typeptr1[i], typeptr2[j]); if constexpr (applyShift) { shift6s[j] = _PPLibrary->mixingShift6(typeptr1[i], typeptr2[j]); } } } // icpc vectorizes this. // g++ only with -ffast-math or -funsafe-math-optimizations #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) for (unsigned int j = 0; j < soa2.getNumParticles(); ++j) { if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } const SoAFloatPrecision drx = x1ptr[i] - x2ptr[j]; const SoAFloatPrecision dry = y1ptr[i] - y2ptr[j]; const SoAFloatPrecision drz = z1ptr[i] - z2ptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; const SoAFloatPrecision mask = (dr2 > cutoffsquare) ? 0. : 1.; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = epsilon24 * (lj12 + lj12m6) * invdr2 * mask; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fx2ptr[j] -= fx; fy2ptr[j] -= fy; fz2ptr[j] -= fz; } if (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6) * mask; upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } } fx1ptr[i] += fxacc; fy1ptr[i] += fyacc; fz1ptr[i] += fzacc; } if (calculateGlobals) { SoAFloatPrecision energyfactor = 1.; if (_duplicatedCalculations) { // if we have duplicated calculations, i.e., we calculate interactions multiple times, we have to take care // that we do not add the energy multiple times! energyfactor = isHaloCell1 ? 0. : 1.; if (newton3) { energyfactor += isHaloCell2 ? 0. : 1.; energyfactor *= 0.5; // we count the energies partly to one of the two cells! } } const int threadnum = autopas_get_thread_num(); _aosThreadData[threadnum].upotSum += upotSum * energyfactor; _aosThreadData[threadnum].virialSum[0] += virialSumX * energyfactor; _aosThreadData[threadnum].virialSum[1] += virialSumY * energyfactor; _aosThreadData[threadnum].virialSum[2] += virialSumZ * energyfactor; } } // clang-format off /** * @copydoc Functor::SoAFunctor(SoAView<SoAArraysType> soa, const std::vector<std::vector<size_t, autopas::AlignedAllocator<size_t>>> &neighborList, size_t iFrom, size_t iTo, bool newton3) * @note If you want to parallelize this by openmp, please ensure that there * are no dependencies, i.e. introduce colors and specify iFrom and iTo accordingly. */ // clang-format on void SoAFunctor(SoAView<SoAArraysType> soa, const std::vector<std::vector<size_t, autopas::AlignedAllocator<size_t>>> &neighborList, size_t iFrom, size_t iTo, const bool newton3) override { if (newton3) { if (_duplicatedCalculations) { SoAFunctorImpl<true, true>(soa, neighborList, iFrom, iTo); } else { SoAFunctorImpl<true, false>(soa, neighborList, iFrom, iTo); } } else { if (_duplicatedCalculations) { SoAFunctorImpl<false, true>(soa, neighborList, iFrom, iTo); } else { SoAFunctorImpl<false, false>(soa, neighborList, iFrom, iTo); } } } /** * @brief Functor using Cuda on SoA in device Memory * * This Functor calculates the pair-wise interactions between particles in the device_handle on the GPU * * @param device_handle soa in device memory * @param newton3 defines whether or whether not to use newton */ void CudaFunctor(CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle, bool newton3) override { #if defined(AUTOPAS_CUDA) const size_t size = device_handle.template get<Particle::AttributeNames::posX>().size(); if (size == 0) { return; } auto cudaSoA = this->createFunctorCudaSoA(device_handle); if (newton3) { _cudawrapper.SoAFunctorN3Wrapper(cudaSoA.get(), 0); } else { _cudawrapper.SoAFunctorNoN3Wrapper(cudaSoA.get(), 0); } #else utils::ExceptionHandler::exception("LJFunctor::CudaFunctor: AutoPas was compiled without CUDA support!"); #endif } /** * Sets the particle properties constants for this functor. * * This is only necessary if no particlePropertiesLibrary is used. * If compiled with CUDA this function also loads the values to the GPU. * * @param epsilon24 * @param sigmaSquare */ void setParticleProperties(SoAFloatPrecision epsilon24, SoAFloatPrecision sigmaSquare) { _epsilon24 = epsilon24; _sigmasquare = sigmaSquare; if (applyShift) { _shift6 = ParticlePropertiesLibrary<double, size_t>::calcShift6(_epsilon24, _sigmasquare, _cutoffsquare); } else { _shift6 = 0.; } #if defined(AUTOPAS_CUDA) LJFunctorConstants<SoAFloatPrecision> constants(_cutoffsquare, _epsilon24 /* epsilon24 */, _sigmasquare /* sigmasquare */, _shift6); _cudawrapper.loadConstants(&constants); #endif } /** * @brief Functor using Cuda on SoAs in device Memory * * This Functor calculates the pair-wise interactions between particles in the device_handle1 and device_handle2 on * the GPU * * @param device_handle1 first soa in device memory * @param device_handle2 second soa in device memory * @param newton3 defines whether or whether not to use newton */ void CudaFunctor(CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle1, CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle2, bool newton3) override { #if defined(AUTOPAS_CUDA) const size_t size1 = device_handle1.template get<Particle::AttributeNames::posX>().size(); const size_t size2 = device_handle2.template get<Particle::AttributeNames::posX>().size(); if ((size1 == 0) or (size2 == 0)) { return; } auto cudaSoA1 = this->createFunctorCudaSoA(device_handle1); auto cudaSoA2 = this->createFunctorCudaSoA(device_handle2); if (newton3) { if (size1 > size2) { _cudawrapper.SoAFunctorN3PairWrapper(cudaSoA1.get(), cudaSoA2.get(), 0); } else { _cudawrapper.SoAFunctorN3PairWrapper(cudaSoA2.get(), cudaSoA1.get(), 0); } } else { _cudawrapper.SoAFunctorNoN3PairWrapper(cudaSoA1.get(), cudaSoA2.get(), 0); } #else utils::ExceptionHandler::exception("AutoPas was compiled without CUDA support!"); #endif } #if defined(AUTOPAS_CUDA) CudaWrapperInterface<SoAFloatPrecision> *getCudaWrapper() override { return &_cudawrapper; } std::unique_ptr<FunctorCudaSoA<SoAFloatPrecision>> createFunctorCudaSoA( CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle) override { if (calculateGlobals) { return std::make_unique<LJFunctorCudaGlobalsSoA<SoAFloatPrecision>>( device_handle.template get<Particle::AttributeNames::posX>().size(), device_handle.template get<Particle::AttributeNames::posX>().get(), device_handle.template get<Particle::AttributeNames::posY>().get(), device_handle.template get<Particle::AttributeNames::posZ>().get(), device_handle.template get<Particle::AttributeNames::forceX>().get(), device_handle.template get<Particle::AttributeNames::forceY>().get(), device_handle.template get<Particle::AttributeNames::forceZ>().get(), device_handle.template get<Particle::AttributeNames::owned>().get(), _cudaGlobals.get()); } else { return std::make_unique<LJFunctorCudaSoA<SoAFloatPrecision>>( device_handle.template get<Particle::AttributeNames::posX>().size(), device_handle.template get<Particle::AttributeNames::posX>().get(), device_handle.template get<Particle::AttributeNames::posY>().get(), device_handle.template get<Particle::AttributeNames::posZ>().get(), device_handle.template get<Particle::AttributeNames::forceX>().get(), device_handle.template get<Particle::AttributeNames::forceY>().get(), device_handle.template get<Particle::AttributeNames::forceZ>().get()); } } #endif /** * @copydoc Functor::deviceSoALoader */ void deviceSoALoader(::autopas::SoA<SoAArraysType> &soa, CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle) override { #if defined(AUTOPAS_CUDA) const size_t size = soa.getNumParticles(); if (size == 0) return; device_handle.template get<Particle::AttributeNames::posX>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::posX>()); device_handle.template get<Particle::AttributeNames::posY>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::posY>()); device_handle.template get<Particle::AttributeNames::posZ>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::posZ>()); device_handle.template get<Particle::AttributeNames::forceX>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::forceX>()); device_handle.template get<Particle::AttributeNames::forceY>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::forceY>()); device_handle.template get<Particle::AttributeNames::forceZ>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::forceZ>()); if (calculateGlobals) { device_handle.template get<Particle::AttributeNames::owned>().copyHostToDevice( size, soa.template begin<Particle::AttributeNames::owned>()); } #else utils::ExceptionHandler::exception("LJFunctor::deviceSoALoader: AutoPas was compiled without CUDA support!"); #endif } /** * @copydoc Functor::deviceSoAExtractor */ void deviceSoAExtractor(::autopas::SoA<SoAArraysType> &soa, CudaSoA<typename Particle::CudaDeviceArraysType> &device_handle) override { #if defined(AUTOPAS_CUDA) const size_t size = soa.getNumParticles(); if (size == 0) return; device_handle.template get<Particle::AttributeNames::forceX>().copyDeviceToHost( size, soa.template begin<Particle::AttributeNames::forceX>()); device_handle.template get<Particle::AttributeNames::forceY>().copyDeviceToHost( size, soa.template begin<Particle::AttributeNames::forceY>()); device_handle.template get<Particle::AttributeNames::forceZ>().copyDeviceToHost( size, soa.template begin<Particle::AttributeNames::forceZ>()); #else utils::ExceptionHandler::exception("LJFunctor::deviceSoAExtractor: AutoPas was compiled without CUDA support!"); #endif } /** * @copydoc Functor::getNeededAttr() */ constexpr static const auto getNeededAttr() { return std::array<typename Particle::AttributeNames, 9>{ Particle::AttributeNames::id, Particle::AttributeNames::posX, Particle::AttributeNames::posY, Particle::AttributeNames::posZ, Particle::AttributeNames::forceX, Particle::AttributeNames::forceY, Particle::AttributeNames::forceZ, Particle::AttributeNames::typeId, Particle::AttributeNames::owned}; } /** * @copydoc Functor::getNeededAttr(std::false_type) */ constexpr static const auto getNeededAttr(std::false_type) { return std::array<typename Particle::AttributeNames, 6>{ Particle::AttributeNames::id, Particle::AttributeNames::posX, Particle::AttributeNames::posY, Particle::AttributeNames::posZ, Particle::AttributeNames::typeId, Particle::AttributeNames::owned}; } /** * @copydoc Functor::getComputedAttr() */ constexpr static const auto getComputedAttr() { return std::array<typename Particle::AttributeNames, 3>{ Particle::AttributeNames::forceX, Particle::AttributeNames::forceY, Particle::AttributeNames::forceZ}; } /** * Get the number of flops used per kernel call. This should count the * floating point operations needed for two particles that lie within a cutoff * radius. * @return the number of floating point operations */ static unsigned long getNumFlopsPerKernelCall() { // Kernel: 12 = 1 (inverse R squared) + 8 (compute scale) + 3 (apply // scale) sum Forces: 6 (forces) kernel total = 12 + 6 = 18 return 18ul; } /** * Reset the global values. * Will set the global values to zero to prepare for the next iteration. */ void initTraversal() override { _upotSum = 0.; _virialSum = {0., 0., 0.}; _postProcessed = false; for (size_t i = 0; i < _aosThreadData.size(); ++i) { _aosThreadData[i].setZero(); } #if defined(AUTOPAS_CUDA) if (calculateGlobals) { std::array<SoAFloatPrecision, 4> globals{0, 0, 0, 0}; _cudaGlobals.copyHostToDevice(4, globals.data()); } #endif } /** * Postprocesses global values, e.g. upot and virial * @param newton3 */ void endTraversal(bool newton3) override { if (_postProcessed) { throw utils::ExceptionHandler::AutoPasException( "Already postprocessed, endTraversal(bool newton3) was called twice without calling initTraversal()."); } if (calculateGlobals) { #if defined(AUTOPAS_CUDA) std::array<SoAFloatPrecision, 4> globals{0, 0, 0, 0}; _cudaGlobals.copyDeviceToHost(4, globals.data()); _virialSum[0] += globals[0]; _virialSum[1] += globals[1]; _virialSum[2] += globals[2]; _upotSum += globals[3]; #endif for (size_t i = 0; i < _aosThreadData.size(); ++i) { _upotSum += _aosThreadData[i].upotSum; _virialSum = utils::ArrayMath::add(_virialSum, _aosThreadData[i].virialSum); } if (not newton3) { // if the newton3 optimization is disabled we have added every energy contribution twice, so we divide by 2 // here. _upotSum *= 0.5; _virialSum = utils::ArrayMath::mulScalar(_virialSum, 0.5); } // we have always calculated 6*upot, so we divide by 6 here! _upotSum /= 6.; _postProcessed = true; } } /** * Get the potential Energy. * @return the potential Energy */ double getUpot() { if (not calculateGlobals) { throw utils::ExceptionHandler::AutoPasException( "Trying to get upot even though calculateGlobals is false. If you want this functor to calculate global " "values, please specify calculateGlobals to be true."); } if (not _postProcessed) { throw utils::ExceptionHandler::AutoPasException("Cannot get upot, because endTraversal was not called."); } return _upotSum; } /** * Get the virial. * @return */ double getVirial() { if (not calculateGlobals) { throw utils::ExceptionHandler::AutoPasException( "Trying to get virial even though calculateGlobals is false. If you want this functor to calculate global " "values, please specify calculateGlobals to be true."); } if (not _postProcessed) { throw utils::ExceptionHandler::AutoPasException("Cannot get virial, because endTraversal was not called."); } return _virialSum[0] + _virialSum[1] + _virialSum[2]; } /** * Getter for 24*epsilon. * @return 24*epsilon */ SoAFloatPrecision getEpsilon24() const { return _epsilon24; } /** * Getter for the squared sigma. * @return squared sigma. */ SoAFloatPrecision getSigmaSquare() const { return _sigmasquare; } private: template <bool newton3, bool duplicatedCalculations> void SoAFunctorImpl(SoAView<SoAArraysType> &soa, const std::vector<std::vector<size_t, autopas::AlignedAllocator<size_t>>> &neighborList, size_t iFrom, size_t iTo) { if (soa.getNumParticles() == 0) return; const auto *const __restrict__ xptr = soa.template begin<Particle::AttributeNames::posX>(); const auto *const __restrict__ yptr = soa.template begin<Particle::AttributeNames::posY>(); const auto *const __restrict__ zptr = soa.template begin<Particle::AttributeNames::posZ>(); auto *const __restrict__ fxptr = soa.template begin<Particle::AttributeNames::forceX>(); auto *const __restrict__ fyptr = soa.template begin<Particle::AttributeNames::forceY>(); auto *const __restrict__ fzptr = soa.template begin<Particle::AttributeNames::forceZ>(); [[maybe_unused]] auto *const __restrict__ typeptr1 = soa.template begin<Particle::AttributeNames::typeId>(); [[maybe_unused]] auto *const __restrict__ typeptr2 = soa.template begin<Particle::AttributeNames::typeId>(); const auto *const __restrict__ ownedPtr = soa.template begin<Particle::AttributeNames::owned>(); const SoAFloatPrecision cutoffsquare = _cutoffsquare; SoAFloatPrecision shift6 = _shift6; SoAFloatPrecision sigmasquare = _sigmasquare; SoAFloatPrecision epsilon24 = _epsilon24; SoAFloatPrecision upotSum = 0.; SoAFloatPrecision virialSumX = 0.; SoAFloatPrecision virialSumY = 0.; SoAFloatPrecision virialSumZ = 0.; for (size_t i = iFrom; i < iTo; ++i) { SoAFloatPrecision fxacc = 0; SoAFloatPrecision fyacc = 0; SoAFloatPrecision fzacc = 0; const size_t listSizeI = neighborList[i].size(); const size_t *const __restrict__ currentList = neighborList[i].data(); // checks whether particle 1 is in the domain box, unused if _duplicatedCalculations is false! SoAFloatPrecision inbox1Mul = 0.; if (duplicatedCalculations) { // only for duplicated calculations we need this value inbox1Mul = ownedPtr[i]; if (newton3) { inbox1Mul *= 0.5; } } // this is a magic number, that should correspond to at least // vectorization width*N have testet multiple sizes: // 4: does not give a speedup, slower than original AoSFunctor // 8: small speedup compared to AoS // 12: highest speedup compared to Aos // 16: smaller speedup // in theory this is a variable, we could auto-tune over... #ifdef __AVX512F__ // use a multiple of 8 for avx constexpr size_t vecsize = 16; #else // for everything else 12 is faster constexpr size_t vecsize = 12; #endif size_t joff = 0; // if the size of the verlet list is larger than the given size vecsize, // we will use a vectorized version. if (listSizeI >= vecsize) { alignas(64) std::array<SoAFloatPrecision, vecsize> xtmp, ytmp, ztmp, xArr, yArr, zArr, fxArr, fyArr, fzArr, ownedArr; // broadcast of the position of particle i for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { xtmp[tmpj] = xptr[i]; ytmp[tmpj] = yptr[i]; ztmp[tmpj] = zptr[i]; } // loop over the verlet list from 0 to x*vecsize for (; joff < listSizeI - vecsize + 1; joff += vecsize) { // in each iteration we calculate the interactions of particle i with // vecsize particles in the neighborlist of particle i starting at // particle joff [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> sigmaSquares; [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> epsilon24s; [[maybe_unused]] alignas(DEFAULT_CACHE_LINE_SIZE) std::array<SoAFloatPrecision, vecsize> shift6s; if constexpr (useMixing) { for (size_t j = 0; j < vecsize; j++) { sigmaSquares[j] = _PPLibrary->mixingSigmaSquare(typeptr1[i], typeptr2[currentList[joff + j]]); epsilon24s[j] = _PPLibrary->mixing24Epsilon(typeptr1[i], typeptr2[currentList[joff + j]]); if constexpr (applyShift) { shift6s[j] = _PPLibrary->mixingShift6(typeptr1[i], typeptr2[currentList[joff + j]]); } } } // gather position of particle j #pragma omp simd safelen(vecsize) for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { xArr[tmpj] = xptr[currentList[joff + tmpj]]; yArr[tmpj] = yptr[currentList[joff + tmpj]]; zArr[tmpj] = zptr[currentList[joff + tmpj]]; ownedArr[tmpj] = ownedPtr[currentList[joff + tmpj]]; } // do omp simd with reduction of the interaction #pragma omp simd reduction(+ : fxacc, fyacc, fzacc, upotSum, virialSumX, virialSumY, virialSumZ) safelen(vecsize) for (size_t j = 0; j < vecsize; j++) { if constexpr (useMixing) { sigmasquare = sigmaSquares[j]; epsilon24 = epsilon24s[j]; if constexpr (applyShift) { shift6 = shift6s[j]; } } // const size_t j = currentList[jNeighIndex]; const SoAFloatPrecision drx = xtmp[j] - xArr[j]; const SoAFloatPrecision dry = ytmp[j] - yArr[j]; const SoAFloatPrecision drz = ztmp[j] - zArr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; const SoAFloatPrecision mask = (dr2 <= cutoffsquare) ? 1. : 0.; const SoAFloatPrecision invdr2 = 1. / dr2 * mask; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = epsilon24 * (lj12 + lj12m6) * invdr2; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fxArr[j] = fx; fyArr[j] = fy; fzArr[j] = fz; } if (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6) * mask; if (duplicatedCalculations) { // for non-newton3 the division is in the post-processing step. SoAFloatPrecision inboxMul = inbox1Mul + (newton3 ? ownedArr[j] * .5 : 0.); upotSum += upot * inboxMul; virialSumX += virialx * inboxMul; virialSumY += virialy * inboxMul; virialSumZ += virialz * inboxMul; } else { // for non-newton3 we divide by 2 only in the postprocess step! upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } } } // scatter the forces to where they belong, this is only needed for newton3 if (newton3) { #pragma omp simd safelen(vecsize) for (size_t tmpj = 0; tmpj < vecsize; tmpj++) { const size_t j = currentList[joff + tmpj]; fxptr[j] -= fxArr[tmpj]; fyptr[j] -= fyArr[tmpj]; fzptr[j] -= fzArr[tmpj]; } } } } // this loop goes over the remainder and uses no optimizations for (size_t jNeighIndex = joff; jNeighIndex < listSizeI; ++jNeighIndex) { size_t j = neighborList[i][jNeighIndex]; if (i == j) continue; if constexpr (useMixing) { sigmasquare = _PPLibrary->mixingSigmaSquare(typeptr1[i], typeptr2[j]); epsilon24 = _PPLibrary->mixing24Epsilon(typeptr1[i], typeptr2[j]); if constexpr (applyShift) { shift6 = _PPLibrary->mixingShift6(typeptr1[i], typeptr2[j]); } } const SoAFloatPrecision drx = xptr[i] - xptr[j]; const SoAFloatPrecision dry = yptr[i] - yptr[j]; const SoAFloatPrecision drz = zptr[i] - zptr[j]; const SoAFloatPrecision drx2 = drx * drx; const SoAFloatPrecision dry2 = dry * dry; const SoAFloatPrecision drz2 = drz * drz; const SoAFloatPrecision dr2 = drx2 + dry2 + drz2; if (dr2 > cutoffsquare) continue; const SoAFloatPrecision invdr2 = 1. / dr2; const SoAFloatPrecision lj2 = sigmasquare * invdr2; const SoAFloatPrecision lj6 = lj2 * lj2 * lj2; const SoAFloatPrecision lj12 = lj6 * lj6; const SoAFloatPrecision lj12m6 = lj12 - lj6; const SoAFloatPrecision fac = epsilon24 * (lj12 + lj12m6) * invdr2; const SoAFloatPrecision fx = drx * fac; const SoAFloatPrecision fy = dry * fac; const SoAFloatPrecision fz = drz * fac; fxacc += fx; fyacc += fy; fzacc += fz; if (newton3) { fxptr[j] -= fx; fyptr[j] -= fy; fzptr[j] -= fz; } if (calculateGlobals) { SoAFloatPrecision virialx = drx * fx; SoAFloatPrecision virialy = dry * fy; SoAFloatPrecision virialz = drz * fz; SoAFloatPrecision upot = (epsilon24 * lj12m6 + shift6); if (duplicatedCalculations) { // for non-newton3 the division is in the post-processing step. if (newton3) { upot *= 0.5; virialx *= 0.5; virialy *= 0.5; virialz *= 0.5; } if (inbox1Mul) { upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } // for non-newton3 the second particle will be considered in a separate calculation if (newton3 and ownedPtr[j]) { upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } } else { // for non-newton3 we divide by 2 only in the postprocess step! upotSum += upot; virialSumX += virialx; virialSumY += virialy; virialSumZ += virialz; } } } if (fxacc != 0 or fyacc != 0 or fzacc != 0) { fxptr[i] += fxacc; fyptr[i] += fyacc; fzptr[i] += fzacc; } } if (calculateGlobals) { const int threadnum = autopas_get_thread_num(); _aosThreadData[threadnum].upotSum += upotSum; _aosThreadData[threadnum].virialSum[0] += virialSumX; _aosThreadData[threadnum].virialSum[1] += virialSumY; _aosThreadData[threadnum].virialSum[2] += virialSumZ; } } /** * This class stores internal data of each thread, make sure that this data has proper size, i.e. k*64 Bytes! */ class AoSThreadData { public: AoSThreadData() : virialSum{0., 0., 0.}, upotSum{0.}, __remainingTo64{} {} void setZero() { virialSum = {0., 0., 0.}; upotSum = 0.; } // variables std::array<double, 3> virialSum; double upotSum; private: // dummy parameter to get the right size (64 bytes) double __remainingTo64[(64 - 4 * sizeof(double)) / sizeof(double)]; }; // make sure of the size of AoSThreadData static_assert(sizeof(AoSThreadData) % 64 == 0, "AoSThreadData has wrong size"); const double _cutoffsquare; // not const because they might be reset through PPL double _epsilon24, _sigmasquare, _shift6 = 0; ParticlePropertiesLibrary<SoAFloatPrecision, size_t> *_PPLibrary = nullptr; // sum of the potential energy, only calculated if calculateGlobals is true double _upotSum; // sum of the virial, only calculated if calculateGlobals is true std::array<double, 3> _virialSum; // thread buffer for aos std::vector<AoSThreadData> _aosThreadData; // bool that defines whether duplicate calculations are happening bool _duplicatedCalculations; // defines whether or whether not the global values are already preprocessed bool _postProcessed; #if defined(AUTOPAS_CUDA) using CudaWrapperType = typename std::conditional<calculateGlobals, LJFunctorCudaGlobalsWrapper<SoAFloatPrecision>, LJFunctorCudaWrapper<SoAFloatPrecision>>::type; // contains wrapper functions for cuda calls CudaWrapperType _cudawrapper; // contains device globals utils::CudaDeviceVector<SoAFloatPrecision> _cudaGlobals; #endif }; // class LJFunctor } // namespace autopas
core_sttmqr.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/core_blas/core_zttmqr.c, normal z -> s, Fri Sep 28 17:38:25 2018 * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> /***************************************************************************//** * * @ingroup core_ttmqr * * Overwrites the general m1-by-n1 tile A1 and * m2-by-n2 tile A2 with * * side = PlasmaLeft side = PlasmaRight * trans = PlasmaNoTrans Q * | A1 | | A1 A2 | * Q * | A2 | * * trans = PlasmaTrans Q^T * | A1 | | A1 A2 | * Q^T * | A2 | * * where Q is a complex orthogonal matrix defined as the product of k * elementary reflectors * * Q = H(1) H(2) . . . H(k) * * as returned by plasma_core_sttqrt. * ******************************************************************************* * * @param[in] side * - PlasmaLeft : apply Q or Q^T from the Left; * - PlasmaRight : apply Q or Q^T from the Right. * * @param[in] trans * - PlasmaNoTrans : Apply Q; * - PlasmaTrans : Apply Q^T. * * @param[in] m1 * The number of rows of the tile A1. m1 >= 0. * * @param[in] n1 * The number of columns of the tile A1. n1 >= 0. * * @param[in] m2 * The number of rows of the tile A2. m2 >= 0. * m2 = m1 if side == PlasmaRight. * * @param[in] n2 * The number of columns of the tile A2. n2 >= 0. * n2 = n1 if side == PlasmaLeft. * * @param[in] k * The number of elementary reflectors whose product defines * the matrix Q. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in,out] A1 * On entry, the m1-by-n1 tile A1. * On exit, A1 is overwritten by the application of Q. * * @param[in] lda1 * The leading dimension of the array A1. lda1 >= max(1,m1). * * @param[in,out] A2 * On entry, the m2-by-n2 tile A2. * On exit, A2 is overwritten by the application of Q. * * @param[in] lda2 * The leading dimension of the tile A2. lda2 >= max(1,m2). * * @param[in] V * The i-th row must contain the vector which defines the * elementary reflector H(i), for i = 1,2,...,k, as returned by * plasma_core_sttqrt in the first k columns of its array argument V. * * @param[in] ldv * The leading dimension of the array V. ldv >= max(1,k). * * @param[in] T * The ib-by-k triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param work * Auxiliary workspace array of length * ldwork-by-n1 if side == PlasmaLeft * ldwork-by-ib if side == PlasmaRight * * @param[in] ldwork * The leading dimension of the array work. * ldwork >= max(1,ib) if side == PlasmaLeft * ldwork >= max(1,m1) if side == PlasmaRight * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ __attribute__((weak)) int plasma_core_sttmqr(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, float *A1, int lda1, float *A2, int lda2, const float *V, int ldv, const float *T, int ldt, float *work, int ldwork) { // Check input arguments. if ((side != PlasmaLeft) && (side != PlasmaRight)) { plasma_coreblas_error("illegal value of side"); return -1; } if ((trans != PlasmaNoTrans) && (trans != PlasmaTrans)) { plasma_coreblas_error("illegal value of trans"); return -2; } if (m1 < 0) { plasma_coreblas_error("illegal value of m1"); return -3; } if (n1 < 0) { plasma_coreblas_error("illegal value of n1"); return -4; } if ((m2 < 0) || ((m2 != m1) && (side == PlasmaRight))) { plasma_coreblas_error("illegal value of m2"); return -5; } if ((n2 < 0) || ((n2 != n1) && (side == PlasmaLeft))) { plasma_coreblas_error("illegal value of n2"); return -6; } if ((k < 0) || ((side == PlasmaLeft) && (k > m1)) || ((side == PlasmaRight) && (k > n1))) { plasma_coreblas_error("illegal value of k"); return -7; } if (ib < 0) { plasma_coreblas_error("illegal value of ib"); return -8; } if (A1 == NULL) { plasma_coreblas_error("NULL A1"); return -9; } if (lda1 < imax(1, m1)) { plasma_coreblas_error("illegal value of lda1"); return -10; } if (A2 == NULL) { plasma_coreblas_error("NULL A2"); return -11; } if (lda2 < imax(1, m2)) { plasma_coreblas_error("illegal value of lda2"); return -12; } if (V == NULL) { plasma_coreblas_error("NULL V"); return -13; } if (ldv < imax(1, side == PlasmaLeft ? m2 : n2)) { plasma_coreblas_error("illegal value of ldv"); return -14; } if (T == NULL) { plasma_coreblas_error("NULL T"); return -15; } if (ldt < imax(1,ib)) { plasma_coreblas_error("illegal value of ldt"); return -16; } if (work == NULL) { plasma_coreblas_error("NULL work"); return -17; } if (ldwork < imax(1, side == PlasmaLeft ? ib : m1)) { plasma_coreblas_error("Illegal value of ldwork"); return -18; } // quick return if (m1 == 0 || n1 == 0 || m2 == 0 || n2 == 0 || k == 0 || ib == 0) return PlasmaSuccess; int i1, i3; if ((side == PlasmaLeft && trans != PlasmaNoTrans) || (side == PlasmaRight && trans == PlasmaNoTrans)) { i1 = 0; i3 = ib; } else { i1 = ((k-1)/ib)*ib; i3 = -ib; } for (int i = i1; i > -1 && i < k; i += i3) { int kb = imin(ib, k-i); int ic = 0; int jc = 0; int mi = m1; int ni = n1; int mi2 = m2; int ni2 = n2; int l = 0; if (side == PlasmaLeft) { // H or H^T is applied to C(i:m,1:n). mi = kb; //m1 - i; mi2 = imin(i+kb, m2); ic = i; l = imin(kb, imax(0, m2-i)); } else { ni = kb; ni2 = imin(i+kb, n2); jc = i; l = imin(kb, imax(0, n2-i)); } // Apply H or H^T (NOTE: plasma_core_sparfb used to be core_zttrfb). plasma_core_sparfb(side, trans, PlasmaForward, PlasmaColumnwise, mi, ni, mi2, ni2, kb, l, &A1[lda1*jc+ic], lda1, A2, lda2, &V[ldv*i], ldv, &T[ldt*i], ldt, work, ldwork); } return PlasmaSuccess; } /******************************************************************************/ void plasma_core_omp_sttmqr(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, float *A1, int lda1, float *A2, int lda2, const float *V, int ldv, const float *T, int ldt, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A1[0:lda1*n1]) \ depend(inout:A2[0:lda2*n2]) \ depend(in:V[0:ldv*k]) \ depend(in:T[0:ib*k]) { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); float *W = (float*)work.spaces[tid]; int ldwork = side == PlasmaLeft ? ib : m1; // TODO: float check // Call the kernel. int info = plasma_core_sttmqr(side, trans, m1, n1, m2, n2, k, ib, A1, lda1, A2, lda2, V, ldv, T, ldt, W, ldwork); if (info != PlasmaSuccess) { plasma_error("core_sttmqr() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
quicksort.h
// -*- C++ -*- // Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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 library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file parallel/quicksort.h * @brief Implementation of a unbalanced parallel quicksort (in-place). * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_QUICKSORT_H #define _GLIBCXX_PARALLEL_QUICKSORT_H 1 #include <parallel/parallel.h> #include <parallel/partition.h> namespace __gnu_parallel { /** @brief Unbalanced quicksort divide step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __pivot_rank Desired __rank of the pivot. * @param __num_samples Choose pivot from that many samples. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> typename std::iterator_traits<_RAIter>::difference_type __parallel_sort_qs_divide(_RAIter __begin, _RAIter __end, _Compare __comp, typename std::iterator_traits <_RAIter>::difference_type __pivot_rank, typename std::iterator_traits <_RAIter>::difference_type __num_samples, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; __num_samples = std::min(__num_samples, __n); // Allocate uninitialized, to avoid default constructor. _ValueType* __samples = static_cast<_ValueType*> (::operator new(__num_samples * sizeof(_ValueType))); for (_DifferenceType __s = 0; __s < __num_samples; ++__s) { const unsigned long long __index = static_cast<unsigned long long> (__s) * __n / __num_samples; ::new(&(__samples[__s])) _ValueType(__begin[__index]); } __gnu_sequential::sort(__samples, __samples + __num_samples, __comp); _ValueType& __pivot = __samples[__pivot_rank * __num_samples / __n]; __gnu_parallel::__binder2nd<_Compare, _ValueType, _ValueType, bool> __pred(__comp, __pivot); _DifferenceType __split = __parallel_partition(__begin, __end, __pred, __num_threads); ::operator delete(__samples); return __split; } /** @brief Unbalanced quicksort conquer step. * @param __begin Begin iterator of subsequence. * @param __end End iterator of subsequence. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> void __parallel_sort_qs_conquer(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; if (__num_threads <= 1) { __gnu_sequential::sort(__begin, __end, __comp); return; } _DifferenceType __n = __end - __begin, __pivot_rank; if (__n <= 1) return; _ThreadIndex __num_threads_left; if ((__num_threads % 2) == 1) __num_threads_left = __num_threads / 2 + 1; else __num_threads_left = __num_threads / 2; __pivot_rank = __n * __num_threads_left / __num_threads; _DifferenceType __split = __parallel_sort_qs_divide (__begin, __end, __comp, __pivot_rank, _Settings::get().sort_qs_num_samples_preset, __num_threads); #pragma omp parallel sections num_threads(2) { #pragma omp section __parallel_sort_qs_conquer(__begin, __begin + __split, __comp, __num_threads_left); #pragma omp section __parallel_sort_qs_conquer(__begin + __split, __end, __comp, __num_threads - __num_threads_left); } } /** @brief Unbalanced quicksort main call. * @param __begin Begin iterator of input sequence. * @param __end End iterator input sequence, ignored. * @param __comp Comparator. * @param __num_threads Number of threads that are allowed to work on * this part. */ template<typename _RAIter, typename _Compare> void __parallel_sort_qs(_RAIter __begin, _RAIter __end, _Compare __comp, _ThreadIndex __num_threads) { _GLIBCXX_CALL(__n) typedef std::iterator_traits<_RAIter> _TraitsType; typedef typename _TraitsType::value_type _ValueType; typedef typename _TraitsType::difference_type _DifferenceType; _DifferenceType __n = __end - __begin; // At least one element per processor. if (__num_threads > __n) __num_threads = static_cast<_ThreadIndex>(__n); __parallel_sort_qs_conquer( __begin, __begin + __n, __comp, __num_threads); } } //namespace __gnu_parallel #endif /* _GLIBCXX_PARALLEL_QUICKSORT_H */