source
stringlengths
3
92
c
stringlengths
26
2.25M
SpecificityMeasurer.h
#ifndef __SPECIFICITY_MEASURER_H__ #define __SPECIFICITY_MEASURER_H__ #include <vector> #include "mesh/Mesh.h" #include "model/Model.h" #include "model/ModelBuilder.h" #include "Subset.h" #include "ErrorDatabase.h" class SpecificityMeasurer{ public: /*-----------------------------------------------------------------------*/ SpecificityMeasurer(const std::vector<Mesh>& meshes, const ModelBuilder& builder) : meshes(meshes), builder(builder) { } /*-----------------------------------------------------------------------*/ SpecificityMeasurer& set_max_components( const int maxComponents) { this->maxComponents = maxComponents; return *this; } /*-----------------------------------------------------------------------*/ SpecificityMeasurer& set_min_components( const int minComponents) { this->minComponents = minComponents; return *this; } /*-----------------------------------------------------------------------*/ SpecificityMeasurer& set_sample_amount( const int sampleAmount) { this->sampleAmount = sampleAmount; return *this; } /*-----------------------------------------------------------------------*/ void measure(std::vector<Subset>& subsets) { init(); for( int i_component = maxComponents; i_component >= this->minComponents; --i_component) { create_model(i_component); // create for each subset an error vector std::vector<arma::vec> errors; for( unsigned int i_subset = 0; i_subset < subsets.size(); ++i_subset) { errors.push_back(arma::zeros(sampleAmount)); } // end for subsets #pragma omp parallel for shared(errors) for( int i_sample = 0; i_sample < sampleAmount; ++i_sample) { Mesh shape = generate_shape(); // find for each subset the smallest distance to a mesh for( unsigned int i_subset = 0; i_subset < subsets.size(); ++i_subset) { errors.at(i_subset)(i_sample) = get_smallest_mean_distance(shape, subsets.at(i_subset).indices); } // end for subsets } // end for sampleAmount // compute statistics for each subset for( unsigned int i_subset = 0; i_subset < subsets.size(); ++i_subset) { const double mean = arma::mean(errors.at(i_subset)); const double standardDeviation = arma::stddev(errors.at(i_subset), 1); subsets.at(i_subset).errorDataBase.add_error( i_component, mean, standardDeviation ); } // end for subsets } // end for components return; } /*-----------------------------------------------------------------------*/ protected: /*-----------------------------------------------------------------------*/ double get_smallest_mean_distance(const Mesh& source, const std::vector<int>& subset) { double minDistance = DBL_MAX; for(const Mesh& target: this->meshes) { double currentDistance = 0; for(const int& index: subset){ const arma::vec sourcePoint = source.get_vertices().at(index); const arma::vec targetPoint = target.get_vertices().at(index); currentDistance += arma::norm(targetPoint - sourcePoint); } // end subset currentDistance /= subset.size(); minDistance = (currentDistance < minDistance)? currentDistance: minDistance; } // end for currentTarget return minDistance; } /*-----------------------------------------------------------------------*/ virtual Mesh generate_shape() { return this->model.sample().generate(); } /*-----------------------------------------------------------------------*/ virtual void init() = 0; virtual void create_model(const int&) = 0; /*-----------------------------------------------------------------------*/ int minComponents = 1; int maxComponents = 1; int sampleAmount = 1000; /*-----------------------------------------------------------------------*/ std::vector<Mesh> meshes; Model model; ModelBuilder builder; /*-----------------------------------------------------------------------*/ }; #endif
wrapfftw.c
#include <stdio.h> #include <stdlib.h> #include "hpccfft.h" #ifdef _OPENMP #include <omp.h> #endif hpcc_fftw_plan HPCC_fftw_create_plan(int n, fftw_direction dir, int flags) { hpcc_fftw_plan p; fftw_complex *a = NULL, *b = NULL; p = (hpcc_fftw_plan)fftw_malloc( sizeof *p ); if (! p) return p; p->w1 = (fftw_complex *)fftw_malloc( (FFTE_NDA2/2 + FFTE_NP) * (sizeof *p->w1) ); p->w2 = (fftw_complex *)fftw_malloc( (FFTE_NDA2/2 + FFTE_NP) * (sizeof *p->w2) ); p->ww = (fftw_complex *)fftw_malloc( ((FFTE_NDA2+FFTE_NP) * 4 + FFTE_NP) * (sizeof *p->ww) ); p->c_size = (FFTE_NDA2+FFTE_NP) * (FFTE_NBLK + 1) + FFTE_NP; #ifdef _OPENMP #pragma omp parallel { #pragma omp single { int i; i = omp_get_num_threads(); p->c = (fftw_complex *)fftw_malloc( p->c_size * (sizeof *p->c) * i ); } } #else p->c = (fftw_complex *)fftw_malloc( p->c_size * (sizeof *p->c) ); #endif if (! p->w1 || ! p->w2 || ! p->ww || ! p->c) { if (p->c) fftw_free( p->c ); if (p->ww) fftw_free( p->ww ); if (p->w2) fftw_free( p->w2 ); if (p->w1) fftw_free( p->w1 ); fftw_free( p ); return NULL; } HPCC_zfft1d( n, a, b, 0, p ); p->n = n; p->dir = dir; p->flags = flags; return p; } void HPCC_fftw_destroy_plan(hpcc_fftw_plan p) { if (! p) return; fftw_free( p->c ); fftw_free( p->ww ); fftw_free( p->w2 ); fftw_free( p->w1 ); fftw_free( p ); } /* Without additional storage of size p->n there is no way to preserve FFTW 2 semantics (the `in' vector is not modified). But it doesn't matter for the calling code: it doesn't rely on this semantics. The change in semantics occured while going from FFTE 3.3 to FFTE 4.0. */ void HPCC_fftw_one(hpcc_fftw_plan p, fftw_complex *in, fftw_complex *out) { int i, n; if (FFTW_FORWARD == p->dir) HPCC_zfft1d( p->n, in, out, -1, p ); else HPCC_zfft1d( p->n, in, out, +1, p ); n = p->n; /* Copy the transform to `out' vector. */ for (i = 0; i < n; ++i) { c_assgn( out[i], in[i] ); } }
sparselu.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 <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <libgen.h> #include "bots.h" #include "sparselu.h" #include "read_memory.h" /*********************************************************************** * checkmat: **********************************************************************/ //float tmp[bots_arg_size][bots_arg_size][bots_arg_size_1*bots_arg_size_1]; int checkmat (float *M, float *N) { //printf("11111\n"); int i, j; float r_err; for (i = 0; i < bots_arg_size_1; i++) { for (j = 0; j < bots_arg_size_1; j++) { r_err = M[i*bots_arg_size_1+j] - N[i*bots_arg_size_1+j]; if (r_err < 0.0 ) r_err = -r_err; r_err = r_err / M[i*bots_arg_size_1+j]; if(r_err > EPSILON) { printf("Checking failure: A[%d][%d]=%20.12E B[%d][%d]=%20.12E; Relative Error=%20.12E\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); bots_message("Checking failure: A[%d][%d]=%f B[%d][%d]=%f; Relative Error=%f\n", i,j, M[i*bots_arg_size_1+j], i,j, N[i*bots_arg_size_1+j], r_err); return FALSE; } } } return TRUE; } /*********************************************************************** * genmat: **********************************************************************/ void genmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; float *prow; float rowsum; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ // M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); M[ii*bots_arg_size+jj] = (float*)((void*)tmp + tmp_pos); tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ /* Modify diagonal element of each row in order */ /* to ensure matrix is diagonally dominant and */ /* well conditioned. */ prow = p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { rowsum = 0.0; for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); rowsum += abs(*p); p++; } if (ii == jj) *(prow+i) = rowsum * (float) bots_arg_size + abs(*(prow+i)); prow += bots_arg_size_1; } } else { M[ii*bots_arg_size+jj] = NULL; } } } } /*********************************************************************** * print_structure: **********************************************************************/ void print_structure(char *name, float *M[]) { int ii, jj; bots_message("Structure for matrix %s @ 0x%p\n",name, M); for (ii = 0; ii < bots_arg_size; ii++) { for (jj = 0; jj < bots_arg_size; jj++) { if (M[ii*bots_arg_size+jj]!=NULL) {bots_message("x");} else bots_message(" "); } bots_message("\n"); } bots_message("\n"); } /*********************************************************************** * allocate_clean_block: **********************************************************************/ float * allocate_clean_block() { int i,j; float *p, *q; //printf("1\n"); // p = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); p = (float*)((void*)tmp + tmp_pos); tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); q=p; if (p!=NULL){ for (i = 0; i < bots_arg_size_1; i++) for (j = 0; j < bots_arg_size_1; j++){(*p)=0.0; p++;} } else { bots_message("Error: Out of memory\n"); exit (101); } return (q); } /*********************************************************************** * lu0: **********************************************************************/ void lu0(float *diag) { int i, j, k; //if(recompute == 0) flag1 = -1;//if(recompute == 0) for (k=flag1+1; k<bots_arg_size_1; k++) { for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } //kai } } /*********************************************************************** * bdiv: **********************************************************************/ void bdiv(float *diag, float *row) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) { for (k=0; k<bots_arg_size_1; k++) { row[i*bots_arg_size_1+k] = row[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) row[i*bots_arg_size_1+j] = row[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*diag[k*bots_arg_size_1+j]; } } } /*********************************************************************** * bmod: **********************************************************************/ void bmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * bmod: **********************************************************************/ void vbmod(float *row, float *col, float *inner) { int i, j, k; for (i=0; i<bots_arg_size_1; i++) for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) inner[i*bots_arg_size_1+j] = inner[i*bots_arg_size_1+j] - row[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } /*********************************************************************** * fwd: **********************************************************************/ void fwd(float *diag, float *col) { int i, j, k; for (j=0; j<bots_arg_size_1; j++) for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) col[i*bots_arg_size_1+j] = col[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k]*col[k*bots_arg_size_1+j]; } void sparselu_init (float ***pBENCH, char *pass) { tmp_pos = 0; *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); // printf("%s\n", pass): tmp = malloc((bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); //*pBENCH = (float **)tmp + tmp_pos; //tmp_pos += bots_arg_size*bots_arg_size*sizeof(float *); genmat(*pBENCH); //crucial_data(tmp, "float", (bots_arg_size*bots_arg_size*bots_arg_size_1*bots_arg_size_1)); //kai /*consistent_data(&flag1, "int", 1); consistent_data(&flag2, "int", 1); consistent_data(&flag3, "int", 1); consistent_data(&flag4, "int", 1); consistent_data(&flag5, "int", 1);*/ /* spec print_structure(pass, *pBENCH); */ } void sparselu_par_call(float **BENCH) { //printf("1111\n"); int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); //kai //flush_whole_cache(); //start_crash(); float *tmpt; tmpt = malloc((bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); int t_flag1,t_flag2,t_flag3,t_flag4,t_flag5,t_flag6,t_flag7,t_flag8,t_flag9; ppid = pid; addr[count_addr++] = tmpt; addr[count_addr++] = &t_flag1; addr[count_addr++] = &t_flag2; addr[count_addr++] = &t_flag3; addr[count_addr++] = &t_flag4; addr[count_addr++] = &t_flag5; addr[count_addr++] = &t_flag6; addr[count_addr++] = &t_flag7; addr[count_addr++] = &t_flag8; addr[count_addr++] = &t_flag9; ReadVarriable(addr,count_addr); printf("flag1 = %d\n",t_flag1); printf("flag2 = %d\n",t_flag2); printf("flag3 = %d\n",t_flag3); printf("flag4 = %d\n",t_flag4); printf("flag5 = %d\n",t_flag5); printf("flag6 = %d\n",t_flag6); printf("flag7 = %d\n",t_flag7); printf("flag8 = %d\n",t_flag8); printf("flag9 = %d\n",t_flag9); //kk=0;flag1 = -1;flag2=kk; flag3 = kk; flag4 = kk; //memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); #pragma omp parallel #pragma omp single nowait //flag5=-1; for (kk=0; kk<bots_arg_size; kk++) { /* */ lu0(BENCH[kk*bots_arg_size+kk]); //if(recompute == 0) flag2=kk; flag2=kk; for (jj=flag2+1; jj<bots_arg_size; jj++) { if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } //kai //flag2 = kk+1; } //if(recompute == 0) flag3=kk; flag3=kk; for (ii=flag3+1; ii<bots_arg_size; ii++) { if (BENCH[ii*bots_arg_size+kk] != NULL) #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } //kai //flag3 = kk+1; } /* if(kk == flag5) { recompute = 1; float *ttmp = (float*) tmp; memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); flag1 = t_flag1;flag2=t_flag2; flag3 =t_flag3; flag4 = t_flag4; } else{ recompute = 0; }*/ if(recompute == 0) flag4=kk; #pragma omp taskwait for (ii=flag4+1; ii<bots_arg_size; ii++) { if(kk == flag5) printf("ii = %d\n",ii); if (BENCH[ii*bots_arg_size+kk] != NULL){ for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } //kai //flag4 = kk+1; if(kk == flag5 && ii ==flag4 &&jj==flag6) { //memcpy(tmpt,tmp,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); memcpy(tmp,tmpt,(bots_arg_size*bots_arg_size)*bots_arg_size_1*bots_arg_size_1*sizeof(float)); if (strcmp(tmp,tmpt) == 0) { printf("Equal\n"); } else{ printf("Error!\n"); } } } } #pragma omp taskwait //flag5 = kk; recompute = 0; } //kai // end_crash(); bots_message(" completed!\n"); } void sparselu_seq_call(float **BENCH) { int ii, jj, kk; for (kk=0; kk<bots_arg_size; kk++) { lu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); bmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } } void sparselu_fini (float **BENCH, char *pass) { /* spec print_structure(pass, BENCH); */ return; } /* * changes for SPEC, original source * int sparselu_check(float **SEQ, float **BENCH) { int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; } */ /* * SPEC modified check, print out values * */ void vgenmat (float *M[]) { int null_entry, init_val, i, j, ii, jj; float *p; float *prow; float rowsum; init_val = 1325; /* generating the structure */ for (ii=0; ii < bots_arg_size; ii++) { for (jj=0; jj < bots_arg_size; jj++) { /* computing null entries */ null_entry=FALSE; if ((ii<jj) && (ii%3 !=0)) null_entry = TRUE; if ((ii>jj) && (jj%3 !=0)) null_entry = TRUE; if (ii%2==1) null_entry = TRUE; if (jj%2==1) null_entry = TRUE; if (ii==jj) null_entry = FALSE; if (ii==jj-1) null_entry = FALSE; if (ii-1 == jj) null_entry = FALSE; /* allocating matrix */ if (null_entry == FALSE){ M[ii*bots_arg_size+jj] = (float *) malloc(bots_arg_size_1*bots_arg_size_1*sizeof(float)); // M[ii*bots_arg_size+jj] = (float*)((void*)tmp + tmp_pos); // tmp_pos += bots_arg_size_1*bots_arg_size_1*sizeof(float); if ((M[ii*bots_arg_size+jj] == NULL)) { bots_message("Error: Out of memory\n"); exit(101); } /* initializing matrix */ /* Modify diagonal element of each row in order */ /* to ensure matrix is diagonally dominant and */ /* well conditioned. */ prow = p = M[ii*bots_arg_size+jj]; for (i = 0; i < bots_arg_size_1; i++) { rowsum = 0.0; for (j = 0; j < bots_arg_size_1; j++) { init_val = (3125 * init_val) % 65536; (*p) = (float)((init_val - 32768.0) / 16384.0); rowsum += abs(*p); p++; } if (ii == jj) *(prow+i) = rowsum * (float) bots_arg_size + abs(*(prow+i)); prow += bots_arg_size_1; } } else { M[ii*bots_arg_size+jj] = NULL; } } } } void vlu0(float *diag) { int i, j, k; for (k=0; k<bots_arg_size_1; k++) for (i=k+1; i<bots_arg_size_1; i++) { diag[i*bots_arg_size_1+k] = diag[i*bots_arg_size_1+k] / diag[k*bots_arg_size_1+k]; for (j=k+1; j<bots_arg_size_1; j++) diag[i*bots_arg_size_1+j] = diag[i*bots_arg_size_1+j] - diag[i*bots_arg_size_1+k] * diag[k*bots_arg_size_1+j]; } } void vsparselu_init (float ***pBENCH, char *pass) { *pBENCH = (float **) malloc(bots_arg_size*bots_arg_size*sizeof(float *)); vgenmat(*pBENCH); /* spec print_structure(pass, *pBENCH); */ } void vsparselu_par_call(float **BENCH) { int ii, jj, kk; bots_message("Computing SparseLU Factorization (%dx%d matrix with %dx%d blocks) ", bots_arg_size,bots_arg_size,bots_arg_size_1,bots_arg_size_1); #pragma omp parallel #pragma omp single nowait for (kk=0; kk<bots_arg_size; kk++) { vlu0(BENCH[kk*bots_arg_size+kk]); for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj) shared(BENCH) { fwd(BENCH[kk*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj]); } for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) #pragma omp task untied firstprivate(kk, ii) shared(BENCH) { bdiv (BENCH[kk*bots_arg_size+kk], BENCH[ii*bots_arg_size+kk]); } #pragma omp taskwait for (ii=kk+1; ii<bots_arg_size; ii++) if (BENCH[ii*bots_arg_size+kk] != NULL) for (jj=kk+1; jj<bots_arg_size; jj++) if (BENCH[kk*bots_arg_size+jj] != NULL) #pragma omp task untied firstprivate(kk, jj, ii) shared(BENCH) { if (BENCH[ii*bots_arg_size+jj]==NULL) BENCH[ii*bots_arg_size+jj] = allocate_clean_block(); vbmod(BENCH[ii*bots_arg_size+kk], BENCH[kk*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } #pragma omp taskwait } bots_message("pre verify completed!\n"); } int sparselu_check(float **SEQ, float **BENCH) { vsparselu_init(&SEQ, NULL); vsparselu_par_call(SEQ); int ii,jj,ok=1; for (ii=0; ((ii<bots_arg_size) && ok); ii++) { for (jj=0; ((jj<bots_arg_size) && ok); jj++) { if ((SEQ[ii*bots_arg_size+jj] == NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] == NULL)) ok = FALSE; if ((SEQ[ii*bots_arg_size+jj] != NULL) && (BENCH[ii*bots_arg_size+jj] != NULL)) ok = checkmat(SEQ[ii*bots_arg_size+jj], BENCH[ii*bots_arg_size+jj]); } } FILE *file; char result_file[128] = "/home/cc/nvc/tests/recompute_result.out.jie"; sprintf(result_file + strlen(result_file), "%d", pid); file = fopen(result_file,"w"); if(ok) { fprintf(file,"SUCCESS\n"); } else{ fprintf(file,"UNSUCCESS\n"); } fclose(file); if (ok) return BOTS_RESULT_SUCCESSFUL; else return BOTS_RESULT_UNSUCCESSFUL; /* int i, j, ok; bots_message("Output size: %d\n",bots_arg_size); for (i = 0; i < bots_arg_size; i+=50) { for (j = 0; j < bots_arg_size; j+=40) { ok = checkmat1(BENCH[i*bots_arg_size+j]); } } return BOTS_RESULT_SUCCESSFUL; */ } int checkmat1 (float *N) { int i, j; for (i = 0; i < bots_arg_size_1; i+=20) { for (j = 0; j < bots_arg_size_1; j+=20) { bots_message("Output Matrix: A[%d][%d]=%8.12f \n", i,j, N[i*bots_arg_size_1+j]); } } //printf("111111111\n"); return TRUE; }
dpotrs.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zpotrs.c, normal z -> d, Fri Sep 28 17:38:02 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_potrs * * Solves a system of linear equations A * X = B with a symmetric positive * definite in the complex matrix A using the Cholesky factorization * A = U^T*U or A = L*L^T computed by plasma_dpotrf. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in] nrhs * The number of right hand sides, i.e., the number of * columns of the matrix B. nrhs >= 0. * * @param[in,out] pA * The triangular factor U or L from the Cholesky * factorization A = U^T*U or A = L*L^T, computed by * plasma_dpotrf. * Remark: If out-of-place layout translation is used, the * matrix A can be considered as input, however if inplace * layout translation is enabled, the content of A will be * reordered for computation and restored before exiting the * function. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * * @param[in,out] pB * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,n). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************* * * @sa plasma_omp_dpotrs * @sa plasma_cpotrs * @sa plasma_dpotrs * @sa plasma_spotrs * @sa plasma_dpotrf * ******************************************************************************/ int plasma_dpotrs(plasma_enum_t uplo, int n, int nrhs, double *pA, int lda, double *pB, int ldb) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (nrhs < 0) { plasma_error("illegal value of nrhs"); return -3; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -5; } if (ldb < imax(1, n)) { plasma_error("illegal value of ldb"); return -7; } // quick return if (imax(n, nrhs) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_trsm(plasma, PlasmaRealDouble, n, n); // Set tiling parameters. int nb = plasma->nb; // Initialize tile matrix descriptors. plasma_desc_t A; plasma_desc_t B; int retval; retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb, n, nrhs, 0, 0, n, nrhs, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_dge2desc(pA, lda, A, &sequence, &request); plasma_omp_dge2desc(pB, ldb, B, &sequence, &request); // Call the tile async function. plasma_omp_dpotrs(uplo, A, B, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_ddesc2ge(B, pB, ldb, &sequence, &request); } // implicit synchronization // Free matrix A in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * * @ingroup plasma_potrs * * Solves a system of linear equations using previously * computed Cholesky factorization. * Non-blocking tile version of plasma_dpotrs(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] A * The triangular factor U or L from the Cholesky factorization * A = U^T*U or A = L*L^T, computed by plasma_dpotrf. * * @param[in,out] B * On entry, the n-by-nrhs right hand side matrix B. * On exit, if return value = 0, the n-by-nrhs solution matrix X. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_dpotrs * @sa plasma_omp_dpotrs * @sa plasma_omp_cpotrs * @sa plasma_omp_dpotrs * @sa plasma_omp_spotrs * @sa plasma_omp_dpotrf * ******************************************************************************/ void plasma_omp_dpotrs(plasma_enum_t uplo, plasma_desc_t A, plasma_desc_t B, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_fatal_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_fatal_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (A.n == 0 || B.n == 0) return; // Call the parallel functions. plasma_pdtrsm(PlasmaLeft, uplo, uplo == PlasmaUpper ? PlasmaConjTrans : PlasmaNoTrans, PlasmaNonUnit, 1.0, A, B, sequence, request); plasma_pdtrsm(PlasmaLeft, uplo, uplo == PlasmaUpper ? PlasmaNoTrans : PlasmaConjTrans, PlasmaNonUnit, 1.0, A, B, sequence, request); }
Calculate_AOs.c
#include "num_of_threads.h" #include<omp.h> #include"utils.h" #include"structs.h" #include"matrix_ops.h" #include"globals.h" void Calculate_AOs(int *tlist,double *vlist,int nfac,int nvert,double *angles,AOstruct *AOs,double *offset,double *D,int dm,int dn,double *Weight,double *scale,double *FT,double *FTdv,double* FTdS,double *Albedo,double *Alimit,double *dA,int deriv) { /*tlist,vlist,angles -the asteroid shape * AO struct contains the AO data * offset naox2 vector, offsets, * D is the derivative matrix (dm x dn), derivatives of vertex coordinates wrt parameters * Weight is additional weighting terms for individual AO images, 1xnao vector (not implemented yet) * Scale additional scaling terms for each ao image. * Albedo nfac vector, optional * Alimit, albedo limit 2-vector * deriv==1, then the derivatives will be calculated * OUTPUT: * FTr,FTi real and imaginary results * Derivative matrix FTdvr (real) FTdvi (imag) */ /* Denote the total number of data points by ntpoints. Then * FT is 2*ntpoints vector * FTdv is 2*ntpoints x (3*dn+3+2*nao) matrix =[real(FTdx)*D real(FTdy)*D real(FTdz)*D real(FTdA) real(FTdoff); * imag(FTdx)*D imag(FTdy)*D imag(FTdz)*D imag(FTdA) imag(FTdoff);...] * FTdS is an optional matrix for Scaling terms * dAr, dAi 2*ntpointsxnfac matrices, only if albedo is to be fitted * NOTE THAT FTdv is assumed to be initialized to zero */ /*TBD: Combine real and complex matrices here*/ int tid; int DisNULL=0; int D1V=0; int D3V=0; int UseScale=0; int UseWeight=0; if(scale!=NULL) UseScale=1; int nao; nao=AOs->nao; //Number of AO images /*First some sanity checking*/ if(D==NULL) DisNULL=1; if(!DisNULL && nvert!=dm) { puts("Error: nvert is not equal dm."); exit(1); } if(Weight!=NULL) UseWeight=1; int M,N; int *nopoints,*cumpoints,ntpoints; nopoints=AOs->nobs; //Array, number of samples in each AO image cumpoints=malloc((nao+1)*sizeof(int)); cumpoints[0]=0; for(int i=1;i<=nao;i++) cumpoints[i]=cumpoints[i-1]+nopoints[i-1]; //cumpoints is the cumulative sum of all observation points, used for indexing ntpoints=cumpoints[nao];//Total number of points if(deriv==0) { omp_set_num_threads(NUM_THREADS); #pragma omp parallel for for(int obsind=0;obsind<nao;obsind++) { // printf("Thread %d, number of threads %d\n",omp_get_thread_num(),omp_get_num_threads()); double Scale=1; if(UseScale==1) Scale=exp(scale[obsind]); double *FTE,*FTE0,*FTTIME,*FTfreqx,*FTfreqy,*FTup,*FTdist,*datar,*datai; double *FTr; double *FTi; double *psfi; double *psfr; double W; if(UseWeight==1) W=Weight[obsind]; else W=1; FTr=calloc(nopoints[obsind],sizeof(double)); FTi=calloc(nopoints[obsind],sizeof(double)); FTE=AOs->E+3*obsind; FTE0=AOs->E0+3*obsind; FTup=AOs->up+3*obsind; FTTIME=AOs->TIME+obsind; FTfreqx=AOs->freqx[obsind]; FTfreqy=AOs->freqy[obsind]; FTdist=AOs->distance+obsind; datar=AOs->datar[obsind]; datai=AOs->datai[obsind]; psfr=AOs->psfr[obsind]; psfi=AOs->psfi[obsind]; // double time=omp_get_wtime(); INI_AO_TOTAL_BRIGHT[obsind]=Calculate_AO(tlist,vlist,nfac,nvert,angles,FTE,FTE0,FTup,*FTTIME,*FTdist,FTfreqx,FTfreqy,nopoints[obsind],offset+2*obsind,FTr,FTi,Albedo,Alimit); // printf("Time taken: %f\n",omp_get_wtime()-time); if(psfr==NULL || psfi==NULL) { for(int j=0;j<nopoints[obsind];j++) { FT[j+cumpoints[obsind]]=W*(datar[j]-Scale*FTr[j]); FT[j+cumpoints[obsind]+ntpoints]=W*(datai[j]-Scale*FTi[j]); } } else { for(int j=0;j<nopoints[obsind];j++) { FT[j+cumpoints[obsind]]=W*(datar[j]-Scale*(psfr[j]*FTr[j]-psfi[j]*FTi[j])); FT[j+cumpoints[obsind]+ntpoints]=W*(datai[j]-Scale*(psfi[j]*FTr[j]+psfr[j]*FTi[j])); } } free(FTr); free(FTi); } free(cumpoints); return; } int nvertf; if(D!=NULL) nvertf=dn; else { nvertf=nvert; dn=nvert; } zero_array(FTdv,2*ntpoints*(3*dn+3+2*nao)); if(UseScale==1) zero_array(FTdS,2*ntpoints*nao); omp_set_num_threads(NUM_THREADS); #pragma omp parallel for for(int obsind=0;obsind<nao;obsind++) { double Scale=1; if(UseScale==1) Scale=exp(scale[obsind]); int cind=0; int oind=0; double W; if(UseWeight==1) W=Weight[obsind]; else W=1; double *FTdxfr,*FTdxfi,*FTdyfr,*FTdyfi,*FTdzfr,*FTdzfi; double *FTE,*FTE0,*FTTIME,*FTfreqx,*FTfreqy,*FTdist,*FTup,*datar,*datai; double *FTdAr,*FTdAi,*FTdoffr,*FTdoffi,*FTdxr,*FTdxi,*FTdyr,*FTdyi,*FTdzr,*FTdzi; double *FTr,*FTi; double *psfr,*psfi; double *dFTdAlbr,*dFTdAlbi; psfr=AOs->psfr[obsind]; psfi=AOs->psfi[obsind]; // obsind=omp_get_thread_num(); FTr=calloc(nopoints[obsind],sizeof(double)); FTi=calloc(nopoints[obsind],sizeof(double)); //TBD: This is a temporary solution, fix this! FTdAr=calloc(nopoints[obsind]*3,sizeof(double)); FTdAi=calloc(nopoints[obsind]*3,sizeof(double)); FTdoffr=calloc(nopoints[obsind]*2,sizeof(double)); FTdoffi=calloc(nopoints[obsind]*2,sizeof(double)); FTdxr=calloc(nopoints[obsind]*nvertf,sizeof(double)); FTdxi=calloc(nopoints[obsind]*nvertf,sizeof(double)); FTdyr=calloc(nopoints[obsind]*nvertf,sizeof(double)); FTdyi=calloc(nopoints[obsind]*nvertf,sizeof(double)); FTdzr=calloc(nopoints[obsind]*nvertf,sizeof(double)); FTdzi=calloc(nopoints[obsind]*nvertf,sizeof(double)); if(INI_FIT_AO_ALBEDO==1) { dFTdAlbr=calloc(nopoints[obsind]*nvert,sizeof(double)); dFTdAlbi=calloc(nopoints[obsind]*nvert,sizeof(double)); } datar=AOs->datar[obsind]; datai=AOs->datai[obsind]; FTE=AOs->E+3*obsind; FTE0=AOs->E0+3*obsind; FTup=AOs->up+3*obsind; FTTIME=AOs->TIME+obsind; FTfreqx=AOs->freqx[obsind]; FTfreqy=AOs->freqy[obsind]; FTdist=AOs->distance+obsind; if(D!=NULL) { FTdxfr=calloc(nopoints[obsind]*nvert,sizeof(double)); FTdyfr=calloc(nopoints[obsind]*nvert,sizeof(double)); FTdzfr=calloc(nopoints[obsind]*nvert,sizeof(double)); FTdxfi=calloc(nopoints[obsind]*nvert,sizeof(double)); FTdyfi=calloc(nopoints[obsind]*nvert,sizeof(double)); FTdzfi=calloc(nopoints[obsind]*nvert,sizeof(double)); //double time=omp_get_wtime(); Calculate_AO_deriv(tlist,vlist,nfac,nvert,angles,FTE,FTE0,FTup, *FTTIME,*FTdist,FTfreqx,FTfreqy,nopoints[obsind],offset+2*obsind,FTr,FTi,FTdxfr,FTdxfi,FTdyfr,FTdyfi,FTdzfr,FTdzfi,FTdAr,FTdAi,FTdoffr,FTdoffi,Albedo,Alimit,dFTdAlbr,dFTdAlbi); // printf("Time taken: %f\n",omp_get_wtime()-time); //Convert from vlistn->vlist by multiplying with D matrix_prod(FTdxfr,nopoints[obsind],nvert,D,nvertf,FTdxr); matrix_prod(FTdxfi,nopoints[obsind],nvert,D,nvertf,FTdxi); free(FTdxfr); free(FTdxfi); matrix_prod(FTdyfr,nopoints[obsind],nvert,D,nvertf,FTdyr); matrix_prod(FTdyfi,nopoints[obsind],nvert,D,nvertf,FTdyi); free(FTdyfr); free(FTdyfi); matrix_prod(FTdzfr,nopoints[obsind],nvert,D,nvertf,FTdzr); matrix_prod(FTdzfi,nopoints[obsind],nvert,D,nvertf,FTdzi); free(FTdzfr); free(FTdzfi); } else Calculate_AO_deriv(tlist,vlist,nfac,nvert,angles,FTE,FTE0,FTup, *FTTIME,*FTdist,FTfreqx,FTfreqy,nopoints[obsind],offset+2*obsind,FTr,FTi,FTdxr,FTdxi,FTdyr,FTdyi,FTdzr,FTdzi,FTdAr,FTdAi,FTdoffr,FTdoffi,Albedo,Alimit,dFTdAlbr,dFTdAlbi); cind=cumpoints[obsind]; oind=nopoints[obsind]; if(psfr==NULL || psfi==NULL) { for(int j=0;j<oind;j++) { FTr[j]=FTr[j]*Scale; FTi[j]=FTi[j]*Scale; FT[j+cind]=W*(datar[j]-FTr[j]); FT[j+cind+ntpoints]=W*(datai[j]-FTi[j]); } } else { double temp; for(int j=0;j<oind;j++) { temp=FTr[j]; FTr[j]=Scale*(psfr[j]*FTr[j]-psfi[j]*FTi[j]); FTi[j]=Scale*(psfi[j]*temp+psfr[j]*FTi[j]); FT[j+cind]=W*(datar[j]-FTr[j]); FT[j+cind+ntpoints]=W*(datai[j]-FTi[j]); } //Multiply derivatives with the psf for(int k1=0;k1<oind;k1++) { for(int k2=0;k2<nvertf;k2++) { temp=FTdxr[k1*nvertf+k2]; FTdxr[k1*nvertf+k2]=FTdxr[k1*nvertf+k2]*psfr[k1]-psfi[k1]*FTdxi[k1*nvertf+k2]; FTdxi[k1*nvertf+k2]=FTdxi[k1*nvertf+k2]*psfr[k1]+psfi[k1]*temp; temp=FTdyr[k1*nvertf+k2]; FTdyr[k1*nvertf+k2]=FTdyr[k1*nvertf+k2]*psfr[k1]-psfi[k1]*FTdyi[k1*nvertf+k2]; FTdyi[k1*nvertf+k2]=FTdyi[k1*nvertf+k2]*psfr[k1]+psfi[k1]*temp; temp=FTdzr[k1*nvertf+k2]; FTdzr[k1*nvertf+k2]=FTdzr[k1*nvertf+k2]*psfr[k1]-psfi[k1]*FTdzi[k1*nvertf+k2]; FTdzi[k1*nvertf+k2]=FTdzi[k1*nvertf+k2]*psfr[k1]+psfi[k1]*temp; } for(int k2=0;k2<3;k2++) { temp=FTdAr[k1*3+k2]; FTdAr[k1*3+k2]=FTdAr[k1*3+k2]*psfr[k1]-psfi[k1]*FTdAi[k1*3+k2]; FTdAi[k1*3+k2]=FTdAi[k1*3+k2]*psfr[k1]+psfi[k1]*temp; } temp=FTdoffr[k1*2]; FTdoffr[k1*2]=FTdoffr[k1*2]*psfr[k1]-psfi[k1]*FTdoffi[k1*2]; FTdoffi[k1*2]=FTdoffi[k1*2]*psfr[k1]+psfi[k1]*temp; temp=FTdoffr[k1*2+1]; FTdoffr[k1*2+1]=FTdoffr[k1*2+1]*psfr[k1]-psfi[k1]*FTdoffi[k1*2+1]; FTdoffi[k1*2+1]=FTdoffi[k1*2+1]*psfr[k1]+psfi[k1]*temp; } //If albedo is used, calculate albedo derivatives if(INI_FIT_AO_ALBEDO==1) for (int k1=0;k1<oind;k1++) for(int k2=0;k2<nvert;k2++) { temp=dFTdAlbr[k1*nvert+k2]; dFTdAlbr[k1*nvert+k2]=dFTdAlbr[k1*nvert+k2]*psfr[k1]-dFTdAlbi[k1*nvert+k2]*psfi[k1]; dFTdAlbi[k1*nvert+k2]=dFTdAlbi[k1*nvert+k2]*psfr[k1]+temp*psfi[k1]; } } /*Copy submatrices to the final matrix. This is a temporary solution. Streamline this to avoid unnecessary copying * FTdv is is 2*ntpoints x 3*dn+3+2*nao matrix */ if(UseWeight==1) { mult_with_cons(FTdxr,oind,nvertf,W); mult_with_cons(FTdxi,oind,nvertf,W); mult_with_cons(FTdyr,oind,nvertf,W); mult_with_cons(FTdyi,oind,nvertf,W); mult_with_cons(FTdzr,oind,nvertf,W); mult_with_cons(FTdzi,oind,nvertf,W); mult_with_cons(FTdAr,oind,3,W); mult_with_cons(FTdAi,oind,3,W); mult_with_cons(FTdoffr,oind,2,W); mult_with_cons(FTdoffi,oind,2,W); mult_with_cons(FTr,oind,1,W); mult_with_cons(FTi,oind,1,W); if(INI_FIT_AO_ALBEDO) { mult_with_cons(dFTdAlbr,oind,nvert,W); mult_with_cons(dFTdAlbi,oind,nvert,W); } } if(UseScale==1) { mult_with_cons(FTdxr,oind,nvertf,Scale); mult_with_cons(FTdxi,oind,nvertf,Scale); mult_with_cons(FTdyr,oind,nvertf,Scale); mult_with_cons(FTdyi,oind,nvertf,Scale); mult_with_cons(FTdzr,oind,nvertf,Scale); mult_with_cons(FTdzi,oind,nvertf,Scale); mult_with_cons(FTdAr,oind,3,Scale); mult_with_cons(FTdAi,oind,3,Scale); mult_with_cons(FTdoffr,oind,2,Scale); mult_with_cons(FTdoffi,oind,2,Scale); if(INI_FIT_AO_ALBEDO) { mult_with_cons(dFTdAlbr,oind,nvert,Scale); mult_with_cons(dFTdAlbi,oind,nvert,Scale); } //derivatives wrt Scale set_submatrix(FTdS,2*ntpoints,nao,FTr,oind,1,cind,obsind); set_submatrix(FTdS,2*ntpoints,nao,FTi,oind,1,cind+ntpoints,obsind); } free(FTr); free(FTi); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdxr,oind,nvertf,cind,0); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdxi,oind,nvertf,cind+ntpoints,0); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdyr,oind,nvertf,cind,nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdyi,oind,nvertf,cind+ntpoints,nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdzr,oind,nvertf,cind,2*nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdzi,oind,nvertf,cind+ntpoints,2*nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdAr,oind,3,cind,3*nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdAi,oind,3,cind+ntpoints,3*nvertf); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdoffr,oind,2,cind,3*nvertf+3+2*obsind); set_submatrix(FTdv,2*ntpoints,3*dn+3+2*nao,FTdoffi,oind,2,cind+ntpoints,3*nvertf+3+2*obsind); //If albedo is set if(INI_FIT_AO_ALBEDO) { set_submatrix(dA,2*ntpoints,nvert,dFTdAlbr,oind,nvert,cind,0); set_submatrix(dA,2*ntpoints,nvert,dFTdAlbi,oind,nvert,cind+ntpoints,0); } free(FTdxr); free(FTdxi); free(FTdyr); free(FTdyi); free(FTdzr); free(FTdzi); free(FTdAr); free(FTdAi); free(FTdoffr); free(FTdoffi); if(INI_FIT_AO_ALBEDO) { free(dFTdAlbr); free(dFTdAlbi); } } free(cumpoints); } /* void main() { // int tlist[]={1,2,3, // 1,3,4, // 2,4,3, // 1,2,4}; //4 facets // double vlist[]={0.0,-2.0,0.0 // ,0.5,0.0,-1.0, // 0.0,1.0,1.0, // -3,1,4}; // // int nvert=4; // int nfac=4; int *tlist; double *vlist; int nfac,nvert; char file[]="mshape.txt"; read_shape(file,&tlist,&vlist,&nfac,&nvert,0); int nobs[]={29,29,29}; int nao=3; int ntpoints=3*29; //double E[]={1,0,0}; double E2[]={1,0.1,0.1}; double E[9]; E[0]=1; E[1]=0; E[2]=0; E[6]=1; E[7]=0; E[8]=0; double norm=NORM(E2); //printf("norm: %f\n",norm); for(int j=0;j<3;j++) E[j+3]=E2[j]/norm; double E0[]={1,0,0,1,0,0,1,0,0}; double TIME[]={0.1,0.2,-0.1}; double distance[]={0.00137879506,0.00137879506,0.00137879506}; double scale[]={1,1,1}; double up[]={0,0,1,0,0,1,0,0,1}; double *datar=calloc(29,sizeof(double)); double *datai=calloc(29,sizeof(double)); double freqx[]={-1.0000, -0.9300, -0.8600, -0.7900, -0.7200, -0.6500, -0.5800, -0.5100, -0.4400, -0.3700, -0.3000, -0.2300, -0.1600, -0.0900, -0.0200, 0.0500, 0.1200, 0.1900, 0.2600, 0.3300, 0.4000, 0.4700, 0.5400, 0.6100, 0.6800, 0.7500, 0.8200, 0.8900, 0.9600}; double freqy[]={1.2900, 1.2200, 1.1500, 1.0800, 1.0100, 0.9400, 0.8700, 0.8000, 0.7300, 0.6600, 0.5900, 0.5200, 0.4500, 0.3800, 0.3100, 0.2400, 0.1700, 0.1000, 0.0300, -0.0400, -0.1100, -0.1800, -0.2500, -0.3200, -0.3900, -0.4600, -0.5300, -0.6000, -0.6700, }; double freqy2[]={-0.3,0.05}; double freqy3[]={-0.5,-0.1}; double freqx2[]={0.1,0.15}; double angles[]={0.1,0.3,30,0}; double offset[]={0.1,0.2,0.5,-0.1,0,-0.3}; double D[]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1}; double psf[]={0.5377,1.8339,-2.2588, 0.8622 ,0.3188 , -1.3077, -0.4336, 0.3426 , 3.5784, 2.7694, -1.3499, 3.0349, 0.7254, -0.0631 , 0.7147, -0.2050, -0.1241, 1.4897 , 1.4090, 1.4172, 0.6715 , -1.2075, 0.7172 , 1.6302, 0.4889 , 1.0347, 0.7269, -0.3034, 0.2939}; double *Weight; double *FT,*FTdv; FT=calloc(2*ntpoints,sizeof(double)); FTdv=calloc(2*ntpoints*(3*nvert+2*nao+3),sizeof(double)); AOstruct AO; AO.nao=3; AO.nobs=nobs; AO.datar=calloc(nao,sizeof(double*)); AO.datai=calloc(nao,sizeof(double*)); AO.freqx=calloc(nao,sizeof(double*)); AO.freqy=calloc(nao,sizeof(double*)); AO.psfi=calloc(nao,sizeof(double*)); AO.psfr=calloc(nao,sizeof(double*)); AO.datar[0]=datar; AO.datai[0]=datai; AO.freqx[0]=freqx; AO.freqy[0]=freqy; AO.datar[1]=datar; AO.datai[1]=datai; AO.freqx[1]=freqx; AO.freqy[1]=freqy; AO.datar[2]=datar; AO.datai[2]=datai; AO.freqx[2]=freqx; AO.freqy[2]=freqy; AO.psfr[0]=psf; AO.psfi[0]=psf; AO.psfr[1]=psf; AO.psfi[1]=psf; AO.psfi[2]=psf; AO.psfr[2]=psf; AO.E=E; AO.E0=E0; AO.TIME=TIME; AO.distance=distance; AO.scalex=scale; AO.scaley=scale; AO.up=up; Calculate_AOs(tlist,vlist,nfac,nvert,angles,&AO,offset,NULL,nvert,nvert,Weight,NULL,FT,FTdv,NULL,1); //print_matrix(FT,1,2*ntpoints); //print_matrix(FTdv,2*ntpoints,3*nvert+2*nao+3); write_matrix_file("/tmp/FT.txt",FT,2*ntpoints,1); write_matrix_file("/tmp/FTdv.txt",FTdv,2*ntpoints,3*nvert+2*nao+3); free(FT); free(FTdv); free(AO.datar); free(AO.datai); free(AO.freqx); free(AO.freqy); } */
DenseMatrix.h
//================================================================================================= /*! // \file blaze/math/smp/openmp/DenseMatrix.h // \brief Header file for the OpenMP-based dense matrix SMP implementation // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) 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. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_SMP_OPENMP_DENSEMATRIX_H_ #define _BLAZE_MATH_SMP_OPENMP_DENSEMATRIX_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <omp.h> #include <blaze/math/Aliases.h> #include <blaze/math/AlignmentFlag.h> #include <blaze/math/constraints/SMPAssignable.h> #include <blaze/math/expressions/DenseMatrix.h> #include <blaze/math/expressions/SparseMatrix.h> #include <blaze/math/simd/SIMDTrait.h> #include <blaze/math/smp/ParallelSection.h> #include <blaze/math/smp/SerialSection.h> #include <blaze/math/smp/ThreadMapping.h> #include <blaze/math/StorageOrder.h> #include <blaze/math/typetraits/IsDenseMatrix.h> #include <blaze/math/typetraits/IsSIMDCombinable.h> #include <blaze/math/typetraits/IsSMPAssignable.h> #include <blaze/math/views/Submatrix.h> #include <blaze/system/SMP.h> #include <blaze/util/algorithms/Min.h> #include <blaze/util/Assert.h> #include <blaze/util/EnableIf.h> #include <blaze/util/FunctionTrace.h> #include <blaze/util/mpl/And.h> #include <blaze/util/mpl/Not.h> #include <blaze/util/mpl/Or.h> #include <blaze/util/StaticAssert.h> #include <blaze/util/Types.h> namespace blaze { //================================================================================================= // // PLAIN ASSIGNMENT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP assignment of a dense matrix to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side dense matrix to be assigned. // \return void // // This function is the backend implementation of the OpenMP-based SMP assignment of a dense // matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side dense matrix , bool SO2 > // Storage order of the right-hand side dense matrix void smpAssign_backend( DenseMatrix<MT1,SO1>& lhs, const DenseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); using ET1 = ElementType_<MT1>; using ET2 = ElementType_<MT2>; constexpr bool simdEnabled( MT1::simdEnabled && MT2::simdEnabled && IsSIMDCombinable<ET1,ET2>::value ); constexpr size_t SIMDSIZE( SIMDTrait< ElementType_<MT1> >::size ); const bool lhsAligned( (~lhs).isAligned() ); const bool rhsAligned( (~rhs).isAligned() ); const int threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t equalShare1( (~rhs).rows() / threadmap.first + addon1 ); const size_t rest1 ( equalShare1 & ( SIMDSIZE - 1UL ) ); const size_t rowsPerThread( ( simdEnabled && rest1 )?( equalShare1 - rest1 + SIMDSIZE ):( equalShare1 ) ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t equalShare2( (~rhs).columns() / threadmap.second + addon2 ); const size_t rest2 ( equalShare2 & ( SIMDSIZE - 1UL ) ); const size_t colsPerThread( ( simdEnabled && rest2 )?( equalShare2 - rest2 + SIMDSIZE ):( equalShare2 ) ); #pragma omp for schedule(dynamic,1) nowait for( int i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~rhs).rows() - row ) ); const size_t n( min( colsPerThread, (~rhs).columns() - column ) ); if( simdEnabled && lhsAligned && rhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); assign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && lhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); assign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && rhsAligned ) { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); assign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); assign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP assignment of a sparse matrix to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side sparse matrix to be assigned. // \return void // // This function is the backend implementation of the OpenMP-based SMP assignment of a sparse // matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side sparse matrix , bool SO2 > // Storage order of the right-hand side sparse matrix void smpAssign_backend( DenseMatrix<MT1,SO1>& lhs, const SparseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); const size_t threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t rowsPerThread( (~rhs).rows() / threadmap.first + addon1 ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t colsPerThread( (~rhs).columns() / threadmap.second + addon2 ); #pragma omp for schedule(dynamic,1) nowait for( size_t i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~lhs).rows() - row ) ); const size_t n( min( colsPerThread, (~lhs).columns() - column ) ); auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); assign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default implementation of the OpenMP-based SMP assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be assigned. // \return void // // This function implements the default OpenMP-based SMP assignment to a dense matrix. Due to // the explicit application of the SFINAE principle, this function can only be selected by the // compiler in case both operands are SMP-assignable and the element types of both operands are // not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1> , Or< Not< IsSMPAssignable<MT1> > , Not< IsSMPAssignable<MT2> > > > > smpAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); assign( ~lhs, ~rhs ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Implementation of the OpenMP-based SMP assignment to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be assigned. // \return void // // This function implements the OpenMP-based SMP assignment to a dense matrix. Due to the // explicit application of the SFINAE principle, this function can only be selected by the // compiler in case both operands are SMP-assignable and the element types of both operands // are not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1>, IsSMPAssignable<MT1>, IsSMPAssignable<MT2> > > smpAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT1> ); BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT2> ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); BLAZE_PARALLEL_SECTION { if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) { assign( ~lhs, ~rhs ); } else { #pragma omp parallel shared( lhs, rhs ) smpAssign_backend( ~lhs, ~rhs ); } } } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // ADDITION ASSIGNMENT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP addition assignment of a dense matrix to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side dense matrix to be added. // \return void // // This function is the backend implementation of the OpenMP-based SMP addition assignment of a // dense matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side dense matrix , bool SO2 > // Storage order of the right-hand side dense matrix void smpAddAssign_backend( DenseMatrix<MT1,SO1>& lhs, const DenseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); using ET1 = ElementType_<MT1>; using ET2 = ElementType_<MT2>; constexpr bool simdEnabled( MT1::simdEnabled && MT2::simdEnabled && IsSIMDCombinable<ET1,ET2>::value ); constexpr size_t SIMDSIZE( SIMDTrait< ElementType_<MT1> >::size ); const bool lhsAligned( (~lhs).isAligned() ); const bool rhsAligned( (~rhs).isAligned() ); const int threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t equalShare1( (~rhs).rows() / threadmap.first + addon1 ); const size_t rest1 ( equalShare1 & ( SIMDSIZE - 1UL ) ); const size_t rowsPerThread( ( simdEnabled && rest1 )?( equalShare1 - rest1 + SIMDSIZE ):( equalShare1 ) ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t equalShare2( (~rhs).columns() / threadmap.second + addon2 ); const size_t rest2 ( equalShare2 & ( SIMDSIZE - 1UL ) ); const size_t colsPerThread( ( simdEnabled && rest2 )?( equalShare2 - rest2 + SIMDSIZE ):( equalShare2 ) ); #pragma omp for schedule(dynamic,1) nowait for( int i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~rhs).rows() - row ) ); const size_t n( min( colsPerThread, (~rhs).columns() - column ) ); if( simdEnabled && lhsAligned && rhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); addAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && lhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); addAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && rhsAligned ) { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); addAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); addAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP addition assignment of a sparse matrix to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side sparse matrix to be added. // \return void // // This function is the backend implementation of the OpenMP-based SMP addition assignment of a // sparse matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side sparse matrix , bool SO2 > // Storage order of the right-hand side sparse matrix void smpAddAssign_backend( DenseMatrix<MT1,SO1>& lhs, const SparseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); const size_t threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t rowsPerThread( (~rhs).rows() / threadmap.first + addon1 ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t colsPerThread( (~rhs).columns() / threadmap.second + addon2 ); #pragma omp for schedule(dynamic,1) nowait for( size_t i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~lhs).rows() - row ) ); const size_t n( min( colsPerThread, (~lhs).columns() - column ) ); auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); addAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default implementation of the OpenMP-based SMP addition assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be added. // \return void // // This function implements the default OpenMP-based SMP addition assignment to a dense matrix. // Due to the explicit application of the SFINAE principle, this function can only be selected // by the compiler in case both operands are SMP-assignable and the element types of both operands // are not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1> , Or< Not< IsSMPAssignable<MT1> > , Not< IsSMPAssignable<MT2> > > > > smpAddAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); addAssign( ~lhs, ~rhs ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Implementation of the OpenMP-based SMP addition assignment to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be added. // \return void // // This function implements the OpenMP-based SMP addition assignment to a dense matrix. Due to // the explicit application of the SFINAE principle, this function can only be selected by the // compiler in case both operands are SMP-assignable and the element types of both operands are // not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1>, IsSMPAssignable<MT1>, IsSMPAssignable<MT2> > > smpAddAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT1> ); BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT2> ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); BLAZE_PARALLEL_SECTION { if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) { addAssign( ~lhs, ~rhs ); } else { #pragma omp parallel shared( lhs, rhs ) smpAddAssign_backend( ~lhs, ~rhs ); } } } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // SUBTRACTION ASSIGNMENT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP subtraction assignment of a dense matrix to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side dense matrix to be subtracted. // \return void // // This function is the backend implementation of the OpenMP-based SMP subtraction assignment // of a dense matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side dense matrix , bool SO2 > // Storage order of the right-hand side dense matrix void smpSubAssign_backend( DenseMatrix<MT1,SO1>& lhs, const DenseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); using ET1 = ElementType_<MT1>; using ET2 = ElementType_<MT2>; constexpr bool simdEnabled( MT1::simdEnabled && MT2::simdEnabled && IsSIMDCombinable<ET1,ET2>::value ); constexpr size_t SIMDSIZE( SIMDTrait< ElementType_<MT1> >::size ); const bool lhsAligned( (~lhs).isAligned() ); const bool rhsAligned( (~rhs).isAligned() ); const int threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t equalShare1( (~rhs).rows() / threadmap.first + addon1 ); const size_t rest1 ( equalShare1 & ( SIMDSIZE - 1UL ) ); const size_t rowsPerThread( ( simdEnabled && rest1 )?( equalShare1 - rest1 + SIMDSIZE ):( equalShare1 ) ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t equalShare2( (~rhs).columns() / threadmap.second + addon2 ); const size_t rest2 ( equalShare2 & ( SIMDSIZE - 1UL ) ); const size_t colsPerThread( ( simdEnabled && rest2 )?( equalShare2 - rest2 + SIMDSIZE ):( equalShare2 ) ); #pragma omp for schedule(dynamic,1) nowait for( int i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~rhs).rows() - row ) ); const size_t n( min( colsPerThread, (~rhs).columns() - column ) ); if( simdEnabled && lhsAligned && rhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); subAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && lhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); subAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && rhsAligned ) { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); subAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); subAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP subtraction assignment of a sparse matrix to a dense // matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side sparse matrix to be subtracted. // \return void // // This function is the backend implementation of the OpenMP-based SMP subtraction assignment // of a sparse matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side sparse matrix , bool SO2 > // Storage order of the right-hand side sparse matrix void smpSubAssign_backend( DenseMatrix<MT1,SO1>& lhs, const SparseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); const size_t threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t rowsPerThread( (~rhs).rows() / threadmap.first + addon1 ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t colsPerThread( (~rhs).columns() / threadmap.second + addon2 ); #pragma omp for schedule(dynamic,1) nowait for( size_t i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~lhs).rows() - row ) ); const size_t n( min( colsPerThread, (~lhs).columns() - column ) ); auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); subAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default implementation of the OpenMP-based SMP subtracction assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be subtracted. // \return void // // This function implements the default OpenMP-based SMP subtraction assignment to a dense matrix. // Due to the explicit application of the SFINAE principle, this function can only be selected by // the compiler in case both operands are SMP-assignable and the element types of both operands // are not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1> , Or< Not< IsSMPAssignable<MT1> > , Not< IsSMPAssignable<MT2> > > > > smpSubAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); subAssign( ~lhs, ~rhs ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Implementation of the OpenMP-based SMP subtracction assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be subtracted. // \return void // // This function implements the default OpenMP-based SMP subtraction assignment of a matrix to a // dense matrix. Due to the explicit application of the SFINAE principle, this function can only // be selected by the compiler in case both operands are SMP-assignable and the element types of // both operands are not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1>, IsSMPAssignable<MT1>, IsSMPAssignable<MT2> > > smpSubAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT1> ); BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT2> ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); BLAZE_PARALLEL_SECTION { if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) { subAssign( ~lhs, ~rhs ); } else { #pragma omp parallel shared( lhs, rhs ) smpSubAssign_backend( ~lhs, ~rhs ); } } } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // SCHUR PRODUCT ASSIGNMENT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP Schur product assignment of a dense matrix to a dense // matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side dense matrix for the Schur product. // \return void // // This function is the backend implementation of the OpenMP-based SMP Schur product assignment // of a dense matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side dense matrix , bool SO2 > // Storage order of the right-hand side dense matrix void smpSchurAssign_backend( DenseMatrix<MT1,SO1>& lhs, const DenseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); using ET1 = ElementType_<MT1>; using ET2 = ElementType_<MT2>; constexpr bool simdEnabled( MT1::simdEnabled && MT2::simdEnabled && IsSIMDCombinable<ET1,ET2>::value ); constexpr size_t SIMDSIZE( SIMDTrait< ElementType_<MT1> >::size ); const bool lhsAligned( (~lhs).isAligned() ); const bool rhsAligned( (~rhs).isAligned() ); const int threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t equalShare1( (~rhs).rows() / threadmap.first + addon1 ); const size_t rest1 ( equalShare1 & ( SIMDSIZE - 1UL ) ); const size_t rowsPerThread( ( simdEnabled && rest1 )?( equalShare1 - rest1 + SIMDSIZE ):( equalShare1 ) ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t equalShare2( (~rhs).columns() / threadmap.second + addon2 ); const size_t rest2 ( equalShare2 & ( SIMDSIZE - 1UL ) ); const size_t colsPerThread( ( simdEnabled && rest2 )?( equalShare2 - rest2 + SIMDSIZE ):( equalShare2 ) ); #pragma omp for schedule(dynamic,1) nowait for( int i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~rhs).rows() - row ) ); const size_t n( min( colsPerThread, (~rhs).columns() - column ) ); if( simdEnabled && lhsAligned && rhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); schurAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && lhsAligned ) { auto target( submatrix<aligned>( ~lhs, row, column, m, n ) ); schurAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } else if( simdEnabled && rhsAligned ) { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); schurAssign( target, submatrix<aligned>( ~rhs, row, column, m, n ) ); } else { auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); schurAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Backend of the OpenMP-based SMP Schur product assignment of a sparse matrix to a dense // matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side sparse matrix for the Schur product. // \return void // // This function is the backend implementation of the OpenMP-based SMP Schur product assignment // of a sparse matrix to a dense matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side sparse matrix , bool SO2 > // Storage order of the right-hand side sparse matrix void smpSchurAssign_backend( DenseMatrix<MT1,SO1>& lhs, const SparseMatrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( isParallelSectionActive(), "Invalid call outside a parallel section" ); const size_t threads( omp_get_num_threads() ); const ThreadMapping threadmap( createThreadMapping( threads, ~rhs ) ); const size_t addon1 ( ( ( (~rhs).rows() % threadmap.first ) != 0UL )? 1UL : 0UL ); const size_t rowsPerThread( (~rhs).rows() / threadmap.first + addon1 ); const size_t addon2 ( ( ( (~rhs).columns() % threadmap.second ) != 0UL )? 1UL : 0UL ); const size_t colsPerThread( (~rhs).columns() / threadmap.second + addon2 ); #pragma omp for schedule(dynamic,1) nowait for( size_t i=0; i<threads; ++i ) { const size_t row ( ( i / threadmap.second ) * rowsPerThread ); const size_t column( ( i % threadmap.second ) * colsPerThread ); if( row >= (~rhs).rows() || column >= (~rhs).columns() ) continue; const size_t m( min( rowsPerThread, (~lhs).rows() - row ) ); const size_t n( min( colsPerThread, (~lhs).columns() - column ) ); auto target( submatrix<unaligned>( ~lhs, row, column, m, n ) ); schurAssign( target, submatrix<unaligned>( ~rhs, row, column, m, n ) ); } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default implementation of the OpenMP-based SMP Schur product assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix for the Schur product. // \return void // // This function implements the default OpenMP-based SMP Schur product assignment to a dense // matrix. Due to the explicit application of the SFINAE principle, this function can only be // selected by the compiler in case both operands are SMP-assignable and the element types of // both operands are not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1> , Or< Not< IsSMPAssignable<MT1> > , Not< IsSMPAssignable<MT2> > > > > smpSchurAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); schurAssign( ~lhs, ~rhs ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Implementation of the OpenMP-based SMP Schur product assignment to a dense matrix. // \ingroup math // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix for the Schur product. // \return void // // This function implements the OpenMP-based SMP Schur product assignment to a dense matrix. Due // to the explicit application of the SFINAE principle, this function can only be selected by the // compiler in case both operands are SMP-assignable and the element types of both operands are // not SMP-assignable.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side dense matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< And< IsDenseMatrix<MT1>, IsSMPAssignable<MT1>, IsSMPAssignable<MT2> > > smpSchurAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT1> ); BLAZE_CONSTRAINT_MUST_NOT_BE_SMP_ASSIGNABLE( ElementType_<MT2> ); BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); BLAZE_PARALLEL_SECTION { if( isSerialSectionActive() || !(~rhs).canSMPAssign() ) { schurAssign( ~lhs, ~rhs ); } else { #pragma omp parallel shared( lhs, rhs ) smpSchurAssign_backend( ~lhs, ~rhs ); } } } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // MULTIPLICATION ASSIGNMENT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Default implementation of the OpenMP-based SMP multiplication assignment to a dense matrix. // \ingroup smp // // \param lhs The target left-hand side dense matrix. // \param rhs The right-hand side matrix to be multiplied. // \return void // // This function implements the default OpenMP-based SMP multiplication assignment to a dense // matrix.\n // This function must \b NOT be called explicitly! It is used internally for the performance // optimized evaluation of expression templates. Calling this function explicitly might result // in erroneous results and/or in compilation errors. Instead of using this function use the // assignment operator. */ template< typename MT1 // Type of the left-hand side dense matrix , bool SO1 // Storage order of the left-hand side matrix , typename MT2 // Type of the right-hand side matrix , bool SO2 > // Storage order of the right-hand side matrix inline EnableIf_< IsDenseMatrix<MT1> > smpMultAssign( Matrix<MT1,SO1>& lhs, const Matrix<MT2,SO2>& rhs ) { BLAZE_FUNCTION_TRACE; BLAZE_INTERNAL_ASSERT( (~lhs).rows() == (~rhs).rows() , "Invalid number of rows" ); BLAZE_INTERNAL_ASSERT( (~lhs).columns() == (~rhs).columns(), "Invalid number of columns" ); multAssign( ~lhs, ~rhs ); } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // COMPILE TIME CONSTRAINT // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ namespace { BLAZE_STATIC_ASSERT( BLAZE_OPENMP_PARALLEL_MODE ); } /*! \endcond */ //************************************************************************************************* } // namespace blaze #endif
omp_smithW-v4-parallel-serial.c
/********************************************************************************* * Smith–Waterman algorithm * Purpose: Local alignment of nucleotide or protein sequences * Authors: Daniel Holanda, Hanoch Griner, Taynara Pinheiro * * Compilation: gcc omp_smithW.c -o omp_smithW -fopenmp -DDEBUG // debugging mode * gcc omp_smithW.c -O3 -o omp_smithW -fopenmp // production run * Execution: ./omp_smithW <number_of_col> <number_of_rows> * * Updated by C. Liao, Jan 2nd, 2019 *********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <time.h> #include <assert.h> #include <stdbool.h> // C99 does not support the boolean data type #include "parameters.h" /*-------------------------------------------------------------------- * Text Tweaks */ #define RESET "\033[0m" #define BOLDRED "\033[1m\033[31m" /* Bold Red */ /* End of text tweaks */ /*-------------------------------------------------------------------- * Constants */ #define PATH -1 #define NONE 0 #define UP 1 #define LEFT 2 #define DIAGONAL 3 /* End of constants */ /*-------------------------------------------------------------------- * Helpers */ #define min(x, y) (((x) < (y)) ? (x) : (y)) #define max(a,b) ((a) > (b) ? a : b) // #define DEBUG /* End of Helpers */ /*-------------------------------------------------------------------- * Functions Prototypes */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos); // without omp critical: how to conditionalize it? void similarityScore2(long long int i, long long int j, int* H, int* P, long long int* maxPos); int matchMissmatchScore(long long int i, long long int j); void backtrack(int* P, long long int maxPos); void printMatrix(int* matrix); void printPredecessorMatrix(int* matrix); void generate(void); long long int nElement(long long int i); void calcFirstDiagElement(long long int i, long long int *si, long long int *sj); /* End of prototypes */ /*-------------------------------------------------------------------- * Global Variables */ bool useBuiltInData=true; //Defines size of strings to be compared long long int m = 8 ; //Columns - Size of string a long long int n = 9; //Lines - Size of string b // the generated scoring matrix's size is m++ and n++ later to have the first row/column as 0s. //Defines scores int matchScore = 3; int missmatchScore = -3; int gapScore = -2; //Strings over the Alphabet Sigma char *a, *b; /* End of global variables */ /*-------------------------------------------------------------------- * Function: main */ int main(int argc, char* argv[]) { // thread_count is no longer used int thread_count; if (argc==3) { m = strtoll(argv[1], NULL, 10); n = strtoll(argv[2], NULL, 10); useBuiltInData = false; } //#ifdef DEBUG if (useBuiltInData) printf ("Using built-in data for testing ..\n"); printf("Problem size: Matrix[%lld][%lld], FACTOR=%d CUTOFF=%d\n", n, m, FACTOR, CUTOFF); //#endif //Allocates a and b a = (char*) malloc(m * sizeof(char)); b = (char*) malloc(n * sizeof(char)); //Because now we have zeros m++; n++; //Allocates similarity matrix H int *H; H = (int *) calloc(m * n, sizeof(int)); //Allocates predecessor matrix P int *P; P = (int *)calloc(m * n, sizeof(int)); if (useBuiltInData) { //Uncomment this to test the sequence available at //http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 // OBS: m=11 n=7 // a[0] = 'C'; // a[1] = 'G'; // a[2] = 'T'; // a[3] = 'G'; // a[4] = 'A'; // a[5] = 'A'; // a[6] = 'T'; // a[7] = 'T'; // a[8] = 'C'; // a[9] = 'A'; // a[10] = 'T'; // b[0] = 'G'; // b[1] = 'A'; // b[2] = 'C'; // b[3] = 'T'; // b[4] = 'T'; // b[5] = 'A'; // b[6] = 'C'; // https://en.wikipedia.org/wiki/Smith%E2%80%93Waterman_algorithm#Example // Using the wiki example to verify the results b[0] = 'G'; b[1] = 'G'; b[2] = 'T'; b[3] = 'T'; b[4] = 'G'; b[5] = 'A'; b[6] = 'C'; b[7] = 'T'; b[8] = 'A'; a[0] = 'T'; a[1] = 'G'; a[2] = 'T'; a[3] = 'T'; a[4] = 'A'; a[5] = 'C'; a[6] = 'G'; a[7] = 'G'; } else { //Gen random arrays a and b generate(); } //Start position for backtrack long long int maxPos = 0; //Calculates the similarity matrix long long int i, j; // The way to generate all wavefront is to go through the top edge elements // starting from the left top of the matrix, go to the bottom top -> down, then left->right // total top edge element count = dim1_size + dim2_size -1 //Because now we have zeros ((m-1) + (n-1) - 1) long long int nDiag = m + n - 3; #ifdef DEBUG printf("nDiag=%d\n", nDiag); printf("Number of wavefront lines and their first element positions:\n"); #endif #pragma omp parallel { #pragma omp master { thread_count = omp_get_num_threads(); printf ("Using %d out of max %d threads...", thread_count, omp_get_max_threads()); } } //Gets Initial time double initialTime = omp_get_wtime(); // #pragma omp parallel default(none) shared(H, P, maxPos, nDiag, j) private(i) { for (i = 1; i <= nDiag; ++i) // start from 1 since 0 is the boundary padding { long long int nEle, si, sj; nEle = nElement(i); calcFirstDiagElement(i, &si, &sj); if (nEle>=CUTOFF) { #pragma omp parallel for private(j) shared (nEle, si, sj, H, P, maxPos) for (j = 0; j < nEle; ++j) { // going upwards : anti-diagnol direction long long int ai = si - j ; // going up vertically long long int aj = sj + j; // going right in horizontal similarityScore(ai, aj, H, P, &maxPos); // a critical section is used inside } } else { // serial version, totally avoid parallel region creation. for (j = 0; j < nEle; ++j) { // going upwards : anti-diagnol direction long long int ai = si - j ; // going up vertically long long int aj = sj + j; // going right in horizontal similarityScore2(ai, aj, H, P, &maxPos); // a specialized version without a critical section used inside } } } // for end nDiag } // end omp parallel double finalTime = omp_get_wtime(); printf("\nElapsed time for scoring matrix computation: %f\n", finalTime - initialTime); initialTime = omp_get_wtime(); backtrack(P, maxPos); finalTime = omp_get_wtime(); //Gets backtrack time finalTime = omp_get_wtime(); printf("Elapsed time for backtracking: %f\n", finalTime - initialTime); if (useBuiltInData) { printf ("Verifying results using the builtinIn data: %s\n", (H[n*m-1]==7)?"true":"false"); assert (H[n*m-1]==7); } #ifdef DEBUG printf("\nSimilarity Matrix:\n"); printMatrix(H); printf("\nPredecessor Matrix:\n"); printPredecessorMatrix(P); #endif //Frees similarity matrixes free(H); free(P); //Frees input arrays free(a); free(b); return 0; } /* End of main */ /*-------------------------------------------------------------------- * Function: nElement * Purpose: Calculate the number of i-diagonal's elements * i value range 1 to nDiag. we inclulde the upper bound value. 0 is for the padded wavefront, which is ignored. */ long long int nElement(long long int i) { if (i < m && i < n) { // smaller than both directions //Number of elements in the diagonal is increasing return i; } else if (i < max(m, n)) { // smaller than only one direction //Number of elements in the diagonal is stable long int min = min(m, n); // the longer direction has the edge elements, the number is the smaller direction's size return min - 1; } else { //Number of elements in the diagonal is decreasing long int min = min(m, n); return 2 * min - i + llabs(m - n) - 2; } } /*-------------------------------------------------------------------- * Function: calcElement: expect valid i value is from 1 to nDiag. since the first one is 0 padding * Purpose: Calculate the position of (si, sj)-element * n rows, m columns: we sweep the matrix on the left edge then bottom edge to get the wavefront */ void calcFirstDiagElement(long long int i, long long int *si, long long int *sj) { // Calculate the first element of diagonal if (i < n) { // smaller than row count *si = i; *sj = 1; // start from the j==1 since j==0 is the padding } else { // now we sweep horizontally at the bottom of the matrix *si = n - 1; // i is fixed *sj = i - n + 2; // j position is the nDiag (id -n) +1 +1 // first +1 } } /* // understanding the calculation by an example n =6 // row m =2 // col padded scoring matrix n=7 m=3 0 1 2 ------- 0 x x x 1 x x x 2 x x x 3 x x x 4 x x x 5 x x x 6 x x x We should peel off top row and left column since they are the padding the remaining 6x2 sub matrix is what is interesting for us Now find the number of wavefront lines and their first element's position in the scoring matrix total diagnol frontwave = (n-1) + (m-1) -1 // submatrix row+column -1 We use the left most element in each wavefront line as its first element. Then we have the first elements like (1,1), (2,1) (3,1) .. (6,1) (6,2) */ /*-------------------------------------------------------------------- * Function: SimilarityScore * Purpose: Calculate value of scoring matrix element H(i,j) : the maximum Similarity-Score H(i,j) * int *P; the predecessor array,storing which of the three elements is picked with max value */ void similarityScore(long long int i, long long int j, int* H, int* P, long long int* maxPos) { int up, left, diag; //Stores index of element long long int index = m * i + j; //Get element above up = H[index - m] + gapScore; //Get element on the left left = H[index - 1] + gapScore; //Get element on the diagonal diag = H[index - m - 1] + matchMissmatchScore(i, j); //Calculates the maximum int max = NONE; int pred = NONE; /* === Matrix === * a[0] ... a[n] * b[0] * ... * b[n] * * generate 'a' from 'b', if '←' insert e '↑' remove * a=GAATTCA * b=GACTT-A * * generate 'b' from 'a', if '←' insert e '↑' remove * b=GACTT-A * a=GAATTCA */ if (diag > max) { //same letter ↖ max = diag; pred = DIAGONAL; } if (up > max) { //remove letter ↑ max = up; pred = UP; } if (left > max) { //insert letter ← max = left; pred = LEFT; } //Inserts the value in the similarity and predecessor matrixes H[index] = max; P[index] = pred; //Updates maximum score to be used as seed on backtrack if (max > H[*maxPos]) { #pragma omp critical *maxPos = index; } } /* End of similarityScore */ void similarityScore2(long long int i, long long int j, int* H, int* P, long long int* maxPos) { int up, left, diag; //Stores index of element long long int index = m * i + j; //Get element above up = H[index - m] + gapScore; //Get element on the left left = H[index - 1] + gapScore; //Get element on the diagonal diag = H[index - m - 1] + matchMissmatchScore(i, j); //Calculates the maximum int max = NONE; int pred = NONE; /* === Matrix === * a[0] ... a[n] * b[0] * ... * b[n] * * generate 'a' from 'b', if '←' insert e '↑' remove * a=GAATTCA * b=GACTT-A * * generate 'b' from 'a', if '←' insert e '↑' remove * b=GACTT-A * a=GAATTCA */ if (diag > max) { //same letter ↖ max = diag; pred = DIAGONAL; } if (up > max) { //remove letter ↑ max = up; pred = UP; } if (left > max) { //insert letter ← max = left; pred = LEFT; } //Inserts the value in the similarity and predecessor matrixes H[index] = max; P[index] = pred; //Updates maximum score to be used as seed on backtrack if (max > H[*maxPos]) { *maxPos = index; } } /* End of similarityScore2 */ /*-------------------------------------------------------------------- * Function: matchMissmatchScore * Purpose: Similarity function on the alphabet for match/missmatch */ int matchMissmatchScore(long long int i, long long int j) { if (a[j - 1] == b[i - 1]) return matchScore; else return missmatchScore; } /* End of matchMissmatchScore */ /*-------------------------------------------------------------------- * Function: backtrack * Purpose: Modify matrix to print, path change from value to PATH */ void backtrack(int* P, long long int maxPos) { //hold maxPos value long long int predPos; //backtrack from maxPos to startPos = 0 do { if (P[maxPos] == DIAGONAL) predPos = maxPos - m - 1; else if (P[maxPos] == UP) predPos = maxPos - m; else if (P[maxPos] == LEFT) predPos = maxPos - 1; P[maxPos] *= PATH; maxPos = predPos; } while (P[maxPos] != NONE); } /* End of backtrack */ /*-------------------------------------------------------------------- * Function: printMatrix * Purpose: Print Matrix */ void printMatrix(int* matrix) { long long int i, j; printf("-\t-\t"); for (j = 0; j < m-1; j++) { printf("%c\t", a[j]); } printf("\n-\t"); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c\t", b[i-1]); printf("%d\t", matrix[m * i + j]); } printf("\n"); } } /* End of printMatrix */ /*-------------------------------------------------------------------- * Function: printPredecessorMatrix * Purpose: Print predecessor matrix */ void printPredecessorMatrix(int* matrix) { long long int i, j, index; printf(" "); for (j = 0; j < m-1; j++) { printf("%c ", a[j]); } printf("\n "); for (i = 0; i < n; i++) { //Lines for (j = 0; j < m; j++) { if (j==0 && i>0) printf("%c ", b[i-1]); index = m * i + j; if (matrix[index] < 0) { printf(BOLDRED); if (matrix[index] == -UP) printf("↑ "); else if (matrix[index] == -LEFT) printf("← "); else if (matrix[index] == -DIAGONAL) printf("↖ "); else printf("- "); printf(RESET); } else { if (matrix[index] == UP) printf("↑ "); else if (matrix[index] == LEFT) printf("← "); else if (matrix[index] == DIAGONAL) printf("↖ "); else printf("- "); } } printf("\n"); } } /* End of printPredecessorMatrix */ /*-------------------------------------------------------------------- * Function: generate * Purpose: Generate arrays a and b */ void generate() { //Random seed srand(time(NULL)); //Generates the values of a long long int i; for (i = 0; i < m; i++) { int aux = rand() % 4; if (aux == 0) a[i] = 'A'; else if (aux == 2) a[i] = 'C'; else if (aux == 3) a[i] = 'G'; else a[i] = 'T'; } //Generates the values of b for (i = 0; i < n; i++) { int aux = rand() % 4; if (aux == 0) b[i] = 'A'; else if (aux == 2) b[i] = 'C'; else if (aux == 3) b[i] = 'G'; else b[i] = 'T'; } } /* End of generate */ /*-------------------------------------------------------------------- * External References: * http://vlab.amrita.edu/?sub=3&brch=274&sim=1433&cnt=1 * http://pt.slideshare.net/avrilcoghlan/the-smith-waterman-algorithm * http://baba.sourceforge.net/ */
mysql_fmt_plug.c
/* MYSQL_half_fmt.c * * Copyright (c) 2008 by <earthquake at rycon.hu> * * John the ripper MYSQL-fast module * * * Note: The mysql hash's first 8byte is relevant, * the another ones depends on the first 8. Maybe * the passwords after 9-10character have collision * in the first 8byte, so we have to check the full * hash. * * Unbelievable good optimization by Péter Kasza * * http://rycon.hu/ * * OpenMP support and other assorted hacks by Solar Designer */ #if FMT_EXTERNS_H extern struct fmt_main fmt_MYSQL_fast; #elif FMT_REGISTERS_H john_register_one(&fmt_MYSQL_fast); #else #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef _OPENMP #include <omp.h> #define OMP_SCALE 81920 #endif #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "memdbg.h" #define FORMAT_LABEL "mysql" #define FORMAT_NAME "MySQL pre-4.1" #define ALGORITHM_NAME "32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define CIPHERTEXT_LENGTH 16 #define BINARY_SIZE 4 #define SALT_SIZE 0 #define BINARY_ALIGN sizeof(ARCH_WORD_32) #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 8 static struct fmt_tests tests[] = { // ciphertext, plaintext {"445ff82636a7ba59", "probe"}, {"60671c896665c3fa", "a"}, {"1acbed4a27b20da3", "hash"}, {"77ff75006118bab8", "hacker"}, {"1b38cd9c2f809809", "hacktivity2008"}, {"1b38cd9c2f809809", "hacktivity 2008"}, {"6fc81597422015a8", "johnmodule"}, {"30f098972cc8924d", "http://guh.nu"}, {"3fc56f6037218993", "Andrew Hintz"}, {"697a7de87c5390b2", "drew"}, {"1eb71cf460712b3e", "http://4tphi.net"}, {"28ff8d49159ffbaf", "http://violating.us"}, {"5d2e19393cc5ef67", "password"}, {"5030573512345671", ""}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_key)[BINARY_SIZE / 4]; 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_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); crypt_key = mem_alloc_tiny(sizeof(*crypt_key) * self->params.max_keys_per_crypt, MEM_ALIGN_CACHE); } static int valid(char* ciphertext, struct fmt_main *self) { unsigned int i; if (strlen(ciphertext) != CIPHERTEXT_LENGTH) return 0; for (i = 0; i < CIPHERTEXT_LENGTH; i++) if (atoi16[ARCH_INDEX(ciphertext[i])] > 15) return 0; return 1; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[CIPHERTEXT_LENGTH + 1]; memcpy(out, ciphertext, CIPHERTEXT_LENGTH); out[CIPHERTEXT_LENGTH] = 0; strlwr(out); return out; } static void *get_binary_size(char *ciphertext, int size) { /* maybe bigger than BINARY_SIZE for use from cmp_exact() */ static ARCH_WORD_32 buff_[8]; unsigned char *buff = (unsigned char *)buff_; unsigned int i; for (i = 0; i < size; i++) { #if ARCH_LITTLE_ENDIAN buff[(i & ~3U) | (3 - (i & 3))] = atoi16[ARCH_INDEX(ciphertext[i * 2])] * 16 + atoi16[ARCH_INDEX(ciphertext[i * 2 + 1])]; #else buff[i] = atoi16[ARCH_INDEX(ciphertext[i * 2])] * 16 + atoi16[ARCH_INDEX(ciphertext[i * 2 + 1])]; #endif } return buff; } static void *get_binary(char *ciphertext) { return get_binary_size(ciphertext, BINARY_SIZE); } static void set_key(char* key, int index) { strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH + 1); } static char* get_key(int index) { return saved_key[index]; } static int cmp_one(void* binary, int index) { return *(ARCH_WORD_32 *)binary == crypt_key[index][0]; } static int cmp_all(void* binary, int count) { int i; #ifdef _OPENMP int retval = 0; #pragma omp parallel for default(none) private(i) shared(count, binary, crypt_key, retval) for (i = 0; i < count; i++) if (*(ARCH_WORD_32 *)binary == crypt_key[i][0]) #pragma omp atomic retval |= 1; return retval; #else for (i = 0; i < count; i++) if (*(ARCH_WORD_32 *)binary == crypt_key[i][0]) return 1; return 0; #endif } static int cmp_exact(char* source, int index) { register ARCH_WORD_32 nr = 1345345333, add = 7, nr2 = 0x12345671; register ARCH_WORD_32 tmp; unsigned char *p; p = (unsigned char *)saved_key[index]; for (; *p; p++) { if (*p == ' ' || *p == '\t') continue; tmp = (ARCH_WORD_32)*p; nr ^= (((nr & 63) + add) * tmp) + (nr << 8); nr2 += (nr2 << 8) ^ nr; add += tmp; } #if 0 { char ctmp[CIPHERTEXT_LENGTH + 1]; sprintf(ctmp, "%08x%08x", nr & (((ARCH_WORD_32)1 << 31) - 1), nr2 & (((ARCH_WORD_32)1 << 31) - 1)); return !memcmp(source, ctmp, CIPHERTEXT_LENGTH); } #else { ARCH_WORD_32 *binary = get_binary_size(source, 8); return binary[0] == (nr & (((ARCH_WORD_32)1 << 31) - 1)) && binary[1] == (nr2 & (((ARCH_WORD_32)1 << 31) - 1)); } #endif } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int i = 0; #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(count, saved_key, crypt_key) #endif #if MAX_KEYS_PER_CRYPT > 1 || defined(_OPENMP) for (i = 0; i < count; i++) #endif { unsigned char *p = (unsigned char *)saved_key[i]; if (*p) { ARCH_WORD_32 nr, add; ARCH_WORD_32 tmp; while (*p == ' ' || *p == '\t') p++; tmp = (ARCH_WORD_32) (unsigned char) *p++; nr = 1345345333 ^ ((((1345345333 & 63) + 7) * tmp) + (1345345333U << 8)); add = 7 + tmp; for (; *p; p++) { if (*p == ' ' || *p == '\t') continue; tmp = (ARCH_WORD_32) (unsigned char) *p; nr ^= (((nr & 63) + add) * tmp) + (nr << 8); add += tmp; } crypt_key[i][0] = (nr & (((ARCH_WORD_32)1 << 31) - 1)); #if MAX_KEYS_PER_CRYPT > 1 || defined(_OPENMP) continue; #else return count; #endif } crypt_key[i][0] = (1345345333 & (((ARCH_WORD_32)1 << 31) - 1)); } return count; } static int get_hash_0(int index) { return crypt_key[index][0] & 0xF; } static int get_hash_1(int index) { return crypt_key[index][0] & 0xFF; } static int get_hash_2(int index) { return crypt_key[index][0] & 0xFFF; } static int get_hash_3(int index) { return crypt_key[index][0] & 0xFFFF; } static int get_hash_4(int index) { return crypt_key[index][0] & 0xFFFFF; } static int get_hash_5(int index) { return crypt_key[index][0] & 0xFFFFFF; } static int get_hash_6(int index) { return crypt_key[index][0] & 0x7FFFFFF; } struct fmt_main fmt_MYSQL_fast = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_SPLIT_UNIFIES_CASE | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
GB_unop__signum_fp64_fp64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__signum_fp64_fp64) // op(A') function: GB (_unop_tran__signum_fp64_fp64) // C type: double // A type: double // cast: double cij = aij // unaryop: cij = GB_signum (aij) #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_signum (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = GB_signum (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SIGNUM || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__signum_fp64_fp64) ( double *Cx, // Cx and Ax may be aliased const double *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = GB_signum (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; double aij = Ax [p] ; double z = aij ; Cx [p] = GB_signum (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__signum_fp64_fp64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
resize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % RRRR EEEEE SSSSS IIIII ZZZZZ EEEEE % % R R E SS I ZZ E % % RRRR EEE SSS I ZZZ EEE % % R R E SS I ZZ E % % R R EEEEE SSSSS IIIII ZZZZZ EEEEE % % % % % % MagickCore Image Resize Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/magick.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resize-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/token.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #if defined(MAGICKCORE_LQR_DELEGATE) #include <lqr.h> #endif /* Typedef declarations. */ struct _ResizeFilter { double (*filter)(const double,const ResizeFilter *), (*window)(const double,const ResizeFilter *), support, /* filter region of support - the filter support limit */ window_support, /* window support, usally equal to support (expert only) */ scale, /* dimension scaling to fit window support (usally 1.0) */ blur, /* x-scale (blur-sharpen) */ coefficient[7]; /* cubic coefficents for BC-cubic filters */ ResizeWeightingFunctionType filterWeightingType, windowWeightingType; size_t signature; }; /* Forward declaractions. */ static double I0(double x), BesselOrderOne(double), Sinc(const double, const ResizeFilter *), SincFast(const double, const ResizeFilter *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + F i l t e r F u n c t i o n s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % These are the various filter and windowing functions that are provided. % % They are internal to this module only. See AcquireResizeFilterInfo() for % details of the access to these functions, via the GetResizeFilterSupport() % and GetResizeFilterWeight() API interface. % % The individual filter functions have this format... % % static MagickRealtype *FilterName(const double x,const double support) % % A description of each parameter follows: % % o x: the distance from the sampling point generally in the range of 0 to % support. The GetResizeFilterWeight() ensures this a positive value. % % o resize_filter: current filter information. This allows function to % access support, and possibly other pre-calculated information defining % the functions. % */ static double Blackman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Blackman: 2nd order cosine windowing function: 0.42 + 0.5 cos(pi x) + 0.08 cos(2pi x) Refactored by Chantal Racette and Nicolas Robidoux to one trig call and five flops. */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.34+cosine*(0.5+cosine*0.16)); } static double Bohman(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Bohman: 2rd Order cosine windowing function: (1-x) cos(pi x) + sin(pi x) / pi. Refactored by Nicolas Robidoux to one trig call, one sqrt call, and 7 flops, taking advantage of the fact that the support of Bohman is 1.0 (so that we know that sin(pi x) >= 0). */ const double cosine = cos((double) (MagickPI*x)); const double sine=sqrt(1.0-cosine*cosine); magick_unreferenced(resize_filter); return((1.0-x)*cosine+(1.0/MagickPI)*sine); } static double Box(const double magick_unused(x), const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(x); magick_unreferenced(resize_filter); /* A Box filter is a equal weighting function (all weights equal). DO NOT LIMIT results by support or resize point sampling will work as it requests points beyond its normal 0.0 support size. */ return(1.0); } static double Cosine(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Cosine window function: cos((pi/2)*x). */ return(cos((double) (MagickPI2*x))); } static double CubicBC(const double x,const ResizeFilter *resize_filter) { /* Cubic Filters using B,C determined values: Mitchell-Netravali B = 1/3 C = 1/3 "Balanced" cubic spline filter Catmull-Rom B = 0 C = 1/2 Interpolatory and exact on linears Spline B = 1 C = 0 B-Spline Gaussian approximation Hermite B = 0 C = 0 B-Spline interpolator See paper by Mitchell and Netravali, Reconstruction Filters in Computer Graphics Computer Graphics, Volume 22, Number 4, August 1988 http://www.cs.utexas.edu/users/fussell/courses/cs384g/lectures/mitchell/ Mitchell.pdf. Coefficents are determined from B,C values: P0 = ( 6 - 2*B )/6 = coeff[0] P1 = 0 P2 = (-18 +12*B + 6*C )/6 = coeff[1] P3 = ( 12 - 9*B - 6*C )/6 = coeff[2] Q0 = ( 8*B +24*C )/6 = coeff[3] Q1 = ( -12*B -48*C )/6 = coeff[4] Q2 = ( 6*B +30*C )/6 = coeff[5] Q3 = ( - 1*B - 6*C )/6 = coeff[6] which are used to define the filter: P0 + P1*x + P2*x^2 + P3*x^3 0 <= x < 1 Q0 + Q1*x + Q2*x^2 + Q3*x^3 1 <= x < 2 which ensures function is continuous in value and derivative (slope). */ if (x < 1.0) return(resize_filter->coefficient[0]+x*(x* (resize_filter->coefficient[1]+x*resize_filter->coefficient[2]))); if (x < 2.0) return(resize_filter->coefficient[3]+x*(resize_filter->coefficient[4]+x* (resize_filter->coefficient[5]+x*resize_filter->coefficient[6]))); return(0.0); } static double CubicSpline(const double x,const ResizeFilter *resize_filter) { if (resize_filter->support <= 2.0) { /* 2-lobe Spline filter. */ if (x < 1.0) return(((x-9.0/5.0)*x-1.0/5.0)*x+1.0); if (x < 2.0) return(((-1.0/3.0*(x-1.0)+4.0/5.0)*(x-1.0)-7.0/15.0)*(x-1.0)); return(0.0); } if (resize_filter->support <= 3.0) { /* 3-lobe Spline filter. */ if (x < 1.0) return(((13.0/11.0*x-453.0/209.0)*x-3.0/209.0)*x+1.0); if (x < 2.0) return(((-6.0/11.0*(x-1.0)+270.0/209.0)*(x-1.0)-156.0/209.0)*(x-1.0)); if (x < 3.0) return(((1.0/11.0*(x-2.0)-45.0/209.0)*(x-2.0)+26.0/209.0)*(x-2.0)); return(0.0); } /* 4-lobe Spline filter. */ if (x < 1.0) return(((49.0/41.0*x-6387.0/2911.0)*x-3.0/2911.0)*x+1.0); if (x < 2.0) return(((-24.0/41.0*(x-1.0)+4032.0/2911.0)*(x-1.0)-2328.0/2911.0)*(x-1.0)); if (x < 3.0) return(((6.0/41.0*(x-2.0)-1008.0/2911.0)*(x-2.0)+582.0/2911.0)*(x-2.0)); if (x < 4.0) return(((-1.0/41.0*(x-3.0)+168.0/2911.0)*(x-3.0)-97.0/2911.0)*(x-3.0)); return(0.0); } static double Gaussian(const double x,const ResizeFilter *resize_filter) { /* Gaussian with a sigma = 1/2 (or as user specified) Gaussian Formula (1D) ... exp( -(x^2)/((2.0*sigma^2) ) / (sqrt(2*PI)*sigma^2)) Gaussian Formula (2D) ... exp( -(x^2+y^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) or for radius exp( -(r^2)/(2.0*sigma^2) ) / (PI*sigma^2) ) Note that it is only a change from 1-d to radial form is in the normalization multiplier which is not needed or used when Gaussian is used as a filter. The constants are pre-calculated... coeff[0]=sigma; coeff[1]=1.0/(2.0*sigma^2); coeff[2]=1.0/(sqrt(2*PI)*sigma^2); exp( -coeff[1]*(x^2)) ) * coeff[2]; However the multiplier coeff[1] is need, the others are informative only. This separates the gaussian 'sigma' value from the 'blur/support' settings allowing for its use in special 'small sigma' gaussians, without the filter 'missing' pixels because the support becomes too small. */ return(exp((double)(-resize_filter->coefficient[1]*x*x))); } static double Hann(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Cosine window function: 0.5+0.5*cos(pi*x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.5+0.5*cosine); } static double Hamming(const double x, const ResizeFilter *magick_unused(resize_filter)) { /* Offset cosine window function: .54 + .46 cos(pi x). */ const double cosine = cos((double) (MagickPI*x)); magick_unreferenced(resize_filter); return(0.54+0.46*cosine); } static double Jinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* See Pratt "Digital Image Processing" p.97 for Jinc/Bessel functions. http://mathworld.wolfram.com/JincFunction.html and page 11 of http://www.ph.ed.ac.uk/%7ewjh/teaching/mo/slides/lens/lens.pdf The original "zoom" program by Paul Heckbert called this "Bessel". But really it is more accurately named "Jinc". */ if (x == 0.0) return(0.5*MagickPI); return(BesselOrderOne(MagickPI*x)/x); } static double Kaiser(const double x,const ResizeFilter *resize_filter) { /* Kaiser Windowing Function (bessel windowing) I0( beta * sqrt( 1-x^2) ) / IO(0) Beta (coeff[0]) is a free value from 5 to 8 (defaults to 6.5). However it is typically defined in terms of Alpha*PI The normalization factor (coeff[1]) is not actually needed, but without it the filters has a large value at x=0 making it difficult to compare the function with other windowing functions. */ return(resize_filter->coefficient[1]*I0(resize_filter->coefficient[0]* sqrt((double) (1.0-x*x)))); } static double Lagrange(const double x,const ResizeFilter *resize_filter) { double value; ssize_t i; ssize_t n, order; /* Lagrange piecewise polynomial fit of sinc: N is the 'order' of the lagrange function and depends on the overall support window size of the filter. That is: for a support of 2, it gives a lagrange-4 (piecewise cubic function). "n" identifies the piece of the piecewise polynomial. See Survey: Interpolation Methods, IEEE Transactions on Medical Imaging, Vol 18, No 11, November 1999, p1049-1075, -- Equation 27 on p1064. */ if (x > resize_filter->support) return(0.0); order=(ssize_t) (2.0*resize_filter->window_support); /* number of pieces */ n=(ssize_t) (resize_filter->window_support+x); value=1.0f; for (i=0; i < order; i++) if (i != n) value*=(n-i-x)/(n-i); return(value); } static double Quadratic(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 2rd order (quadratic) B-Spline approximation of Gaussian. */ if (x < 0.5) return(0.75-x*x); if (x < 1.5) return(0.5*(x-1.5)*(x-1.5)); return(0.0); } static double Sinc(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Scaled sinc(x) function using a trig call: sinc(x) == sin(pi x)/(pi x). */ if (x != 0.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } return((double) 1.0); } static double SincFast(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Approximations of the sinc function sin(pi x)/(pi x) over the interval [-4,4] constructed by Nicolas Robidoux and Chantal Racette with funding from the Natural Sciences and Engineering Research Council of Canada. Although the approximations are polynomials (for low order of approximation) and quotients of polynomials (for higher order of approximation) and consequently are similar in form to Taylor polynomials / Pade approximants, the approximations are computed with a completely different technique. Summary: These approximations are "the best" in terms of bang (accuracy) for the buck (flops). More specifically: Among the polynomial quotients that can be computed using a fixed number of flops (with a given "+ - * / budget"), the chosen polynomial quotient is the one closest to the approximated function with respect to maximum absolute relative error over the given interval. The Remez algorithm, as implemented in the boost library's minimax package, is the key to the construction: http://www.boost.org/doc/libs/1_36_0/libs/ math/doc/sf_and_dist/html/math_toolkit/backgrounders/remez.html If outside of the interval of approximation, use the standard trig formula. */ if (x > 4.0) { const double alpha=(double) (MagickPI*x); return(sin((double) alpha)/alpha); } { /* The approximations only depend on x^2 (sinc is an even function). */ const double xx = x*x; #if MAGICKCORE_QUANTUM_DEPTH <= 8 /* Maximum absolute relative error 6.3e-6 < 1/2^17. */ const double c0 = 0.173610016489197553621906385078711564924e-2L; const double c1 = -0.384186115075660162081071290162149315834e-3L; const double c2 = 0.393684603287860108352720146121813443561e-4L; const double c3 = -0.248947210682259168029030370205389323899e-5L; const double c4 = 0.107791837839662283066379987646635416692e-6L; const double c5 = -0.324874073895735800961260474028013982211e-8L; const double c6 = 0.628155216606695311524920882748052490116e-10L; const double c7 = -0.586110644039348333520104379959307242711e-12L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #elif MAGICKCORE_QUANTUM_DEPTH <= 16 /* Max. abs. rel. error 2.2e-8 < 1/2^25. */ const double c0 = 0.173611107357320220183368594093166520811e-2L; const double c1 = -0.384240921114946632192116762889211361285e-3L; const double c2 = 0.394201182359318128221229891724947048771e-4L; const double c3 = -0.250963301609117217660068889165550534856e-5L; const double c4 = 0.111902032818095784414237782071368805120e-6L; const double c5 = -0.372895101408779549368465614321137048875e-8L; const double c6 = 0.957694196677572570319816780188718518330e-10L; const double c7 = -0.187208577776590710853865174371617338991e-11L; const double c8 = 0.253524321426864752676094495396308636823e-13L; const double c9 = -0.177084805010701112639035485248501049364e-15L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*(c7+xx*(c8+xx*c9)))))))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)*p); #else /* Max. abs. rel. error 1.2e-12 < 1/2^39. */ const double c0 = 0.173611111110910715186413700076827593074e-2L; const double c1 = -0.289105544717893415815859968653611245425e-3L; const double c2 = 0.206952161241815727624413291940849294025e-4L; const double c3 = -0.834446180169727178193268528095341741698e-6L; const double c4 = 0.207010104171026718629622453275917944941e-7L; const double c5 = -0.319724784938507108101517564300855542655e-9L; const double c6 = 0.288101675249103266147006509214934493930e-11L; const double c7 = -0.118218971804934245819960233886876537953e-13L; const double p = c0+xx*(c1+xx*(c2+xx*(c3+xx*(c4+xx*(c5+xx*(c6+xx*c7)))))); const double d0 = 1.0L; const double d1 = 0.547981619622284827495856984100563583948e-1L; const double d2 = 0.134226268835357312626304688047086921806e-2L; const double d3 = 0.178994697503371051002463656833597608689e-4L; const double d4 = 0.114633394140438168641246022557689759090e-6L; const double q = d0+xx*(d1+xx*(d2+xx*(d3+xx*d4))); return((xx-1.0)*(xx-4.0)*(xx-9.0)*(xx-16.0)/q*p); #endif } } static double Triangle(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* 1st order (linear) B-Spline, bilinear interpolation, Tent 1D filter, or a Bartlett 2D Cone filter. Also used as a Bartlett Windowing function for Sinc(). */ if (x < 1.0) return(1.0-x); return(0.0); } static double Welch(const double x, const ResizeFilter *magick_unused(resize_filter)) { magick_unreferenced(resize_filter); /* Welch parabolic windowing filter. */ if (x < 1.0) return(1.0-x*x); return(0.0); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireResizeFilter() allocates the ResizeFilter structure. Choose from % these filters: % % FIR (Finite impulse Response) Filters % Box Triangle Quadratic % Spline Hermite Catrom % Mitchell % % IIR (Infinite impulse Response) Filters % Gaussian Sinc Jinc (Bessel) % % Windowed Sinc/Jinc Filters % Blackman Bohman Lanczos % Hann Hamming Cosine % Kaiser Welch Parzen % Bartlett % % Special Purpose Filters % Cubic SincFast LanczosSharp Lanczos2 Lanczos2Sharp % Robidoux RobidouxSharp % % The users "-filter" selection is used to lookup the default 'expert' % settings for that filter from a internal table. However any provided % 'expert' settings (see below) may override this selection. % % FIR filters are used as is, and are limited to that filters support window % (unless over-ridden). 'Gaussian' while classed as an IIR filter, is also % simply clipped by its support size (currently 1.5 or approximately 3*sigma % as recommended by many references) % % The special a 'cylindrical' filter flag will promote the default 4-lobed % Windowed Sinc filter to a 3-lobed Windowed Jinc equivalent, which is better % suited to this style of image resampling. This typically happens when using % such a filter for images distortions. % % SPECIFIC FILTERS: % % Directly requesting 'Sinc', 'Jinc' function as a filter will force the use % of function without any windowing, or promotion for cylindrical usage. This % is not recommended, except by image processing experts, especially as part % of expert option filter function selection. % % Two forms of the 'Sinc' function are available: Sinc and SincFast. Sinc is % computed using the traditional sin(pi*x)/(pi*x); it is selected if the user % specifically specifies the use of a Sinc filter. SincFast uses highly % accurate (and fast) polynomial (low Q) and rational (high Q) approximations, % and will be used by default in most cases. % % The Lanczos filter is a special 3-lobed Sinc-windowed Sinc filter (promoted % to Jinc-windowed Jinc for cylindrical (Elliptical Weighted Average) use). % The Sinc version is the most popular windowed filter. % % LanczosSharp is a slightly sharpened (blur=0.9812505644269356 < 1) form of % the Lanczos filter, specifically designed for EWA distortion (as a % Jinc-Jinc); it can also be used as a slightly sharper orthogonal Lanczos % (Sinc-Sinc) filter. The chosen blur value comes as close as possible to % satisfying the following condition without changing the character of the % corresponding EWA filter: % % 'No-Op' Vertical and Horizontal Line Preservation Condition: Images with % only vertical or horizontal features are preserved when performing 'no-op" % with EWA distortion. % % The Lanczos2 and Lanczos2Sharp filters are 2-lobe versions of the Lanczos % filters. The 'sharp' version uses a blur factor of 0.9549963639785485, % again chosen because the resulting EWA filter comes as close as possible to % satisfying the above condition. % % Robidoux is another filter tuned for EWA. It is the Keys cubic filter % defined by B=(228 - 108 sqrt(2))/199. Robidoux satisfies the "'No-Op' % Vertical and Horizontal Line Preservation Condition" exactly, and it % moderately blurs high frequency 'pixel-hash' patterns under no-op. It turns % out to be close to both Mitchell and Lanczos2Sharp. For example, its first % crossing is at (36 sqrt(2) + 123)/(72 sqrt(2) + 47), almost the same as the % first crossing of Mitchell and Lanczos2Sharp. % % RodidouxSharp is a slightly sharper version of Rodidoux, some believe it % is too sharp. It is designed to minimize the maximum possible change in % a pixel value which is at one of the extremes (e.g., 0 or 255) under no-op % conditions. Amazingly Mitchell falls roughly between Rodidoux and % RodidouxSharp, though this seems to have been pure coincidence. % % 'EXPERT' OPTIONS: % % These artifact "defines" are not recommended for production use without % expert knowledge of resampling, filtering, and the effects they have on the % resulting resampled (resized or distorted) image. % % They can be used to override any and all filter default, and it is % recommended you make good use of "filter:verbose" to make sure that the % overall effect of your selection (before and after) is as expected. % % "filter:verbose" controls whether to output the exact results of the % filter selections made, as well as plotting data for graphing the % resulting filter over the filters support range. % % "filter:filter" select the main function associated with this filter % name, as the weighting function of the filter. This can be used to % set a windowing function as a weighting function, for special % purposes, such as graphing. % % If a "filter:window" operation has not been provided, a 'Box' % windowing function will be set to denote that no windowing function is % being used. % % "filter:window" Select this windowing function for the filter. While any % filter could be used as a windowing function, using the 'first lobe' of % that filter over the whole support window, using a non-windowing % function is not advisible. If no weighting filter function is specified % a 'SincFast' filter is used. % % "filter:lobes" Number of lobes to use for the Sinc/Jinc filter. This a % simpler method of setting filter support size that will correctly % handle the Sinc/Jinc switch for an operators filtering requirements. % Only integers should be given. % % "filter:support" Set the support size for filtering to the size given. % This not recommended for Sinc/Jinc windowed filters (lobes should be % used instead). This will override any 'filter:lobes' option. % % "filter:win-support" Scale windowing function to this size instead. This % causes the windowing (or self-windowing Lagrange filter) to act is if % the support window it much much larger than what is actually supplied % to the calling operator. The filter however is still clipped to the % real support size given, by the support range supplied to the caller. % If unset this will equal the normal filter support size. % % "filter:blur" Scale the filter and support window by this amount. A value % of > 1 will generally result in a more blurred image with more ringing % effects, while a value <1 will sharpen the resulting image with more % aliasing effects. % % "filter:sigma" The sigma value to use for the Gaussian filter only. % Defaults to '1/2'. Using a different sigma effectively provides a % method of using the filter as a 'blur' convolution. Particularly when % using it for Distort. % % "filter:b" % "filter:c" Override the preset B,C values for a Cubic filter. % If only one of these are given it is assumes to be a 'Keys' type of % filter such that B+2C=1, where Keys 'alpha' value = C. % % Examples: % % Set a true un-windowed Sinc filter with 10 lobes (very slow): % -define filter:filter=Sinc % -define filter:lobes=8 % % Set an 8 lobe Lanczos (Sinc or Jinc) filter: % -filter Lanczos % -define filter:lobes=8 % % The format of the AcquireResizeFilter method is: % % ResizeFilter *AcquireResizeFilter(const Image *image, % const FilterType filter_type,const MagickBooleanType cylindrical, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filter: the filter type, defining a preset filter, window and support. % The artifact settings listed above will override those selections. % % o blur: blur the filter by this amount, use 1.0 if unknown. Image % artifact "filter:blur" will override this API call usage, including any % internal change (such as for cylindrical usage). % % o radial: use a 1D orthogonal filter (Sinc) or 2D cylindrical (radial) % filter (Jinc). % % o exception: return any errors or warnings in this structure. % */ MagickPrivate ResizeFilter *AcquireResizeFilter(const Image *image, const FilterType filter,const MagickBooleanType cylindrical, ExceptionInfo *exception) { const char *artifact; FilterType filter_type, window_type; double B, C, value; ResizeFilter *resize_filter; /* Table Mapping given Filter, into Weighting and Windowing functions. A 'Box' windowing function means its a simble non-windowed filter. An 'SincFast' filter function could be upgraded to a 'Jinc' filter if a "cylindrical" is requested, unless a 'Sinc' or 'SincFast' filter was specifically requested by the user. WARNING: The order of this table must match the order of the FilterType enumeration specified in "resample.h", or the filter names will not match the filter being setup. You can check filter setups with the "filter:verbose" expert setting. */ static struct { FilterType filter, window; } const mapping[SentinelFilter] = { { UndefinedFilter, BoxFilter }, /* Undefined (default to Box) */ { PointFilter, BoxFilter }, /* SPECIAL: Nearest neighbour */ { BoxFilter, BoxFilter }, /* Box averaging filter */ { TriangleFilter, BoxFilter }, /* Linear interpolation filter */ { HermiteFilter, BoxFilter }, /* Hermite interpolation filter */ { SincFastFilter, HannFilter }, /* Hann -- cosine-sinc */ { SincFastFilter, HammingFilter }, /* Hamming -- '' variation */ { SincFastFilter, BlackmanFilter }, /* Blackman -- 2*cosine-sinc */ { GaussianFilter, BoxFilter }, /* Gaussian blur filter */ { QuadraticFilter, BoxFilter }, /* Quadratic Gaussian approx */ { CubicFilter, BoxFilter }, /* General Cubic Filter, Spline */ { CatromFilter, BoxFilter }, /* Cubic-Keys interpolator */ { MitchellFilter, BoxFilter }, /* 'Ideal' Cubic-Keys filter */ { JincFilter, BoxFilter }, /* Raw 3-lobed Jinc function */ { SincFilter, BoxFilter }, /* Raw 4-lobed Sinc function */ { SincFastFilter, BoxFilter }, /* Raw fast sinc ("Pade"-type) */ { SincFastFilter, KaiserFilter }, /* Kaiser -- square root-sinc */ { LanczosFilter, WelchFilter }, /* Welch -- parabolic (3 lobe) */ { SincFastFilter, CubicFilter }, /* Parzen -- cubic-sinc */ { SincFastFilter, BohmanFilter }, /* Bohman -- 2*cosine-sinc */ { SincFastFilter, TriangleFilter }, /* Bartlett -- triangle-sinc */ { LagrangeFilter, BoxFilter }, /* Lagrange self-windowing */ { LanczosFilter, LanczosFilter }, /* Lanczos Sinc-Sinc filters */ { LanczosSharpFilter, LanczosSharpFilter }, /* | these require */ { Lanczos2Filter, Lanczos2Filter }, /* | special handling */ { Lanczos2SharpFilter, Lanczos2SharpFilter }, { RobidouxFilter, BoxFilter }, /* Cubic Keys tuned for EWA */ { RobidouxSharpFilter, BoxFilter }, /* Sharper Cubic Keys for EWA */ { LanczosFilter, CosineFilter }, /* Cosine window (3 lobes) */ { SplineFilter, BoxFilter }, /* Spline Cubic Filter */ { LanczosRadiusFilter, LanczosFilter }, /* Lanczos with integer radius */ { CubicSplineFilter, BoxFilter }, /* CubicSpline (2/3/4 lobes) */ }; /* Table mapping the filter/window from the above table to an actual function. The default support size for that filter as a weighting function, the range to scale with to use that function as a sinc windowing function, (typ 1.0). Note that the filter_type -> function is 1 to 1 except for Sinc(), SincFast(), and CubicBC() functions, which may have multiple filter to function associations. See "filter:verbose" handling below for the function -> filter mapping. */ static struct { double (*function)(const double,const ResizeFilter*), support, /* Default lobes/support size of the weighting filter. */ scale, /* Support when function used as a windowing function Typically equal to the location of the first zero crossing. */ B,C; /* BC-spline coefficients, ignored if not a CubicBC filter. */ ResizeWeightingFunctionType weightingFunctionType; } const filters[SentinelFilter] = { /* .--- support window (if used as a Weighting Function) | .--- first crossing (if used as a Windowing Function) | | .--- B value for Cubic Function | | | .---- C value for Cubic Function | | | | */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Undefined (default to Box) */ { Box, 0.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Point (special handling) */ { Box, 0.5, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Box */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Triangle */ { CubicBC, 1.0, 1.0, 0.0, 0.0, CubicBCWeightingFunction }, /* Hermite (cubic B=C=0) */ { Hann, 1.0, 1.0, 0.0, 0.0, HannWeightingFunction }, /* Hann, cosine window */ { Hamming, 1.0, 1.0, 0.0, 0.0, HammingWeightingFunction }, /* Hamming, '' variation */ { Blackman, 1.0, 1.0, 0.0, 0.0, BlackmanWeightingFunction }, /* Blackman, 2*cosine window */ { Gaussian, 2.0, 1.5, 0.0, 0.0, GaussianWeightingFunction }, /* Gaussian */ { Quadratic, 1.5, 1.5, 0.0, 0.0, QuadraticWeightingFunction },/* Quadratic gaussian */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* General Cubic Filter */ { CubicBC, 2.0, 1.0, 0.0, 0.5, CubicBCWeightingFunction }, /* Catmull-Rom (B=0,C=1/2) */ { CubicBC, 2.0, 8.0/7.0, 1./3., 1./3., CubicBCWeightingFunction }, /* Mitchell (B=C=1/3) */ { Jinc, 3.0, 1.2196698912665045, 0.0, 0.0, JincWeightingFunction }, /* Raw 3-lobed Jinc */ { Sinc, 4.0, 1.0, 0.0, 0.0, SincWeightingFunction }, /* Raw 4-lobed Sinc */ { SincFast, 4.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Raw fast sinc ("Pade"-type) */ { Kaiser, 1.0, 1.0, 0.0, 0.0, KaiserWeightingFunction }, /* Kaiser (square root window) */ { Welch, 1.0, 1.0, 0.0, 0.0, WelchWeightingFunction }, /* Welch (parabolic window) */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Parzen (B-Spline window) */ { Bohman, 1.0, 1.0, 0.0, 0.0, BohmanWeightingFunction }, /* Bohman, 2*Cosine window */ { Triangle, 1.0, 1.0, 0.0, 0.0, TriangleWeightingFunction }, /* Bartlett (triangle window) */ { Lagrange, 2.0, 1.0, 0.0, 0.0, LagrangeWeightingFunction }, /* Lagrange sinc approximation */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 3-lobed Sinc-Sinc */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Sharpened */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, 2-lobed */ { SincFast, 2.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos2, sharpened */ /* Robidoux: Keys cubic close to Lanczos2D sharpened */ { CubicBC, 2.0, 1.1685777620836932, 0.37821575509399867, 0.31089212245300067, CubicBCWeightingFunction }, /* RobidouxSharp: Sharper version of Robidoux */ { CubicBC, 2.0, 1.105822933719019, 0.2620145123990142, 0.3689927438004929, CubicBCWeightingFunction }, { Cosine, 1.0, 1.0, 0.0, 0.0, CosineWeightingFunction }, /* Low level cosine window */ { CubicBC, 2.0, 2.0, 1.0, 0.0, CubicBCWeightingFunction }, /* Cubic B-Spline (B=1,C=0) */ { SincFast, 3.0, 1.0, 0.0, 0.0, SincFastWeightingFunction }, /* Lanczos, Interger Radius */ { CubicSpline,2.0, 0.5, 0.0, 0.0, BoxWeightingFunction }, /* Spline Lobes 2-lobed */ }; /* The known zero crossings of the Jinc() or more accurately the Jinc(x*PI) function being used as a filter. It is used by the "filter:lobes" expert setting and for 'lobes' for Jinc functions in the previous table. This way users do not have to deal with the highly irrational lobe sizes of the Jinc filter. Values taken from http://cose.math.bas.bg/webMathematica/webComputing/BesselZeros.jsp using Jv-function with v=1, then dividing by PI. */ static double jinc_zeros[16] = { 1.2196698912665045, 2.2331305943815286, 3.2383154841662362, 4.2410628637960699, 5.2427643768701817, 6.2439216898644877, 7.2447598687199570, 8.2453949139520427, 9.2458926849494673, 10.246293348754916, 11.246622794877883, 12.246898461138105, 13.247132522181061, 14.247333735806849, 15.247508563037300, 16.247661874700962 }; /* Allocate resize filter. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(UndefinedFilter < filter && filter < SentinelFilter); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) exception; resize_filter=(ResizeFilter *) AcquireCriticalMemory(sizeof(*resize_filter)); (void) memset(resize_filter,0,sizeof(*resize_filter)); /* Defaults for the requested filter. */ filter_type=mapping[filter].filter; window_type=mapping[filter].window; resize_filter->blur=1.0; /* Promote 1D Windowed Sinc Filters to a 2D Windowed Jinc filters */ if ((cylindrical != MagickFalse) && (filter_type == SincFastFilter) && (filter != SincFastFilter)) filter_type=JincFilter; /* 1D Windowed Sinc => 2D Windowed Jinc filters */ /* Expert filter setting override */ artifact=GetImageArtifact(image,"filter:filter"); if (IsStringTrue(artifact) != MagickFalse) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { /* Raw filter request - no window function. */ filter_type=(FilterType) option; window_type=BoxFilter; } /* Filter override with a specific window function. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) window_type=(FilterType) option; } } else { /* Window specified, but no filter function? Assume Sinc/Jinc. */ artifact=GetImageArtifact(image,"filter:window"); if (artifact != (const char *) NULL) { ssize_t option; option=ParseCommandOption(MagickFilterOptions,MagickFalse,artifact); if ((UndefinedFilter < option) && (option < SentinelFilter)) { filter_type= cylindrical != MagickFalse ? JincFilter : SincFastFilter; window_type=(FilterType) option; } } } /* Assign the real functions to use for the filters selected. */ resize_filter->filter=filters[filter_type].function; resize_filter->support=filters[filter_type].support; resize_filter->filterWeightingType=filters[filter_type].weightingFunctionType; resize_filter->window=filters[window_type].function; resize_filter->windowWeightingType=filters[window_type].weightingFunctionType; resize_filter->scale=filters[window_type].scale; resize_filter->signature=MagickCoreSignature; /* Filter Modifications for orthogonal/cylindrical usage */ if (cylindrical != MagickFalse) switch (filter_type) { case BoxFilter: /* Support for Cylindrical Box should be sqrt(2)/2 */ resize_filter->support=(double) MagickSQ1_2; break; case LanczosFilter: case LanczosSharpFilter: case Lanczos2Filter: case Lanczos2SharpFilter: case LanczosRadiusFilter: resize_filter->filter=filters[JincFilter].function; resize_filter->window=filters[JincFilter].function; resize_filter->scale=filters[JincFilter].scale; /* number of lobes (support window size) remain unchanged */ break; default: break; } /* Global Sharpening (regardless of orthoginal/cylindrical) */ switch (filter_type) { case LanczosSharpFilter: resize_filter->blur *= 0.9812505644269356; break; case Lanczos2SharpFilter: resize_filter->blur *= 0.9549963639785485; break; /* case LanczosRadius: blur adjust is done after lobes */ default: break; } /* Expert Option Modifications. */ /* User Gaussian Sigma Override - no support change */ if ((resize_filter->filter == Gaussian) || (resize_filter->window == Gaussian) ) { value=0.5; /* guassian sigma default, half pixel */ artifact=GetImageArtifact(image,"filter:sigma"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); /* Define coefficents for Gaussian */ resize_filter->coefficient[0]=value; /* note sigma too */ resize_filter->coefficient[1]=PerceptibleReciprocal(2.0*value*value); /* sigma scaling */ resize_filter->coefficient[2]=PerceptibleReciprocal(Magick2PI*value*value); /* normalization - not actually needed or used! */ if ( value > 0.5 ) resize_filter->support *= 2*value; /* increase support linearly */ } /* User Kaiser Alpha Override - no support change */ if ((resize_filter->filter == Kaiser) || (resize_filter->window == Kaiser) ) { value=6.5; /* default beta value for Kaiser bessel windowing function */ artifact=GetImageArtifact(image,"filter:alpha"); /* FUTURE: depreciate */ if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-beta"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL); artifact=GetImageArtifact(image,"filter:kaiser-alpha"); if (artifact != (const char *) NULL) value=StringToDouble(artifact,(char **) NULL)*MagickPI; /* Define coefficents for Kaiser Windowing Function */ resize_filter->coefficient[0]=value; /* alpha */ resize_filter->coefficient[1]=PerceptibleReciprocal(I0(value)); /* normalization */ } /* Support Overrides */ artifact=GetImageArtifact(image,"filter:lobes"); if (artifact != (const char *) NULL) { ssize_t lobes; lobes=(ssize_t) StringToLong(artifact); if (lobes < 1) lobes=1; resize_filter->support=(double) lobes; } if (resize_filter->filter == Jinc) { /* Convert a Jinc function lobes value to a real support value. */ if (resize_filter->support > 16) resize_filter->support=jinc_zeros[15]; /* largest entry in table */ else resize_filter->support=jinc_zeros[((long) resize_filter->support)-1]; /* Blur this filter so support is a integer value (lobes dependant). */ if (filter_type == LanczosRadiusFilter) resize_filter->blur*=floor(resize_filter->support)/ resize_filter->support; } /* Expert blur override. */ artifact=GetImageArtifact(image,"filter:blur"); if (artifact != (const char *) NULL) resize_filter->blur*=StringToDouble(artifact,(char **) NULL); if (resize_filter->blur < MagickEpsilon) resize_filter->blur=(double) MagickEpsilon; /* Expert override of the support setting. */ artifact=GetImageArtifact(image,"filter:support"); if (artifact != (const char *) NULL) resize_filter->support=fabs(StringToDouble(artifact,(char **) NULL)); /* Scale windowing function separately to the support 'clipping' window that calling operator is planning to actually use. (Expert override) */ resize_filter->window_support=resize_filter->support; /* default */ artifact=GetImageArtifact(image,"filter:win-support"); if (artifact != (const char *) NULL) resize_filter->window_support=fabs(StringToDouble(artifact,(char **) NULL)); /* Adjust window function scaling to match windowing support for weighting function. This avoids a division on every filter call. */ resize_filter->scale*=PerceptibleReciprocal(resize_filter->window_support); /* Set Cubic Spline B,C values, calculate Cubic coefficients. */ B=0.0; C=0.0; if ((resize_filter->filter == CubicBC) || (resize_filter->window == CubicBC) ) { B=filters[filter_type].B; C=filters[filter_type].C; if (filters[window_type].function == CubicBC) { B=filters[window_type].B; C=filters[window_type].C; } artifact=GetImageArtifact(image,"filter:b"); if (artifact != (const char *) NULL) { B=StringToDouble(artifact,(char **) NULL); C=(1.0-B)/2.0; /* Calculate C to get a Keys cubic filter. */ artifact=GetImageArtifact(image,"filter:c"); /* user C override */ if (artifact != (const char *) NULL) C=StringToDouble(artifact,(char **) NULL); } else { artifact=GetImageArtifact(image,"filter:c"); if (artifact != (const char *) NULL) { C=StringToDouble(artifact,(char **) NULL); B=1.0-2.0*C; /* Calculate B to get a Keys cubic filter. */ } } { const double twoB = B+B; /* Convert B,C values into Cubic Coefficents. See CubicBC(). */ resize_filter->coefficient[0]=1.0-(1.0/3.0)*B; resize_filter->coefficient[1]=-3.0+twoB+C; resize_filter->coefficient[2]=2.0-1.5*B-C; resize_filter->coefficient[3]=(4.0/3.0)*B+4.0*C; resize_filter->coefficient[4]=-8.0*C-twoB; resize_filter->coefficient[5]=B+5.0*C; resize_filter->coefficient[6]=(-1.0/6.0)*B-C; } } /* Expert Option Request for verbose details of the resulting filter. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp master { #endif if (IsStringTrue(GetImageArtifact(image,"filter:verbose")) != MagickFalse) { double support, x; /* Set the weighting function properly when the weighting function may not exactly match the filter of the same name. EG: a Point filter is really uses a Box weighting function with a different support than is typically used. */ if (resize_filter->filter == Box) filter_type=BoxFilter; if (resize_filter->filter == Sinc) filter_type=SincFilter; if (resize_filter->filter == SincFast) filter_type=SincFastFilter; if (resize_filter->filter == Jinc) filter_type=JincFilter; if (resize_filter->filter == CubicBC) filter_type=CubicFilter; if (resize_filter->window == Box) window_type=BoxFilter; if (resize_filter->window == Sinc) window_type=SincFilter; if (resize_filter->window == SincFast) window_type=SincFastFilter; if (resize_filter->window == Jinc) window_type=JincFilter; if (resize_filter->window == CubicBC) window_type=CubicFilter; /* Report Filter Details. */ support=GetResizeFilterSupport(resize_filter); /* practical_support */ (void) FormatLocaleFile(stdout, "# Resampling Filter (for graphing)\n#\n"); (void) FormatLocaleFile(stdout,"# filter = %s\n", CommandOptionToMnemonic(MagickFilterOptions,filter_type)); (void) FormatLocaleFile(stdout,"# window = %s\n", CommandOptionToMnemonic(MagickFilterOptions,window_type)); (void) FormatLocaleFile(stdout,"# support = %.*g\n", GetMagickPrecision(),(double) resize_filter->support); (void) FormatLocaleFile(stdout,"# window-support = %.*g\n", GetMagickPrecision(),(double) resize_filter->window_support); (void) FormatLocaleFile(stdout,"# scale-blur = %.*g\n", GetMagickPrecision(),(double) resize_filter->blur); if ((filter_type == GaussianFilter) || (window_type == GaussianFilter)) (void) FormatLocaleFile(stdout,"# gaussian-sigma = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); if ( filter_type == KaiserFilter || window_type == KaiserFilter ) (void) FormatLocaleFile(stdout,"# kaiser-beta = %.*g\n", GetMagickPrecision(),(double) resize_filter->coefficient[0]); (void) FormatLocaleFile(stdout,"# practical-support = %.*g\n", GetMagickPrecision(), (double) support); if ((filter_type == CubicFilter) || (window_type == CubicFilter)) (void) FormatLocaleFile(stdout,"# B,C = %.*g,%.*g\n", GetMagickPrecision(),(double) B,GetMagickPrecision(),(double) C); (void) FormatLocaleFile(stdout,"\n"); /* Output values of resulting filter graph -- for graphing filter result. */ for (x=0.0; x <= support; x+=0.01f) (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",x, GetMagickPrecision(),(double) GetResizeFilterWeight(resize_filter,x)); /* A final value so gnuplot can graph the 'stop' properly. */ (void) FormatLocaleFile(stdout,"%5.2lf\t%.*g\n",support, GetMagickPrecision(),0.0); } /* Output the above once only for each image - remove setting */ (void) DeleteImageArtifact((Image *) image,"filter:verbose"); #if defined(MAGICKCORE_OPENMP_SUPPORT) } #endif return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveResizeImage() adaptively resize image with pixel resampling. % % This is shortcut function for a fast interpolative resize using mesh % interpolation. It works well for small resizes of less than +/- 50% % of the original image size. For larger resizing on images a full % filtered and slower resize function should be used instead. % % The format of the AdaptiveResizeImage method is: % % Image *AdaptiveResizeImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveResizeImage(const Image *image, const size_t columns,const size_t rows,ExceptionInfo *exception) { Image *resize_image; resize_image=InterpolativeResizeImage(image,columns,rows,MeshInterpolatePixel, exception); return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + B e s s e l O r d e r O n e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BesselOrderOne() computes the Bessel function of x of the first kind of % order 0. This is used to create the Jinc() filter function below. % % Reduce x to |x| since j1(x)= -j1(-x), and for x in (0,8] % % j1(x) = x*j1(x); % % For x in (8,inf) % % j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) % % where x1 = x-3*pi/4. Compute sin(x1) and cos(x1) as follow: % % cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) % = 1/sqrt(2) * (sin(x) - cos(x)) % sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) % = -1/sqrt(2) * (sin(x) + cos(x)) % % The format of the BesselOrderOne method is: % % double BesselOrderOne(double x) % % A description of each parameter follows: % % o x: double value. % */ #undef I0 static double I0(double x) { double sum, t, y; ssize_t i; /* Zeroth order Bessel function of the first kind. */ sum=1.0; y=x*x/4.0; t=y; for (i=2; t > MagickEpsilon; i++) { sum+=t; t*=y/((double) i*i); } return(sum); } #undef J1 static double J1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.581199354001606143928050809e+21, -0.6672106568924916298020941484e+20, 0.2316433580634002297931815435e+19, -0.3588817569910106050743641413e+17, 0.2908795263834775409737601689e+15, -0.1322983480332126453125473247e+13, 0.3413234182301700539091292655e+10, -0.4695753530642995859767162166e+7, 0.270112271089232341485679099e+4 }, Qone[] = { 0.11623987080032122878585294e+22, 0.1185770712190320999837113348e+20, 0.6092061398917521746105196863e+17, 0.2081661221307607351240184229e+15, 0.5243710262167649715406728642e+12, 0.1013863514358673989967045588e+10, 0.1501793594998585505921097578e+7, 0.1606931573481487801970916749e+4, 0.1e+1 }; p=Pone[8]; q=Qone[8]; for (i=7; i >= 0; i--) { p=p*x*x+Pone[i]; q=q*x*x+Qone[i]; } return(p/q); } #undef P1 static double P1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.352246649133679798341724373e+5, 0.62758845247161281269005675e+5, 0.313539631109159574238669888e+5, 0.49854832060594338434500455e+4, 0.2111529182853962382105718e+3, 0.12571716929145341558495e+1 }, Qone[] = { 0.352246649133679798068390431e+5, 0.626943469593560511888833731e+5, 0.312404063819041039923015703e+5, 0.4930396490181088979386097e+4, 0.2030775189134759322293574e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } #undef Q1 static double Q1(double x) { double p, q; ssize_t i; static const double Pone[] = { 0.3511751914303552822533318e+3, 0.7210391804904475039280863e+3, 0.4259873011654442389886993e+3, 0.831898957673850827325226e+2, 0.45681716295512267064405e+1, 0.3532840052740123642735e-1 }, Qone[] = { 0.74917374171809127714519505e+4, 0.154141773392650970499848051e+5, 0.91522317015169922705904727e+4, 0.18111867005523513506724158e+4, 0.1038187585462133728776636e+3, 0.1e+1 }; p=Pone[5]; q=Qone[5]; for (i=4; i >= 0; i--) { p=p*(8.0/x)*(8.0/x)+Pone[i]; q=q*(8.0/x)*(8.0/x)+Qone[i]; } return(p/q); } static double BesselOrderOne(double x) { double p, q; if (x == 0.0) return(0.0); p=x; if (x < 0.0) x=(-x); if (x < 8.0) return(p*J1(x)); q=sqrt((double) (2.0/(MagickPI*x)))*(P1(x)*(1.0/sqrt(2.0)*(sin(x)- cos(x)))-8.0/x*Q1(x)*(-1.0/sqrt(2.0)*(sin(x)+cos(x)))); if (p < 0.0) q=(-q); return(q); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y R e s i z e F i l t e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyResizeFilter() destroy the resize filter. % % The format of the DestroyResizeFilter method is: % % ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) % % A description of each parameter follows: % % o resize_filter: the resize filter. % */ MagickPrivate ResizeFilter *DestroyResizeFilter(ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); resize_filter->signature=(~MagickCoreSignature); resize_filter=(ResizeFilter *) RelinquishMagickMemory(resize_filter); return(resize_filter); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r S u p p o r t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterSupport() return the current support window size for this % filter. Note that this may have been enlarged by filter:blur factor. % % The format of the GetResizeFilterSupport method is: % % double GetResizeFilterSupport(const ResizeFilter *resize_filter) % % A description of each parameter follows: % % o filter: Image filter to use. % */ MagickPrivate double *GetResizeFilterCoefficient( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return((double *) resize_filter->coefficient); } MagickPrivate double GetResizeFilterBlur(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->blur); } MagickPrivate double GetResizeFilterScale(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->scale); } MagickPrivate double GetResizeFilterWindowSupport( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->window_support); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->filterWeightingType); } MagickPrivate ResizeWeightingFunctionType GetResizeFilterWindowWeightingType( const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->windowWeightingType); } MagickPrivate double GetResizeFilterSupport(const ResizeFilter *resize_filter) { assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); return(resize_filter->support*resize_filter->blur); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t R e s i z e F i l t e r W e i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetResizeFilterWeight evaluates the specified resize filter at the point x % which usally lies between zero and the filters current 'support' and % returns the weight of the filter function at that point. % % The format of the GetResizeFilterWeight method is: % % double GetResizeFilterWeight(const ResizeFilter *resize_filter, % const double x) % % A description of each parameter follows: % % o filter: the filter type. % % o x: the point. % */ MagickPrivate double GetResizeFilterWeight(const ResizeFilter *resize_filter, const double x) { double scale, weight, x_blur; /* Windowing function - scale the weighting filter by this amount. */ assert(resize_filter != (ResizeFilter *) NULL); assert(resize_filter->signature == MagickCoreSignature); x_blur=fabs((double) x)/resize_filter->blur; /* X offset with blur scaling */ if ((resize_filter->window_support < MagickEpsilon) || (resize_filter->window == Box)) scale=1.0; /* Point or Box Filter -- avoid division by zero */ else { scale=resize_filter->scale; scale=resize_filter->window(x_blur*scale,resize_filter); } weight=scale*resize_filter->filter(x_blur,resize_filter); return(weight); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t i v e R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolativeResizeImage() resizes an image using the specified % interpolation method. % % The format of the InterpolativeResizeImage method is: % % Image *InterpolativeResizeImage(const Image *image,const size_t columns, % const size_t rows,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the resized image. % % o rows: the number of rows in the resized image. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *InterpolativeResizeImage(const Image *image, const size_t columns,const size_t rows,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define InterpolativeResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; Image *resize_image; MagickBooleanType status; MagickOffsetType progress; PointInfo scale; ssize_t y; /* Interpolatively resize image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(resize_image,DirectClass,exception) == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); scale.x=(double) image->columns/resize_image->columns; scale.y=(double) image->rows/resize_image->rows; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { PointInfo offset; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if (q == (Quantum *) NULL) continue; offset.y=((double) y+0.5)*scale.y-0.5; for (x=0; x < (ssize_t) resize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait resize_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; offset.x=((double) x+0.5)*scale.x-0.5; status=InterpolatePixelChannels(image,image_view,resize_image,method, offset.x,offset.y,q,exception); if (status == MagickFalse) break; } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,InterpolativeResizeImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) resize_image=DestroyImage(resize_image); return(resize_image); } #if defined(MAGICKCORE_LQR_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i q u i d R e s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % LiquidRescaleImage() rescales image with seam carving. % % The format of the LiquidRescaleImage method is: % % Image *LiquidRescaleImage(const Image *image,const size_t columns, % const size_t rows,const double delta_x,const double rigidity, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the rescaled image. % % o rows: the number of rows in the rescaled image. % % o delta_x: maximum seam transversal step (0 means straight seams). % % o rigidity: introduce a bias for non-straight seams (typically 0). % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *LiquidRescaleImage(const Image *image,const size_t columns, const size_t rows,const double delta_x,const double rigidity, ExceptionInfo *exception) { #define LiquidRescaleImageTag "Rescale/Image" CacheView *image_view, *rescale_view; gfloat *packet, *pixels; Image *rescale_image; int x_offset, y_offset; LqrCarver *carver; LqrRetVal lqr_status; MagickBooleanType status; MemoryInfo *pixel_info; gfloat *q; ssize_t y; /* Liquid rescale image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); if ((columns <= 2) || (rows <= 2)) return(ResizeImage(image,columns,rows,image->filter,exception)); pixel_info=AcquireVirtualMemory(image->columns,image->rows*MaxPixelChannels* sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) return((Image *) NULL); pixels=(gfloat *) GetVirtualMemoryBlob(pixel_info); status=MagickTrue; q=pixels; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) *q++=QuantumScale*p[i]; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); carver=lqr_carver_new_ext(pixels,(int) image->columns,(int) image->rows, (int) GetPixelChannels(image),LQR_COLDEPTH_32F); if (carver == (LqrCarver *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } lqr_carver_set_preserve_input_image(carver); lqr_status=lqr_carver_init(carver,(int) delta_x,rigidity); lqr_status=lqr_carver_resize(carver,(int) columns,(int) rows); (void) lqr_status; rescale_image=CloneImage(image,lqr_carver_get_width(carver), lqr_carver_get_height(carver),MagickTrue,exception); if (rescale_image == (Image *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); return((Image *) NULL); } if (SetImageStorageClass(rescale_image,DirectClass,exception) == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); rescale_image=DestroyImage(rescale_image); return((Image *) NULL); } rescale_view=AcquireAuthenticCacheView(rescale_image,exception); (void) lqr_carver_scan_reset(carver); while (lqr_carver_scan_ext(carver,&x_offset,&y_offset,(void **) &packet) != 0) { Quantum *magick_restrict p; ssize_t i; p=QueueCacheViewAuthenticPixels(rescale_view,x_offset,y_offset,1,1, exception); if (p == (Quantum *) NULL) break; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel; PixelTrait rescale_traits, traits; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); rescale_traits=GetPixelChannelTraits(rescale_image,channel); if ((traits == UndefinedPixelTrait) || (rescale_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rescale_image,channel,ClampToQuantum(QuantumRange* packet[i]),p); } if (SyncCacheViewAuthenticPixels(rescale_view,exception) == MagickFalse) break; } rescale_view=DestroyCacheView(rescale_view); pixel_info=RelinquishVirtualMemory(pixel_info); lqr_carver_destroy(carver); return(rescale_image); } #else MagickExport Image *LiquidRescaleImage(const Image *image, const size_t magick_unused(columns),const size_t magick_unused(rows), const double magick_unused(delta_x),const double magick_unused(rigidity), ExceptionInfo *exception) { assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); (void) ThrowMagickException(exception,GetMagickModule(),MissingDelegateError, "DelegateLibrarySupportNotBuiltIn","'%s' (LQR)",image->filename); return((Image *) NULL); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagnifyImage() doubles the size of the image with a pixel art scaling % algorithm. % % The format of the MagnifyImage method is: % % Image *MagnifyImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline void CopyPixels(const Quantum *source,const ssize_t source_offset, Quantum *destination,const ssize_t destination_offset,const size_t channels) { ssize_t i; for (i=0; i < (ssize_t) channels; i++) destination[channels*destination_offset+i]=source[source_offset*channels+i]; } static inline void MixPixels(const Quantum *source,const ssize_t *source_offset, const size_t source_size,Quantum *destination, const ssize_t destination_offset,const size_t channels) { ssize_t sum; ssize_t i; for (i=0; i < (ssize_t) channels; i++) { ssize_t j; sum=0; for (j=0; j < (ssize_t) source_size; j++) sum+=source[source_offset[j]*channels+i]; destination[channels*destination_offset+i]=(Quantum) (sum/source_size); } } static inline void Mix2Pixels(const Quantum *source, const ssize_t source_offset1,const ssize_t source_offset2, Quantum *destination,const ssize_t destination_offset,const size_t channels) { const ssize_t offsets[2] = { source_offset1, source_offset2 }; MixPixels(source,offsets,2,destination,destination_offset,channels); } static inline int PixelsEqual(const Quantum *source1,ssize_t offset1, const Quantum *source2,ssize_t offset2,const size_t channels) { ssize_t i; offset1*=channels; offset2*=channels; for (i=0; i < (ssize_t) channels; i++) if (source1[offset1+i] != source2[offset2+i]) return(0); return(1); } static inline void Eagle2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t i; (void) source; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if (PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,0,result,0,channels); if (PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels)) CopyPixels(pixels,2,result,1,channels); if (PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels)) CopyPixels(pixels,6,result,2,channels); if (PixelsEqual(pixels,5,pixels,8,channels) && PixelsEqual(pixels,8,pixels,7,channels)) CopyPixels(pixels,8,result,3,channels); } static void Hq2XHelper(const unsigned int rule,const Quantum *source, Quantum *destination,const ssize_t destination_offset,const size_t channels, const ssize_t e,const ssize_t a,const ssize_t b,const ssize_t d, const ssize_t f,const ssize_t h) { #define caseA(N,A,B,C,D) \ case N: \ { \ const ssize_t \ offsets[4] = { A, B, C, D }; \ \ MixPixels(source,offsets,4,destination,destination_offset,channels);\ break; \ } #define caseB(N,A,B,C,D,E,F,G,H) \ case N: \ { \ const ssize_t \ offsets[8] = { A, B, C, D, E, F, G, H }; \ \ MixPixels(source,offsets,8,destination,destination_offset,channels);\ break; \ } switch (rule) { case 0: { CopyPixels(source,e,destination,destination_offset,channels); break; } caseA(1,e,e,e,a) caseA(2,e,e,e,d) caseA(3,e,e,e,b) caseA(4,e,e,d,b) caseA(5,e,e,a,b) caseA(6,e,e,a,d) caseB(7,e,e,e,e,e,b,b,d) caseB(8,e,e,e,e,e,d,d,b) caseB(9,e,e,e,e,e,e,d,b) caseB(10,e,e,d,d,d,b,b,b) case 11: { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); break; } case 12: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 13: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 14: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[16] = { e, e, e, e, e, e, e, e, e, e, e, e, e, e, d, b }; MixPixels(source,offsets,16,destination,destination_offset,channels); } else CopyPixels(source,e,destination,destination_offset,channels); break; } case 15: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[4] = { e, e, d, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 16: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, e, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 17: { if (PixelsEqual(source,b,source,d,channels)) { const ssize_t offsets[8] = { e, e, d, d, d, b, b, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, a }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } case 18: { if (PixelsEqual(source,b,source,f,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, b, b, d }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, d }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } default: { if (PixelsEqual(source,d,source,h,channels)) { const ssize_t offsets[8] = { e, e, e, e, e, d, d, b }; MixPixels(source,offsets,8,destination,destination_offset,channels); } else { const ssize_t offsets[4] = { e, e, e, b }; MixPixels(source,offsets,4,destination,destination_offset,channels); } break; } } #undef caseA #undef caseB } static inline unsigned int Hq2XPatternToNumber(const int *pattern) { ssize_t i; unsigned int result, order; result=0; order=1; for (i=7; i >= 0; i--) { result+=order*pattern[i]; order*=2; } return(result); } static inline void Hq2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { static const unsigned int Hq2XTable[] = { 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 12, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 18, 4, 4, 6, 18, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 12, 12, 5, 19, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 19, 1, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 18, 5, 3, 16, 12, 5, 19, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 15, 12, 5, 3, 17, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 17, 13, 5, 3, 16, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 13, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 16, 13, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 12, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 16, 12, 5, 3, 1, 14, 4, 4, 6, 2, 4, 4, 6, 2, 5, 3, 1, 12, 5, 3, 1, 14 }; const int pattern1[] = { !PixelsEqual(pixels,4,pixels,8,channels), !PixelsEqual(pixels,4,pixels,7,channels), !PixelsEqual(pixels,4,pixels,6,channels), !PixelsEqual(pixels,4,pixels,5,channels), !PixelsEqual(pixels,4,pixels,3,channels), !PixelsEqual(pixels,4,pixels,2,channels), !PixelsEqual(pixels,4,pixels,1,channels), !PixelsEqual(pixels,4,pixels,0,channels) }; #define Rotated(p) p[2], p[4], p[7], p[1], p[6], p[0], p[3], p[5] const int pattern2[] = { Rotated(pattern1) }; const int pattern3[] = { Rotated(pattern2) }; const int pattern4[] = { Rotated(pattern3) }; #undef Rotated (void) source; Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern1)],pixels,result,0, channels,4,0,1,3,5,7); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern2)],pixels,result,1, channels,4,2,5,1,7,3); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern3)],pixels,result,3, channels,4,8,7,5,3,1); Hq2XHelper(Hq2XTable[Hq2XPatternToNumber(pattern4)],pixels,result,2, channels,4,6,3,7,1,5); } static void Fish2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { #define Corner(A,B,C,D) \ { \ if (intensities[B] > intensities[A]) \ { \ ssize_t \ offsets[3] = { B, C, D }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ else \ { \ ssize_t \ offsets[3] = { A, B, C }; \ \ MixPixels(pixels,offsets,3,result,3,channels); \ } \ } #define Line(A,B,C,D) \ { \ if (intensities[C] > intensities[A]) \ Mix2Pixels(pixels,C,D,result,3,channels); \ else \ Mix2Pixels(pixels,A,B,result,3,channels); \ } MagickFloatType intensities[9]; int ae, bd, ab, ad, be, de; ssize_t i; ssize_t offsets[4] = { 0, 1, 3, 4 }; for (i=0; i < 9; i++) intensities[i]=GetPixelIntensity(source,pixels + i*channels); CopyPixels(pixels,0,result,0,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[1] ? 0 : 1),result, 1,channels); CopyPixels(pixels,(ssize_t) (intensities[0] > intensities[3] ? 0 : 3),result, 2,channels); ae=PixelsEqual(pixels,0,pixels,4,channels); bd=PixelsEqual(pixels,1,pixels,3,channels); ab=PixelsEqual(pixels,0,pixels,1,channels); de=PixelsEqual(pixels,3,pixels,4,channels); ad=PixelsEqual(pixels,0,pixels,3,channels); be=PixelsEqual(pixels,1,pixels,4,channels); if (ae && bd && ab) { CopyPixels(pixels,0,result,3,channels); return; } if (ad && de && !ab) { Corner(1,0,4,3) return; } if (be && de && !ab) { Corner(0,1,3,4) return; } if (ad && ab && !be) { Corner(4,3,1,0) return; } if (ab && be && !ad) { Corner(3,0,4,1) return; } if (ae && (!bd || intensities[1] > intensities[0])) { Mix2Pixels(pixels,0,4,result,3,channels); return; } if (bd && (!ae || intensities[0] > intensities[1])) { Mix2Pixels(pixels,1,3,result,3,channels); return; } if (ab) { Line(0,1,3,4) return; } if (de) { Line(3,4,0,1) return; } if (ad) { Line(0,3,1,4) return; } if (be) { Line(1,4,0,3) return; } MixPixels(pixels,offsets,4,result,3,channels); #undef Corner #undef Line } static void Xbr2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { #define WeightVar(M,N) const int w_##M##_##N = \ PixelsEqual(pixels,M,pixels,N,channels) ? 0 : 1; WeightVar(12,11) WeightVar(12,7) WeightVar(12,13) WeightVar(12,17) WeightVar(12,16) WeightVar(12,8) WeightVar(6,10) WeightVar(6,2) WeightVar(11,7) WeightVar(11,17) WeightVar(11,5) WeightVar(7,13) WeightVar(7,1) WeightVar(12,6) WeightVar(12,18) WeightVar(8,14) WeightVar(8,2) WeightVar(13,17) WeightVar(13,9) WeightVar(7,3) WeightVar(16,10) WeightVar(16,22) WeightVar(17,21) WeightVar(11,15) WeightVar(18,14) WeightVar(18,22) WeightVar(17,23) WeightVar(17,19) #undef WeightVar if ( w_12_16 + w_12_8 + w_6_10 + w_6_2 + (4 * w_11_7) < w_11_17 + w_11_5 + w_7_13 + w_7_1 + (4 * w_12_6) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_7 ? 11 : 7),12,result,0, channels); else CopyPixels(pixels,12,result,0,channels); if ( w_12_18 + w_12_6 + w_8_14 + w_8_2 + (4 * w_7_13) < w_13_17 + w_13_9 + w_11_7 + w_7_3 + (4 * w_12_8) ) Mix2Pixels(pixels,(ssize_t) (w_12_7 <= w_12_13 ? 7 : 13),12,result,1, channels); else CopyPixels(pixels,12,result,1,channels); if ( w_12_6 + w_12_18 + w_16_10 + w_16_22 + (4 * w_11_17) < w_11_7 + w_11_15 + w_13_17 + w_17_21 + (4 * w_12_16) ) Mix2Pixels(pixels,(ssize_t) (w_12_11 <= w_12_17 ? 11 : 17),12,result,2, channels); else CopyPixels(pixels,12,result,2,channels); if ( w_12_8 + w_12_16 + w_18_14 + w_18_22 + (4 * w_13_17) < w_11_17 + w_17_23 + w_17_19 + w_7_13 + (4 * w_12_18) ) Mix2Pixels(pixels,(ssize_t) (w_12_13 <= w_12_17 ? 13 : 17),12,result,3, channels); else CopyPixels(pixels,12,result,3,channels); } static void Scale2X(const Image *source,const Quantum *pixels,Quantum *result, const size_t channels) { if (PixelsEqual(pixels,1,pixels,7,channels) || PixelsEqual(pixels,3,pixels,5,channels)) { ssize_t i; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); return; } if (PixelsEqual(pixels,1,pixels,3,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if (PixelsEqual(pixels,1,pixels,5,channels)) CopyPixels(pixels,5,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,3,channels); else CopyPixels(pixels,4,result,3,channels); } static void Epbx2X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { #define HelperCond(a,b,c,d,e,f,g) ( \ PixelsEqual(pixels,a,pixels,b,channels) && ( \ PixelsEqual(pixels,c,pixels,d,channels) || \ PixelsEqual(pixels,c,pixels,e,channels) || \ PixelsEqual(pixels,a,pixels,f,channels) || \ PixelsEqual(pixels,b,pixels,g,channels) \ ) \ ) ssize_t i; for (i=0; i < 4; i++) CopyPixels(pixels,4,result,i,channels); if ( !PixelsEqual(pixels,3,pixels,5,channels) && !PixelsEqual(pixels,1,pixels,7,channels) && ( PixelsEqual(pixels,4,pixels,3,channels) || PixelsEqual(pixels,4,pixels,7,channels) || PixelsEqual(pixels,4,pixels,5,channels) || PixelsEqual(pixels,4,pixels,1,channels) || ( ( !PixelsEqual(pixels,0,pixels,8,channels) || PixelsEqual(pixels,4,pixels,6,channels) || PixelsEqual(pixels,3,pixels,2,channels) ) && ( !PixelsEqual(pixels,6,pixels,2,channels) || PixelsEqual(pixels,4,pixels,0,channels) || PixelsEqual(pixels,4,pixels,8,channels) ) ) ) ) { if (HelperCond(1,3,4,0,8,2,6)) Mix2Pixels(pixels,1,3,result,0,channels); if (HelperCond(5,1,4,2,6,8,0)) Mix2Pixels(pixels,5,1,result,1,channels); if (HelperCond(3,7,4,6,2,0,8)) Mix2Pixels(pixels,3,7,result,2,channels); if (HelperCond(7,5,4,8,0,6,2)) Mix2Pixels(pixels,7,5,result,3,channels); } #undef HelperCond } static inline void Eagle3X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); if (corner_tl && corner_tr) Mix2Pixels(pixels,0,2,result,1,channels); else CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); if (corner_tl && corner_bl) Mix2Pixels(pixels,0,6,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if (corner_tr && corner_br) Mix2Pixels(pixels,2,8,result,5,channels); else CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); if (corner_bl && corner_br) Mix2Pixels(pixels,6,8,result,7,channels); else CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Eagle3XB(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { ssize_t corner_tl, corner_tr, corner_bl, corner_br; corner_tl=PixelsEqual(pixels,0,pixels,1,channels) && PixelsEqual(pixels,0,pixels,3,channels); corner_tr=PixelsEqual(pixels,1,pixels,2,channels) && PixelsEqual(pixels,2,pixels,5,channels); corner_bl=PixelsEqual(pixels,3,pixels,6,channels) && PixelsEqual(pixels,6,pixels,7,channels); corner_br=PixelsEqual(pixels,5,pixels,7,channels) && PixelsEqual(pixels,7,pixels,8,channels); CopyPixels(pixels,(ssize_t) (corner_tl ? 0 : 4),result,0,channels); CopyPixels(pixels,4,result,1,channels); CopyPixels(pixels,(ssize_t) (corner_tr ? 1 : 4),result,2,channels); CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); CopyPixels(pixels,4,result,5,channels); CopyPixels(pixels,(ssize_t) (corner_bl ? 3 : 4),result,6,channels); CopyPixels(pixels,4,result,7,channels); CopyPixels(pixels,(ssize_t) (corner_br ? 5 : 4),result,8,channels); } static inline void Scale3X(const Image *source,const Quantum *pixels, Quantum *result,const size_t channels) { if (!PixelsEqual(pixels,1,pixels,7,channels) && !PixelsEqual(pixels,3,pixels,5,channels)) { if (PixelsEqual(pixels,3,pixels,1,channels)) CopyPixels(pixels,3,result,0,channels); else CopyPixels(pixels,4,result,0,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) || ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,1,result,1,channels); else CopyPixels(pixels,4,result,1,channels); if (PixelsEqual(pixels,5,pixels,1,channels)) CopyPixels(pixels,5,result,2,channels); else CopyPixels(pixels,4,result,2,channels); if ( ( PixelsEqual(pixels,3,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) || ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,0,channels) ) ) CopyPixels(pixels,3,result,3,channels); else CopyPixels(pixels,4,result,3,channels); CopyPixels(pixels,4,result,4,channels); if ( ( PixelsEqual(pixels,5,pixels,1,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,2,channels) ) ) CopyPixels(pixels,5,result,5,channels); else CopyPixels(pixels,4,result,5,channels); if (PixelsEqual(pixels,3,pixels,7,channels)) CopyPixels(pixels,3,result,6,channels); else CopyPixels(pixels,4,result,6,channels); if ( ( PixelsEqual(pixels,3,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,8,channels) ) || ( PixelsEqual(pixels,5,pixels,7,channels) && !PixelsEqual(pixels,4,pixels,6,channels) ) ) CopyPixels(pixels,7,result,7,channels); else CopyPixels(pixels,4,result,7,channels); if (PixelsEqual(pixels,5,pixels,7,channels)) CopyPixels(pixels,5,result,8,channels); else CopyPixels(pixels,4,result,8,channels); } else { ssize_t i; for (i=0; i < 9; i++) CopyPixels(pixels,4,result,i,channels); } } MagickExport Image *MagnifyImage(const Image *image,ExceptionInfo *exception) { #define MagnifyImageTag "Magnify/Image" CacheView *image_view, *magnify_view; const char *option; Image *source_image, *magnify_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; RectangleInfo rectangle; ssize_t y; unsigned char magnification, width; void (*scaling_method)(const Image *,const Quantum *,Quantum *,size_t); /* Initialize magnified image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); option=GetImageOption(image->image_info,"magnify:method"); if (option == (char *) NULL) option="scale2x"; scaling_method=Scale2X; magnification=1; width=1; switch (*option) { case 'e': { if (LocaleCompare(option,"eagle2x") == 0) { scaling_method=Eagle2X; magnification=2; width=3; break; } if (LocaleCompare(option,"eagle3x") == 0) { scaling_method=Eagle3X; magnification=3; width=3; break; } if (LocaleCompare(option,"eagle3xb") == 0) { scaling_method=Eagle3XB; magnification=3; width=3; break; } if (LocaleCompare(option,"epbx2x") == 0) { scaling_method=Epbx2X; magnification=2; width=3; break; } break; } case 'f': { if (LocaleCompare(option,"fish2x") == 0) { scaling_method=Fish2X; magnification=2; width=3; break; } break; } case 'h': { if (LocaleCompare(option,"hq2x") == 0) { scaling_method=Hq2X; magnification=2; width=3; break; } break; } case 's': { if (LocaleCompare(option,"scale2x") == 0) { scaling_method=Scale2X; magnification=2; width=3; break; } if (LocaleCompare(option,"scale3x") == 0) { scaling_method=Scale3X; magnification=3; width=3; break; } break; } case 'x': { if (LocaleCompare(option,"xbr2x") == 0) { scaling_method=Xbr2X; magnification=2; width=5; } break; } default: break; } /* Make a working copy of the source image and convert it to RGB colorspace. */ source_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (source_image == (Image *) NULL) return((Image *) NULL); offset.x=0; offset.y=0; rectangle.x=0; rectangle.y=0; rectangle.width=image->columns; rectangle.height=image->rows; (void) CopyImagePixels(source_image,image,&rectangle,&offset,exception); (void) SetImageColorspace(source_image,RGBColorspace,exception); magnify_image=CloneImage(source_image,magnification*source_image->columns, magnification*source_image->rows,MagickTrue,exception); if (magnify_image == (Image *) NULL) { source_image=DestroyImage(source_image); return((Image *) NULL); } /* Magnify the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(source_image,exception); magnify_view=AcquireAuthenticCacheView(magnify_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,magnify_image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { Quantum r[128]; /* to hold result pixels */ Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(magnify_view,0,magnification*y, magnify_image->columns,magnification,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } /* Magnify this row of pixels. */ for (x=0; x < (ssize_t) source_image->columns; x++) { const Quantum *magick_restrict p; size_t channels; ssize_t i; ssize_t j; p=GetCacheViewVirtualPixels(image_view,x-width/2,y-width/2,width,width, exception); channels=GetPixelChannels(source_image); scaling_method(source_image,p,r,channels); /* Copy the result pixels into the final image. */ for (j=0; j < (ssize_t) magnification; j++) for (i=0; i < (ssize_t) (channels*magnification); i++) q[j*channels*magnify_image->columns+i]=r[j*magnification*channels+i]; q+=magnification*GetPixelChannels(magnify_image); } if (SyncCacheViewAuthenticPixels(magnify_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,MagnifyImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } magnify_view=DestroyCacheView(magnify_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); if (status == MagickFalse) magnify_image=DestroyImage(magnify_image); return(magnify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M i n i f y I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MinifyImage() is a convenience method that scales an image proportionally to % half its size. % % The format of the MinifyImage method is: % % Image *MinifyImage(const Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MinifyImage(const Image *image,ExceptionInfo *exception) { Image *minify_image; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); minify_image=ResizeImage(image,image->columns/2,image->rows/2,SplineFilter, exception); return(minify_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResampleImage() resize image in terms of its pixel size, so that when % displayed at the given resolution it will be the same size in terms of % real world units as the original image at the original resolution. % % The format of the ResampleImage method is: % % Image *ResampleImage(Image *image,const double x_resolution, % const double y_resolution,const FilterType filter, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image to be resized to fit the given resolution. % % o x_resolution: the new image x resolution. % % o y_resolution: the new image y resolution. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ResampleImage(const Image *image,const double x_resolution, const double y_resolution,const FilterType filter,ExceptionInfo *exception) { #define ResampleImageTag "Resample/Image" Image *resample_image; size_t height, width; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); width=(size_t) (x_resolution*image->columns/(image->resolution.x == 0.0 ? 72.0 : image->resolution.x)+0.5); height=(size_t) (y_resolution*image->rows/(image->resolution.y == 0.0 ? 72.0 : image->resolution.y)+0.5); resample_image=ResizeImage(image,width,height,filter,exception); if (resample_image != (Image *) NULL) { resample_image->resolution.x=x_resolution; resample_image->resolution.y=y_resolution; } return(resample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeImage() scales an image to the desired dimensions, using the given % filter (see AcquireFilterInfo()). % % If an undefined filter is given the filter defaults to Mitchell for a % colormapped image, a image with a matte channel, or if the image is % enlarged. Otherwise the filter defaults to a Lanczos. % % ResizeImage() was inspired by Paul Heckbert's "zoom" program. % % The format of the ResizeImage method is: % % Image *ResizeImage(Image *image,const size_t columns,const size_t rows, % const FilterType filter,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o filter: Image filter to use. % % o exception: return any errors or warnings in this structure. % */ typedef struct _ContributionInfo { double weight; ssize_t pixel; } ContributionInfo; static ContributionInfo **DestroyContributionThreadSet( ContributionInfo **contribution) { ssize_t i; assert(contribution != (ContributionInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (contribution[i] != (ContributionInfo *) NULL) contribution[i]=(ContributionInfo *) RelinquishAlignedMemory( contribution[i]); contribution=(ContributionInfo **) RelinquishMagickMemory(contribution); return(contribution); } static ContributionInfo **AcquireContributionThreadSet(const size_t count) { ssize_t i; ContributionInfo **contribution; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); contribution=(ContributionInfo **) AcquireQuantumMemory(number_threads, sizeof(*contribution)); if (contribution == (ContributionInfo **) NULL) return((ContributionInfo **) NULL); (void) memset(contribution,0,number_threads*sizeof(*contribution)); for (i=0; i < (ssize_t) number_threads; i++) { contribution[i]=(ContributionInfo *) MagickAssumeAligned( AcquireAlignedMemory(count,sizeof(**contribution))); if (contribution[i] == (ContributionInfo *) NULL) return(DestroyContributionThreadSet(contribution)); } return(contribution); } static MagickBooleanType HorizontalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double x_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { #define ResizeImageTag "Resize/Image" CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; MagickBooleanType status; double scale, support; ssize_t x; /* Apply filter to resize horizontally from image to resize image. */ scale=MagickMax(1.0/x_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->columns,1) #endif for (x=0; x < (ssize_t) resize_image->columns; x++) { const int id = GetOpenMPThreadId(); double bisect, density; const Quantum *magick_restrict p; ContributionInfo *magick_restrict contribution; Quantum *magick_restrict q; ssize_t y; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (x+0.5)/x_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->columns); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,contribution[0].pixel,0,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1),image->rows,exception); q=QueueCacheViewAuthenticPixels(resize_view,x,0,1,resize_image->rows, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (y=0; y < (ssize_t) resize_image->rows; y++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j-start].pixel-contribution[0].pixel); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } /* Alpha blending. */ gamma=0.0; for (j=0; j < n; j++) { k=y*(contribution[n-1].pixel-contribution[0].pixel+1)+ (contribution[j].pixel-contribution[0].pixel); alpha=contribution[j].weight*QuantumScale* GetPixelAlpha(image,p+k*GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif (*progress)++; proceed=SetImageProgress(image,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } static MagickBooleanType VerticalFilter( const ResizeFilter *magick_restrict resize_filter, const Image *magick_restrict image,Image *magick_restrict resize_image, const double y_factor,const MagickSizeType span, MagickOffsetType *magick_restrict progress,ExceptionInfo *exception) { CacheView *image_view, *resize_view; ClassType storage_class; ContributionInfo **magick_restrict contributions; double scale, support; MagickBooleanType status; ssize_t y; /* Apply filter to resize vertically from image to resize image. */ scale=MagickMax(1.0/y_factor+MagickEpsilon,1.0); support=scale*GetResizeFilterSupport(resize_filter); storage_class=support > 0.5 ? DirectClass : image->storage_class; if (SetImageStorageClass(resize_image,storage_class,exception) == MagickFalse) return(MagickFalse); if (support < 0.5) { /* Support too small even for nearest neighbour: Reduce to point sampling. */ support=(double) 0.5; scale=1.0; } contributions=AcquireContributionThreadSet((size_t) (2.0*support+3.0)); if (contributions == (ContributionInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } status=MagickTrue; scale=PerceptibleReciprocal(scale); image_view=AcquireVirtualCacheView(image,exception); resize_view=AcquireAuthenticCacheView(resize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,resize_image,resize_image->rows,1) #endif for (y=0; y < (ssize_t) resize_image->rows; y++) { const int id = GetOpenMPThreadId(); double bisect, density; const Quantum *magick_restrict p; ContributionInfo *magick_restrict contribution; Quantum *magick_restrict q; ssize_t x; ssize_t n, start, stop; if (status == MagickFalse) continue; bisect=(double) (y+0.5)/y_factor+MagickEpsilon; start=(ssize_t) MagickMax(bisect-support+0.5,0.0); stop=(ssize_t) MagickMin(bisect+support+0.5,(double) image->rows); density=0.0; contribution=contributions[id]; for (n=0; n < (stop-start); n++) { contribution[n].pixel=start+n; contribution[n].weight=GetResizeFilterWeight(resize_filter,scale* ((double) (start+n)-bisect+0.5)); density+=contribution[n].weight; } if (n == 0) continue; if ((density != 0.0) && (density != 1.0)) { ssize_t i; /* Normalize. */ density=PerceptibleReciprocal(density); for (i=0; i < n; i++) contribution[i].weight*=density; } p=GetCacheViewVirtualPixels(image_view,0,contribution[0].pixel, image->columns,(size_t) (contribution[n-1].pixel-contribution[0].pixel+1), exception); q=QueueCacheViewAuthenticPixels(resize_view,0,y,resize_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) resize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha, gamma, pixel; PixelChannel channel; PixelTrait resize_traits, traits; ssize_t j; ssize_t k; channel=GetPixelChannelChannel(image,i); traits=GetPixelChannelTraits(image,channel); resize_traits=GetPixelChannelTraits(resize_image,channel); if ((traits == UndefinedPixelTrait) || (resize_traits == UndefinedPixelTrait)) continue; if (((resize_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(resize_image,q) <= (QuantumRange/2))) { j=(ssize_t) (MagickMin(MagickMax(bisect,(double) start),(double) stop-1.0)+0.5); k=(ssize_t) ((contribution[j-start].pixel-contribution[0].pixel)* image->columns+x); SetPixelChannel(resize_image,channel,p[k*GetPixelChannels(image)+i], q); continue; } pixel=0.0; if ((resize_traits & BlendPixelTrait) == 0) { /* No alpha blending. */ for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight; pixel+=alpha*p[k*GetPixelChannels(image)+i]; } SetPixelChannel(resize_image,channel,ClampToQuantum(pixel),q); continue; } gamma=0.0; for (j=0; j < n; j++) { k=(ssize_t) ((contribution[j].pixel-contribution[0].pixel)* image->columns+x); alpha=contribution[j].weight*QuantumScale*GetPixelAlpha(image,p+k* GetPixelChannels(image)); pixel+=alpha*p[k*GetPixelChannels(image)+i]; gamma+=alpha; } gamma=PerceptibleReciprocal(gamma); SetPixelChannel(resize_image,channel,ClampToQuantum(gamma*pixel),q); } q+=GetPixelChannels(resize_image); } if (SyncCacheViewAuthenticPixels(resize_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif (*progress)++; proceed=SetImageProgress(image,ResizeImageTag,*progress,span); if (proceed == MagickFalse) status=MagickFalse; } } resize_view=DestroyCacheView(resize_view); image_view=DestroyCacheView(image_view); contributions=DestroyContributionThreadSet(contributions); return(status); } MagickExport Image *ResizeImage(const Image *image,const size_t columns, const size_t rows,const FilterType filter,ExceptionInfo *exception) { double x_factor, y_factor; FilterType filter_type; Image *filter_image, *resize_image; MagickOffsetType offset; MagickSizeType span; MagickStatusType status; ResizeFilter *resize_filter; /* Acquire resize image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows) && (filter == UndefinedFilter)) return(CloneImage(image,0,0,MagickTrue,exception)); /* Acquire resize filter. */ x_factor=(double) columns/(double) image->columns; y_factor=(double) rows/(double) image->rows; filter_type=LanczosFilter; if (filter != UndefinedFilter) filter_type=filter; else if ((x_factor == 1.0) && (y_factor == 1.0)) filter_type=PointFilter; else if ((image->storage_class == PseudoClass) || (image->alpha_trait != UndefinedPixelTrait) || ((x_factor*y_factor) > 1.0)) filter_type=MitchellFilter; resize_filter=AcquireResizeFilter(image,filter_type,MagickFalse,exception); #if defined(MAGICKCORE_OPENCL_SUPPORT) resize_image=AccelerateResizeImage(image,columns,rows,resize_filter, exception); if (resize_image != (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } #endif resize_image=CloneImage(image,columns,rows,MagickTrue,exception); if (resize_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(resize_image); } if (x_factor > y_factor) filter_image=CloneImage(image,columns,image->rows,MagickTrue,exception); else filter_image=CloneImage(image,image->columns,rows,MagickTrue,exception); if (filter_image == (Image *) NULL) { resize_filter=DestroyResizeFilter(resize_filter); return(DestroyImage(resize_image)); } /* Resize image. */ offset=0; if (x_factor > y_factor) { span=(MagickSizeType) (filter_image->columns+rows); status=HorizontalFilter(resize_filter,image,filter_image,x_factor,span, &offset,exception); status&=VerticalFilter(resize_filter,filter_image,resize_image,y_factor, span,&offset,exception); } else { span=(MagickSizeType) (filter_image->rows+columns); status=VerticalFilter(resize_filter,image,filter_image,y_factor,span, &offset,exception); status&=HorizontalFilter(resize_filter,filter_image,resize_image,x_factor, span,&offset,exception); } /* Free resources. */ filter_image=DestroyImage(filter_image); resize_filter=DestroyResizeFilter(resize_filter); if (status == MagickFalse) { resize_image=DestroyImage(resize_image); return((Image *) NULL); } resize_image->type=image->type; return(resize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S a m p l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SampleImage() scales an image to the desired dimensions with pixel % sampling. Unlike other scaling methods, this method does not introduce % any additional color into the scaled image. % % The format of the SampleImage method is: % % Image *SampleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the sampled image. % % o rows: the number of rows in the sampled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SampleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleImageTag "Sample/Image" CacheView *image_view, *sample_view; Image *sample_image; MagickBooleanType status; MagickOffsetType progress; ssize_t x1; ssize_t *x_offset, y; PointInfo sample_offset; /* Initialize sampled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); sample_image=CloneImage(image,columns,rows,MagickTrue,exception); if (sample_image == (Image *) NULL) return((Image *) NULL); /* Set the sampling offset, default is in the mid-point of sample regions. */ sample_offset.x=sample_offset.y=0.5-MagickEpsilon; { const char *value; value=GetImageArtifact(image,"sample:offset"); if (value != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; (void) ParseGeometry(value,&geometry_info); flags=ParseGeometry(value,&geometry_info); sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon; if ((flags & SigmaValue) != 0) sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; } } /* Allocate scan line buffer and column offset buffers. */ x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, sizeof(*x_offset)); if (x_offset == (ssize_t *) NULL) { sample_image=DestroyImage(sample_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (x1=0; x1 < (ssize_t) sample_image->columns; x1++) x_offset[x1]=(ssize_t) ((((double) x1+sample_offset.x)*image->columns)/ sample_image->columns); /* Sample each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sample_view=AcquireAuthenticCacheView(sample_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,sample_image,sample_image->rows,1) #endif for (y=0; y < (ssize_t) sample_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; ssize_t y_offset; if (status == MagickFalse) continue; y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ sample_image->rows); p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, exception); q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } /* Sample each column. */ for (x=0; x < (ssize_t) sample_image->columns; x++) { ssize_t i; if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(sample_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) { PixelChannel channel; PixelTrait image_traits, traits; channel=GetPixelChannelChannel(sample_image,i); traits=GetPixelChannelTraits(sample_image,channel); image_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (image_traits == UndefinedPixelTrait)) continue; SetPixelChannel(sample_image,channel,p[x_offset[x]*GetPixelChannels( image)+i],q); } q+=GetPixelChannels(sample_image); } if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); sample_view=DestroyCacheView(sample_view); x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); sample_image->type=image->type; if (status == MagickFalse) sample_image=DestroyImage(sample_image); return(sample_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleImage() changes the size of an image to the given dimensions. % % The format of the ScaleImage method is: % % Image *ScaleImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ScaleImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define ScaleImageTag "Scale/Image" CacheView *image_view, *scale_view; double alpha, pixel[CompositePixelChannel], *scale_scanline, *scanline, *x_vector, *y_vector; Image *scale_image; MagickBooleanType next_column, next_row, proceed, status; PixelTrait scale_traits; PointInfo scale, span; ssize_t i; ssize_t n, number_rows, y; /* Initialize scaled image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((columns == 0) || (rows == 0)) ThrowImageException(ImageError,"NegativeOrZeroImageSize"); if ((columns == image->columns) && (rows == image->rows)) return(CloneImage(image,0,0,MagickTrue,exception)); scale_image=CloneImage(image,columns,rows,MagickTrue,exception); if (scale_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(scale_image,DirectClass,exception) == MagickFalse) { scale_image=DestroyImage(scale_image); return((Image *) NULL); } /* Allocate memory. */ x_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*x_vector)); scanline=x_vector; if (image->rows != scale_image->rows) scanline=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*scanline)); scale_scanline=(double *) AcquireQuantumMemory((size_t) scale_image->columns, MaxPixelChannels*sizeof(*scale_scanline)); y_vector=(double *) AcquireQuantumMemory((size_t) image->columns, MaxPixelChannels*sizeof(*y_vector)); if ((scanline == (double *) NULL) || (scale_scanline == (double *) NULL) || (x_vector == (double *) NULL) || (y_vector == (double *) NULL)) { if ((image->rows != scale_image->rows) && (scanline != (double *) NULL)) scanline=(double *) RelinquishMagickMemory(scanline); if (scale_scanline != (double *) NULL) scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (x_vector != (double *) NULL) x_vector=(double *) RelinquishMagickMemory(x_vector); if (y_vector != (double *) NULL) y_vector=(double *) RelinquishMagickMemory(y_vector); scale_image=DestroyImage(scale_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Scale image. */ number_rows=0; next_row=MagickTrue; span.y=1.0; scale.y=(double) scale_image->rows/(double) image->rows; (void) memset(y_vector,0,(size_t) MaxPixelChannels*image->columns* sizeof(*y_vector)); n=0; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); scale_view=AcquireAuthenticCacheView(scale_image,exception); for (y=0; y < (ssize_t) scale_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) break; q=QueueCacheViewAuthenticPixels(scale_view,0,y,scale_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } alpha=1.0; if (scale_image->rows == image->rows) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } } else { /* Scale Y direction. */ while (scale.y < span.y) { if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; } for (x=0; x < (ssize_t) image->columns; x++) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) y_vector[x*GetPixelChannels(image)+i]+=scale.y* x_vector[x*GetPixelChannels(image)+i]; span.y-=scale.y; scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } if ((next_row != MagickFalse) && (number_rows < (ssize_t) image->rows)) { /* Read a new scanline. */ p=GetCacheViewVirtualPixels(image_view,0,n++,image->columns,1, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } if (image->alpha_trait != UndefinedPixelTrait) alpha=QuantumScale*GetPixelAlpha(image,p); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & BlendPixelTrait) == 0) { x_vector[x*GetPixelChannels(image)+i]=(double) p[i]; continue; } x_vector[x*GetPixelChannels(image)+i]=alpha*p[i]; } p+=GetPixelChannels(image); } number_rows++; next_row=MagickFalse; } for (x=0; x < (ssize_t) image->columns; x++) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { pixel[i]=y_vector[x*GetPixelChannels(image)+i]+span.y* x_vector[x*GetPixelChannels(image)+i]; scanline[x*GetPixelChannels(image)+i]=pixel[i]; y_vector[x*GetPixelChannels(image)+i]=0.0; } } scale.y-=span.y; if (scale.y <= 0) { scale.y=(double) scale_image->rows/(double) image->rows; next_row=MagickTrue; } span.y=1.0; } if (scale_image->columns == image->columns) { /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha*scanline[ x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } else { ssize_t t; /* Scale X direction. */ for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; span.x=1.0; t=0; for (x=0; x < (ssize_t) image->columns; x++) { scale.x=(double) scale_image->columns/(double) image->columns; while (scale.x >= span.x) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; pixel[i]+=span.x*scanline[x*GetPixelChannels(image)+i]; scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; } scale.x-=span.x; span.x=1.0; next_column=MagickTrue; } if (scale.x > 0) { if (next_column != MagickFalse) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]=0.0; next_column=MagickFalse; t++; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=scale.x*scanline[x*GetPixelChannels(image)+i]; span.x-=scale.x; } } if (span.x > 0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) pixel[i]+=span.x*scanline[(x-1)*GetPixelChannels(image)+i]; } if ((next_column == MagickFalse) && (t < (ssize_t) scale_image->columns)) for (i=0; i < (ssize_t) GetPixelChannels(image); i++) scale_scanline[t*GetPixelChannels(image)+i]=pixel[i]; /* Transfer scanline to scaled image. */ for (x=0; x < (ssize_t) scale_image->columns; x++) { if (GetPixelWriteMask(scale_image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(scale_image); continue; } if (image->alpha_trait != UndefinedPixelTrait) { alpha=QuantumScale*scale_scanline[x*GetPixelChannels(image)+ GetPixelChannelOffset(image,AlphaPixelChannel)]; alpha=PerceptibleReciprocal(alpha); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); scale_traits=GetPixelChannelTraits(scale_image,channel); if ((traits == UndefinedPixelTrait) || (scale_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) { SetPixelChannel(scale_image,channel,ClampToQuantum( scale_scanline[x*GetPixelChannels(image)+i]),q); continue; } SetPixelChannel(scale_image,channel,ClampToQuantum(alpha* scale_scanline[x*GetPixelChannels(image)+i]),q); } q+=GetPixelChannels(scale_image); } } if (SyncCacheViewAuthenticPixels(scale_view,exception) == MagickFalse) { status=MagickFalse; break; } proceed=SetImageProgress(image,ScaleImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) { status=MagickFalse; break; } } scale_view=DestroyCacheView(scale_view); image_view=DestroyCacheView(image_view); /* Free allocated memory. */ y_vector=(double *) RelinquishMagickMemory(y_vector); scale_scanline=(double *) RelinquishMagickMemory(scale_scanline); if (scale_image->rows != image->rows) scanline=(double *) RelinquishMagickMemory(scanline); x_vector=(double *) RelinquishMagickMemory(x_vector); scale_image->type=image->type; if (status == MagickFalse) scale_image=DestroyImage(scale_image); return(scale_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T h u m b n a i l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ThumbnailImage() changes the size of an image to the given dimensions and % removes any associated profiles. The goal is to produce small low cost % thumbnail images suited for display on the Web. % % The format of the ThumbnailImage method is: % % Image *ThumbnailImage(const Image *image,const size_t columns, % const size_t rows,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o columns: the number of columns in the scaled image. % % o rows: the number of rows in the scaled image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ThumbnailImage(const Image *image,const size_t columns, const size_t rows,ExceptionInfo *exception) { #define SampleFactor 5 char filename[MagickPathExtent], value[MagickPathExtent]; const char *name; Image *thumbnail_image; double x_factor, y_factor; struct stat attributes; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); x_factor=(double) columns/(double) image->columns; y_factor=(double) rows/(double) image->rows; if ((x_factor*y_factor) > 0.1) thumbnail_image=ResizeImage(image,columns,rows,image->filter,exception); else if (((SampleFactor*columns) < 128) || ((SampleFactor*rows) < 128)) thumbnail_image=ResizeImage(image,columns,rows,image->filter,exception); else { Image *sample_image; sample_image=SampleImage(image,SampleFactor*columns,SampleFactor*rows, exception); if (sample_image == (Image *) NULL) return((Image *) NULL); thumbnail_image=ResizeImage(sample_image,columns,rows,image->filter, exception); sample_image=DestroyImage(sample_image); } if (thumbnail_image == (Image *) NULL) return(thumbnail_image); (void) ParseAbsoluteGeometry("0x0+0+0",&thumbnail_image->page); if (thumbnail_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(thumbnail_image,OpaqueAlphaChannel,exception); thumbnail_image->depth=8; thumbnail_image->interlace=NoInterlace; /* Strip all profiles except color profiles. */ ResetImageProfileIterator(thumbnail_image); for (name=GetNextImageProfile(thumbnail_image); name != (const char *) NULL; ) { if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) { (void) DeleteImageProfile(thumbnail_image,name); ResetImageProfileIterator(thumbnail_image); } name=GetNextImageProfile(thumbnail_image); } (void) DeleteImageProperty(thumbnail_image,"comment"); (void) CopyMagickString(value,image->magick_filename,MagickPathExtent); if (strstr(image->magick_filename,"//") == (char *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"file://%s", image->magick_filename); (void) SetImageProperty(thumbnail_image,"Thumb::URI",value,exception); GetPathComponent(image->magick_filename,TailPath,filename); (void) CopyMagickString(value,filename,MagickPathExtent); if ( GetPathAttributes(image->filename,&attributes) != MagickFalse ) (void) FormatImageProperty(thumbnail_image,"Thumb::MTime","%.20g",(double) attributes.st_mtime); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) attributes.st_mtime); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B",MagickPathExtent, value); (void) SetImageProperty(thumbnail_image,"Thumb::Size",value,exception); (void) FormatLocaleString(value,MagickPathExtent,"image/%s",image->magick); LocaleLower(value); (void) SetImageProperty(thumbnail_image,"Thumb::Mimetype",value,exception); (void) SetImageProperty(thumbnail_image,"software",MagickAuthoritativeURL, exception); (void) FormatImageProperty(thumbnail_image,"Thumb::Image::Width","%.20g", (double) image->magick_columns); (void) FormatImageProperty(thumbnail_image,"Thumb::Image::Height","%.20g", (double) image->magick_rows); (void) FormatImageProperty(thumbnail_image,"Thumb::Document::Pages","%.20g", (double) GetImageListLength(image)); return(thumbnail_image); }
convolution_3x3_pack4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void conv3x3s1_winograd64_transform_kernel_pack4_neon(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch) { // winograd63 transform kernel Mat kernel_tm; kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 64-inch-outch // dst = 4b-4a-inch/4a-64-outch/4b; #if __aarch64__ kernel_tm_pack4.create(2 * inch / 4, 64, (outch / 4) / 2 + (outch / 4) % 2, (size_t)4u * 16, 16); #else kernel_tm_pack4.create(inch / 4, 64, outch / 4, (size_t)4u * 16, 16); #endif int q = 0; #if __aarch64__ for (; q + 7 < outch; q += 8) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); const Mat k4 = kernel_tm.channel(q + 4); const Mat k5 = kernel_tm.channel(q + 5); const Mat k6 = kernel_tm.channel(q + 6); const Mat k7 = kernel_tm.channel(q + 7); Mat g0 = kernel_tm_pack4.channel(q / 8); for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int p = 0; p + 3 < inch; p += 4) { 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* 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* 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* 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* 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* 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* 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* 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); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k40[k]; g00[5] = k50[k]; g00[6] = k60[k]; g00[7] = k70[k]; g00[8] = k01[k]; g00[9] = k11[k]; g00[10] = k21[k]; g00[11] = k31[k]; g00[12] = k41[k]; g00[13] = k51[k]; g00[14] = k61[k]; g00[15] = k71[k]; g00[16] = k02[k]; g00[17] = k12[k]; g00[18] = k22[k]; g00[19] = k32[k]; g00[20] = k42[k]; g00[21] = k52[k]; g00[22] = k62[k]; g00[23] = k72[k]; g00[24] = k03[k]; g00[25] = k13[k]; g00[26] = k23[k]; g00[27] = k33[k]; g00[28] = k43[k]; g00[29] = k53[k]; g00[30] = k63[k]; g00[31] = k73[k]; g00 += 32; } } } #endif // __aarch64__ for (; q + 3 < outch; q += 4) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); #if __aarch64__ Mat g0 = kernel_tm_pack4.channel(q / 8 + (q % 8) / 4); #else Mat g0 = kernel_tm_pack4.channel(q / 4); #endif for (int k = 0; k < 64; k++) { float* g00 = g0.row(k); for (int p = 0; p + 3 < inch; p += 4) { 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* 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* 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* 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); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k01[k]; g00[5] = k11[k]; g00[6] = k21[k]; g00[7] = k31[k]; g00[8] = k02[k]; g00[9] = k12[k]; g00[10] = k22[k]; g00[11] = k32[k]; g00[12] = k03[k]; g00[13] = k13[k]; g00[14] = k23[k]; g00[15] = k33[k]; g00 += 16; } } } } static void conv3x3s1_winograd64_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8][4]; // tile for (int i = 0; i < h_tm / 8; i++) { for (int j = 0; j < w_tm / 8; j++) { const float* r0 = img0.row(i * 6) + (j * 6) * 4; for (int m = 0; m < 8; m++) { float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r01 = vld1q_f32(r0 + 4); float32x4_t _r02 = vld1q_f32(r0 + 8); float32x4_t _r03 = vld1q_f32(r0 + 12); float32x4_t _r04 = vld1q_f32(r0 + 16); float32x4_t _r05 = vld1q_f32(r0 + 20); float32x4_t _r06 = vld1q_f32(r0 + 24); float32x4_t _r07 = vld1q_f32(r0 + 28); float32x4_t _tmp0m = vmlaq_n_f32(vsubq_f32(_r00, _r06), vsubq_f32(_r04, _r02), 5.25f); float32x4_t _tmp7m = vmlaq_n_f32(vsubq_f32(_r07, _r01), vsubq_f32(_r03, _r05), 5.25f); vst1q_f32(tmp[0][m], _tmp0m); vst1q_f32(tmp[7][m], _tmp7m); // tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; // tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_r02, _r06), _r04, 4.25f); float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_r01, _r05), _r03, 4.25f); // float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); // float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); float32x4_t _tmp1m = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _tmp2m = vsubq_f32(_tmp12a, _tmp12b); vst1q_f32(tmp[1][m], _tmp1m); vst1q_f32(tmp[2][m], _tmp2m); // tmp[1][m] = tmp12a + tmp12b; // tmp[2][m] = tmp12a - tmp12b; float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_r06, _r02, 0.25f), _r04, 1.25f); float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 0.5f), _r03, 2.5f), _r05, 2.f); // float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); // float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); float32x4_t _tmp3m = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _tmp4m = vsubq_f32(_tmp34a, _tmp34b); vst1q_f32(tmp[3][m], _tmp3m); vst1q_f32(tmp[4][m], _tmp4m); // tmp[3][m] = tmp34a + tmp34b; // tmp[4][m] = tmp34a - tmp34b; float32x4_t _tmp56a = vmlaq_n_f32(_r06, vmlsq_n_f32(_r02, _r04, 1.25f), 4.f); float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_r01, 2.f), _r03, 2.5f), _r05, 0.5f); // float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); // float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); float32x4_t _tmp5m = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _tmp6m = vsubq_f32(_tmp56a, _tmp56b); vst1q_f32(tmp[5][m], _tmp5m); vst1q_f32(tmp[6][m], _tmp6m); // tmp[5][m] = tmp56a + tmp56b; // tmp[6][m] = tmp56a - tmp56b; r0 += w * 4; } float* r0_tm_0 = (float*)img0_tm + (i * w_tm / 8 + j) * 4; float* r0_tm_1 = r0_tm_0 + tiles * 4; float* r0_tm_2 = r0_tm_0 + tiles * 8; float* r0_tm_3 = r0_tm_0 + tiles * 12; float* r0_tm_4 = r0_tm_0 + tiles * 16; float* r0_tm_5 = r0_tm_0 + tiles * 20; float* r0_tm_6 = r0_tm_0 + tiles * 24; float* r0_tm_7 = r0_tm_0 + tiles * 28; for (int m = 0; m < 8; m++) { float32x4_t _tmp00 = vld1q_f32(tmp[m][0]); float32x4_t _tmp01 = vld1q_f32(tmp[m][1]); float32x4_t _tmp02 = vld1q_f32(tmp[m][2]); float32x4_t _tmp03 = vld1q_f32(tmp[m][3]); float32x4_t _tmp04 = vld1q_f32(tmp[m][4]); float32x4_t _tmp05 = vld1q_f32(tmp[m][5]); float32x4_t _tmp06 = vld1q_f32(tmp[m][6]); float32x4_t _tmp07 = vld1q_f32(tmp[m][7]); float32x4_t _r0tm0 = vmlaq_n_f32(vsubq_f32(_tmp00, _tmp06), vsubq_f32(_tmp04, _tmp02), 5.25f); float32x4_t _r0tm7 = vmlaq_n_f32(vsubq_f32(_tmp07, _tmp01), vsubq_f32(_tmp03, _tmp05), 5.25f); // r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; // r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float32x4_t _tmp12a = vmlsq_n_f32(vaddq_f32(_tmp02, _tmp06), _tmp04, 4.25f); float32x4_t _tmp12b = vmlsq_n_f32(vaddq_f32(_tmp01, _tmp05), _tmp03, 4.25f); // float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); // float tmp12b = (tmp0[1] + tmp0[5] - tmp0[3] * 4.25); float32x4_t _r0tm1 = vaddq_f32(_tmp12a, _tmp12b); float32x4_t _r0tm2 = vsubq_f32(_tmp12a, _tmp12b); // r0_tm[1] = tmp12a + tmp12b; // r0_tm[2] = tmp12a - tmp12b; float32x4_t _tmp34a = vmlsq_n_f32(vmlaq_n_f32(_tmp06, _tmp02, 0.25f), _tmp04, 1.25f); float32x4_t _tmp34b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 0.5f), _tmp03, 2.5f), _tmp05, 2.f); // float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); // float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); float32x4_t _r0tm3 = vaddq_f32(_tmp34a, _tmp34b); float32x4_t _r0tm4 = vsubq_f32(_tmp34a, _tmp34b); // r0_tm[3] = tmp34a + tmp34b; // r0_tm[4] = tmp34a - tmp34b; float32x4_t _tmp56a = vmlaq_n_f32(_tmp06, vmlsq_n_f32(_tmp02, _tmp04, 1.25f), 4.f); float32x4_t _tmp56b = vmlaq_n_f32(vmlsq_n_f32(vmulq_n_f32(_tmp01, 2.f), _tmp03, 2.5f), _tmp05, 0.5f); // float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); // float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); float32x4_t _r0tm5 = vaddq_f32(_tmp56a, _tmp56b); float32x4_t _r0tm6 = vsubq_f32(_tmp56a, _tmp56b); // r0_tm[5] = tmp56a + tmp56b; // r0_tm[6] = tmp56a - tmp56b; vst1q_f32(r0_tm_0, _r0tm0); vst1q_f32(r0_tm_1, _r0tm1); vst1q_f32(r0_tm_2, _r0tm2); vst1q_f32(r0_tm_3, _r0tm3); vst1q_f32(r0_tm_4, _r0tm4); vst1q_f32(r0_tm_5, _r0tm5); vst1q_f32(r0_tm_6, _r0tm6); vst1q_f32(r0_tm_7, _r0tm7); r0_tm_0 += tiles * 32; r0_tm_1 += tiles * 32; r0_tm_2 += tiles * 32; r0_tm_3 += tiles * 32; r0_tm_4 += tiles * 32; r0_tm_5 += tiles * 32; r0_tm_6 += tiles * 32; r0_tm_7 += tiles * 32; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __aarch64__ if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator); #else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 64, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, elemsize, elempack, opt.workspace_allocator); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { float* tm2p = tm2.row(i / 12); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v8.4s, v9.4s, v10.4s, v11.4s}, [%0] \n" "st1 {v0.4s}, [%1], #16 \n" "st1 {v4.4s}, [%1], #16 \n" "st1 {v8.4s}, [%1], #16 \n" "sub %0, %0, #128 \n" "st1 {v1.4s}, [%1], #16 \n" "st1 {v5.4s}, [%1], #16 \n" "st1 {v9.4s}, [%1], #16 \n" "st1 {v2.4s}, [%1], #16 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v10.4s}, [%1], #16 \n" "st1 {v3.4s}, [%1], #16 \n" "st1 {v7.4s}, [%1], #16 \n" "st1 {v11.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"); r0 += bottom_blob_tm.cstep * 4; } } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8); #else float* tm2p = tm2.row(i / 8); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" "sub %0, %0, #64 \n" "st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"); #else asm volatile( "pld [%0, #512] \n" "vldm %0!, {d0-d7} \n" "pld [%0, #512] \n" "vldm %0, {d16-d23} \n" // transpose 8x4 "vtrn.32 q0, q1 \n" "vtrn.32 q2, q3 \n" "vtrn.32 q8, q9 \n" "vtrn.32 q10, q11 \n" "vswp d1, d4 \n" "vswp d3, d6 \n" "vswp d17, d20 \n" "vswp d19, d22 \n" "vswp q1, q8 \n" "vswp q3, q10 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "sub %0, %0, #64 \n" "vst1.f32 {d4-d7}, [%1 :128]! \n" "vst1.f32 {d20-d23}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11"); #endif r0 += bottom_blob_tm.cstep * 4; } } for (; i + 3 < tiles; i += 4) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); #else asm volatile( "pld [%0, #512] \n" "vldm %0, {d0-d7} \n" "vstm %1!, {d0-d7} \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } for (; i + 1 < tiles; i += 2) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v0.4s, v1.4s}, [%0] \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1"); #else asm volatile( "pld [%0, #256] \n" "vld1.f32 {d0-d3}, [%0 :128] \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } for (; i < tiles; i++) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.4s}, [%0] \n" "st1 {v0.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0"); #else asm volatile( "pld [%0, #128] \n" "vld1.f32 {d0-d1}, [%0 :128] \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, elemsize, elempack, opt.workspace_allocator); int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ int nn_outch = 0; nn_outch = outch >> 1; remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); const Mat kernel01_tm = kernel_tm.channel(pp); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w0011_01 "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "fmla v16.4s, v4.4s, v2.s[0] \n" "fmla v17.4s, v4.4s, v2.s[1] \n" "fmla v18.4s, v4.4s, v2.s[2] \n" "fmla v19.4s, v4.4s, v2.s[3] \n" "fmla v20.4s, v5.4s, v0.s[0] \n" "fmla v21.4s, v5.4s, v0.s[1] \n" "fmla v22.4s, v5.4s, v0.s[2] \n" "fmla v23.4s, v5.4s, v0.s[3] \n" "fmla v24.4s, v5.4s, v1.s[0] \n" "fmla v25.4s, v5.4s, v1.s[1] \n" "fmla v26.4s, v5.4s, v1.s[2] \n" "fmla v27.4s, v5.4s, v1.s[3] \n" "fmla v28.4s, v5.4s, v2.s[0] \n" "fmla v29.4s, v5.4s, v2.s[1] \n" "fmla v30.4s, v5.4s, v2.s[2] \n" "fmla v31.4s, v5.4s, v2.s[3] \n" "fmla v8.4s, v6.4s, v3.s[0] \n" "fmla v9.4s, v6.4s, v3.s[1] \n" "fmla v10.4s, v6.4s, v3.s[2] \n" "fmla v11.4s, v6.4s, v3.s[3] \n" "fmla v20.4s, v7.4s, v3.s[0] \n" "fmla v21.4s, v7.4s, v3.s[1] \n" "fmla v22.4s, v7.4s, v3.s[2] \n" "fmla v23.4s, v7.4s, v3.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "fmla v12.4s, v6.4s, v0.s[0] \n" "fmla v13.4s, v6.4s, v0.s[1] \n" "fmla v14.4s, v6.4s, v0.s[2] \n" "fmla v15.4s, v6.4s, v0.s[3] \n" "fmla v16.4s, v6.4s, v1.s[0] \n" "fmla v17.4s, v6.4s, v1.s[1] \n" "fmla v18.4s, v6.4s, v1.s[2] \n" "fmla v19.4s, v6.4s, v1.s[3] \n" "fmla v24.4s, v7.4s, v0.s[0] \n" "fmla v25.4s, v7.4s, v0.s[1] \n" "fmla v26.4s, v7.4s, v0.s[2] \n" "fmla v27.4s, v7.4s, v0.s[3] \n" "fmla v28.4s, v7.4s, v1.s[0] \n" "fmla v29.4s, v7.4s, v1.s[1] \n" "fmla v30.4s, v7.4s, v1.s[2] \n" "fmla v31.4s, v7.4s, v1.s[3] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w2233_01 "fmla v8.4s, v4.4s, v2.s[0] \n" "fmla v9.4s, v4.4s, v2.s[1] \n" "fmla v10.4s, v4.4s, v2.s[2] \n" "fmla v11.4s, v4.4s, v2.s[3] \n" "fmla v12.4s, v4.4s, v3.s[0] \n" "fmla v13.4s, v4.4s, v3.s[1] \n" "fmla v14.4s, v4.4s, v3.s[2] \n" "fmla v15.4s, v4.4s, v3.s[3] \n" "fmla v20.4s, v5.4s, v2.s[0] \n" "fmla v21.4s, v5.4s, v2.s[1] \n" "fmla v22.4s, v5.4s, v2.s[2] \n" "fmla v23.4s, v5.4s, v2.s[3] \n" "fmla v24.4s, v5.4s, v3.s[0] \n" "fmla v25.4s, v5.4s, v3.s[1] \n" "fmla v26.4s, v5.4s, v3.s[2] \n" "fmla v27.4s, v5.4s, v3.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "fmla v16.4s, v4.4s, v0.s[0] \n" "fmla v17.4s, v4.4s, v0.s[1] \n" "fmla v18.4s, v4.4s, v0.s[2] \n" "fmla v19.4s, v4.4s, v0.s[3] \n" "fmla v28.4s, v5.4s, v0.s[0] \n" "fmla v29.4s, v5.4s, v0.s[1] \n" "fmla v30.4s, v5.4s, v0.s[2] \n" "fmla v31.4s, v5.4s, v0.s[3] \n" "fmla v8.4s, v6.4s, v1.s[0] \n" "fmla v9.4s, v6.4s, v1.s[1] \n" "fmla v10.4s, v6.4s, v1.s[2] \n" "fmla v11.4s, v6.4s, v1.s[3] \n" "fmla v12.4s, v6.4s, v2.s[0] \n" "fmla v13.4s, v6.4s, v2.s[1] \n" "fmla v14.4s, v6.4s, v2.s[2] \n" "fmla v15.4s, v6.4s, v2.s[3] \n" "fmla v16.4s, v6.4s, v3.s[0] \n" "fmla v17.4s, v6.4s, v3.s[1] \n" "fmla v18.4s, v6.4s, v3.s[2] \n" "fmla v19.4s, v6.4s, v3.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v20.4s, v7.4s, v1.s[0] \n" "fmla v21.4s, v7.4s, v1.s[1] \n" "fmla v22.4s, v7.4s, v1.s[2] \n" "fmla v23.4s, v7.4s, v1.s[3] \n" "fmla v24.4s, v7.4s, v2.s[0] \n" "fmla v25.4s, v7.4s, v2.s[1] \n" "fmla v26.4s, v7.4s, v2.s[2] \n" "fmla v27.4s, v7.4s, v2.s[3] \n" "fmla v28.4s, v7.4s, v3.s[0] \n" "fmla v29.4s, v7.4s, v3.s[1] \n" "fmla v30.4s, v7.4s, v3.s[2] \n" "fmla v31.4s, v7.4s, v3.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" "st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "prfm pldl1keep, [%3, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // r4 r5 r6 r7 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v20.4s, v8.4s, v4.s[0] \n" "fmla v21.4s, v8.4s, v5.s[0] \n" "fmla v22.4s, v8.4s, v6.s[0] \n" "fmla v23.4s, v8.4s, v7.s[0] \n" "fmla v24.4s, v9.4s, v0.s[0] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v26.4s, v9.4s, v2.s[0] \n" "fmla v27.4s, v9.4s, v3.s[0] \n" "fmla v28.4s, v9.4s, v4.s[0] \n" "fmla v29.4s, v9.4s, v5.s[0] \n" "fmla v30.4s, v9.4s, v6.s[0] \n" "fmla v31.4s, v9.4s, v7.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v19.4s, v10.4s, v3.s[1] \n" "fmla v20.4s, v10.4s, v4.s[1] \n" "fmla v21.4s, v10.4s, v5.s[1] \n" "fmla v22.4s, v10.4s, v6.s[1] \n" "fmla v23.4s, v10.4s, v7.s[1] \n" "fmla v24.4s, v11.4s, v0.s[1] \n" "fmla v25.4s, v11.4s, v1.s[1] \n" "fmla v26.4s, v11.4s, v2.s[1] \n" "fmla v27.4s, v11.4s, v3.s[1] \n" "fmla v28.4s, v11.4s, v4.s[1] \n" "fmla v29.4s, v11.4s, v5.s[1] \n" "fmla v30.4s, v11.4s, v6.s[1] \n" "fmla v31.4s, v11.4s, v7.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v12.4s, v2.s[2] \n" "fmla v19.4s, v12.4s, v3.s[2] \n" "fmla v20.4s, v12.4s, v4.s[2] \n" "fmla v21.4s, v12.4s, v5.s[2] \n" "fmla v22.4s, v12.4s, v6.s[2] \n" "fmla v23.4s, v12.4s, v7.s[2] \n" "fmla v24.4s, v13.4s, v0.s[2] \n" "fmla v25.4s, v13.4s, v1.s[2] \n" "fmla v26.4s, v13.4s, v2.s[2] \n" "fmla v27.4s, v13.4s, v3.s[2] \n" "fmla v28.4s, v13.4s, v4.s[2] \n" "fmla v29.4s, v13.4s, v5.s[2] \n" "fmla v30.4s, v13.4s, v6.s[2] \n" "fmla v31.4s, v13.4s, v7.s[2] \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v14.4s, v2.s[3] \n" "fmla v19.4s, v14.4s, v3.s[3] \n" "fmla v20.4s, v14.4s, v4.s[3] \n" "fmla v21.4s, v14.4s, v5.s[3] \n" "fmla v22.4s, v14.4s, v6.s[3] \n" "fmla v23.4s, v14.4s, v7.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v24.4s, v15.4s, v0.s[3] \n" "fmla v25.4s, v15.4s, v1.s[3] \n" "fmla v26.4s, v15.4s, v2.s[3] \n" "fmla v27.4s, v15.4s, v3.s[3] \n" "fmla v28.4s, v15.4s, v4.s[3] \n" "fmla v29.4s, v15.4s, v5.s[3] \n" "fmla v30.4s, v15.4s, v6.s[3] \n" "fmla v31.4s, v15.4s, v7.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v20.4s, v9.4s, v0.s[0] \n" "fmla v21.4s, v9.4s, v1.s[0] \n" "fmla v22.4s, v9.4s, v2.s[0] \n" "fmla v23.4s, v9.4s, v3.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v19.4s, v10.4s, v3.s[1] \n" "fmla v20.4s, v11.4s, v0.s[1] \n" "fmla v21.4s, v11.4s, v1.s[1] \n" "fmla v22.4s, v11.4s, v2.s[1] \n" "fmla v23.4s, v11.4s, v3.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v12.4s, v2.s[2] \n" "fmla v19.4s, v12.4s, v3.s[2] \n" "fmla v20.4s, v13.4s, v0.s[2] \n" "fmla v21.4s, v13.4s, v1.s[2] \n" "fmla v22.4s, v13.4s, v2.s[2] \n" "fmla v23.4s, v13.4s, v3.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v14.4s, v2.s[3] \n" "fmla v19.4s, v14.4s, v3.s[3] \n" "fmla v20.4s, v15.4s, v0.s[3] \n" "fmla v21.4s, v15.4s, v1.s[3] \n" "fmla v22.4s, v15.4s, v2.s[3] \n" "fmla v23.4s, v15.4s, v3.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); } for (; i + 1 < tiles; i += 2) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v0.4s, v1.4s}, [%3], #32 \n" // r0 r1 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v9.4s, v0.s[0] \n" "fmla v19.4s, v9.4s, v1.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v11.4s, v0.s[1] \n" "fmla v19.4s, v11.4s, v1.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v13.4s, v0.s[2] \n" "fmla v19.4s, v13.4s, v1.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v15.4s, v0.s[3] \n" "fmla v19.4s, v15.4s, v1.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" "st1 {v18.4s, v19.4s}, [%2], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"); } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "0: \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v0.4s}, [%3], #16 \n" // r0 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v11.4s, v0.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v13.4s, v0.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v15.4s, v0.s[3] \n" "bne 0b \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17"); } } } #endif // __ARM_NEON && __aarch64__ #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); #if __aarch64__ const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2); #else const Mat kernel0_tm = kernel_tm.channel(p); #endif for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // w0123_0 "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "fmla v16.4s, v4.4s, v2.s[0] \n" "fmla v17.4s, v4.4s, v2.s[1] \n" "fmla v18.4s, v4.4s, v2.s[2] \n" "fmla v19.4s, v4.4s, v2.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" "fmla v8.4s, v5.4s, v3.s[0] \n" "fmla v9.4s, v5.4s, v3.s[1] \n" "fmla v10.4s, v5.4s, v3.s[2] \n" "fmla v11.4s, v5.4s, v3.s[3] \n" "fmla v12.4s, v5.4s, v20.s[0] \n" "fmla v13.4s, v5.4s, v20.s[1] \n" "fmla v14.4s, v5.4s, v20.s[2] \n" "fmla v15.4s, v5.4s, v20.s[3] \n" "fmla v16.4s, v5.4s, v21.s[0] \n" "fmla v17.4s, v5.4s, v21.s[1] \n" "fmla v18.4s, v5.4s, v21.s[2] \n" "fmla v19.4s, v5.4s, v21.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "fmla v8.4s, v6.4s, v22.s[0] \n" "fmla v9.4s, v6.4s, v22.s[1] \n" "fmla v10.4s, v6.4s, v22.s[2] \n" "fmla v11.4s, v6.4s, v22.s[3] \n" "fmla v12.4s, v6.4s, v23.s[0] \n" "fmla v13.4s, v6.4s, v23.s[1] \n" "fmla v14.4s, v6.4s, v23.s[2] \n" "fmla v15.4s, v6.4s, v23.s[3] \n" "fmla v16.4s, v6.4s, v24.s[0] \n" "fmla v17.4s, v6.4s, v24.s[1] \n" "fmla v18.4s, v6.4s, v24.s[2] \n" "fmla v19.4s, v6.4s, v24.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v7.4s, v25.s[0] \n" "fmla v9.4s, v7.4s, v25.s[1] \n" "fmla v10.4s, v7.4s, v25.s[2] \n" "fmla v11.4s, v7.4s, v25.s[3] \n" "fmla v12.4s, v7.4s, v26.s[0] \n" "fmla v13.4s, v7.4s, v26.s[1] \n" "fmla v14.4s, v7.4s, v26.s[2] \n" "fmla v15.4s, v7.4s, v26.s[3] \n" "fmla v16.4s, v7.4s, v27.s[0] \n" "fmla v17.4s, v7.4s, v27.s[1] \n" "fmla v18.4s, v7.4s, v27.s[2] \n" "fmla v19.4s, v7.4s, v27.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" "st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8); #else const float* r0 = bb2.row(i / 8); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n" // r4 r5 r6 r7 "fmla v20.4s, v8.4s, v4.s[0] \n" "fmla v21.4s, v8.4s, v5.s[0] \n" "fmla v22.4s, v8.4s, v6.s[0] \n" "fmla v23.4s, v8.4s, v7.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v18.4s, v9.4s, v2.s[1] \n" "fmla v19.4s, v9.4s, v3.s[1] \n" "fmla v20.4s, v9.4s, v4.s[1] \n" "fmla v21.4s, v9.4s, v5.s[1] \n" "fmla v22.4s, v9.4s, v6.s[1] \n" "fmla v23.4s, v9.4s, v7.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "fmla v18.4s, v10.4s, v2.s[2] \n" "fmla v19.4s, v10.4s, v3.s[2] \n" "fmla v20.4s, v10.4s, v4.s[2] \n" "fmla v21.4s, v10.4s, v5.s[2] \n" "fmla v22.4s, v10.4s, v6.s[2] \n" "fmla v23.4s, v10.4s, v7.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "fmla v18.4s, v11.4s, v2.s[3] \n" "fmla v19.4s, v11.4s, v3.s[3] \n" "fmla v20.4s, v11.4s, v4.s[3] \n" "fmla v21.4s, v11.4s, v5.s[3] \n" "fmla v22.4s, v11.4s, v6.s[3] \n" "fmla v23.4s, v11.4s, v7.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "veor q12, q12 \n" "veor q13, q13 \n" "veor q14, q14 \n" "veor q15, q15 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "vmla.f32 q12, q4, d2[0] \n" "vmla.f32 q13, q4, d2[1] \n" "vmla.f32 q14, q4, d3[0] \n" "vmla.f32 q15, q4, d3[1] \n" "vmla.f32 q8, q5, d4[0] \n" "vmla.f32 q9, q5, d4[1] \n" "vmla.f32 q10, q5, d5[0] \n" "vmla.f32 q11, q5, d5[1] \n" "vmla.f32 q12, q5, d6[0] \n" "vmla.f32 q13, q5, d6[1] \n" "vmla.f32 q14, q5, d7[0] \n" "vmla.f32 q15, q5, d7[1] \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "vmla.f32 q8, q6, d0[0] \n" "vmla.f32 q9, q6, d0[1] \n" "vmla.f32 q10, q6, d1[0] \n" "vmla.f32 q11, q6, d1[1] \n" "vmla.f32 q12, q6, d2[0] \n" "vmla.f32 q13, q6, d2[1] \n" "vmla.f32 q14, q6, d3[0] \n" "vmla.f32 q15, q6, d3[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d4[0] \n" "vmla.f32 q9, q7, d4[1] \n" "vmla.f32 q10, q7, d5[0] \n" "vmla.f32 q11, q7, d5[1] \n" "vmla.f32 q12, q7, d6[0] \n" "vmla.f32 q13, q7, d6[1] \n" "vmla.f32 q14, q7, d7[0] \n" "vmla.f32 q15, q7, d7[1] \n" "bne 0b \n" "vstm %1!, {d16-d23} \n" "vstm %1!, {d24-d31} \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif } for (; i + 3 < tiles; i += 4) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v18.4s, v9.4s, v2.s[1] \n" "fmla v19.4s, v9.4s, v3.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "fmla v18.4s, v10.4s, v2.s[2] \n" "fmla v19.4s, v10.4s, v3.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "fmla v18.4s, v11.4s, v2.s[3] \n" "fmla v19.4s, v11.4s, v3.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d2[0] \n" "vmla.f32 q10, q4, d4[0] \n" "vmla.f32 q11, q4, d6[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q10, q5, d4[1] \n" "vmla.f32 q11, q5, d6[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q9, q6, d3[0] \n" "vmla.f32 q10, q6, d5[0] \n" "vmla.f32 q11, q6, d7[0] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d1[1] \n" "vmla.f32 q9, q7, d3[1] \n" "vmla.f32 q10, q7, d5[1] \n" "vmla.f32 q11, q7, d7[1] \n" "bne 0b \n" "vstm %1!, {d16-d23} \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"); #endif } for (; i + 1 < tiles; i += 2) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "0: \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v0.4s, v1.4s}, [%2], #32 \n" // r0 r1 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v16", "v17"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "0: \n" "pld [%2, #256] \n" "vld1.f32 {d0-d3}, [%2 :128]! \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d2[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q9, q6, d3[0] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d1[1] \n" "vmla.f32 q9, q7, d3[1] \n" "bne 0b \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9"); #endif } for (; i < tiles; i++) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "0: \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.4s}, [%2], #16 \n" // r0 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "bne 0b \n" "st1 {v16.4s}, [%1], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v16"); #else asm volatile( "veor q8, q8 \n" "0: \n" "pld [%2, #128] \n" "vld1.f32 {d0-d1}, [%2 :128]! \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q8, q5, d0[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q8, q7, d1[1] \n" "bne 0b \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8"); #endif } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator); } { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm / 8 * h_tm / 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); // const float bias0 = bias ? bias[p] : 0.f; float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f); float tmp[6][8][4]; // tile for (int i = 0; i < outh / 6; i++) { for (int j = 0; j < outw / 6; j++) { // top_blob_tm.create(tiles, 64, outch, elemsize, elempack); const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm / 8 + j) * 4; const float* output0_tm_1 = output0_tm_0 + tiles * 4; const float* output0_tm_2 = output0_tm_0 + tiles * 8; const float* output0_tm_3 = output0_tm_0 + tiles * 12; const float* output0_tm_4 = output0_tm_0 + tiles * 16; const float* output0_tm_5 = output0_tm_0 + tiles * 20; const float* output0_tm_6 = output0_tm_0 + tiles * 24; const float* output0_tm_7 = output0_tm_0 + tiles * 28; float* output0 = out0.row(i * 6) + (j * 6) * 4; // TODO neon optimize for (int m = 0; m < 8; m++) { float32x4_t _out0tm0 = vld1q_f32(output0_tm_0); float32x4_t _out0tm1 = vld1q_f32(output0_tm_1); float32x4_t _out0tm2 = vld1q_f32(output0_tm_2); float32x4_t _out0tm3 = vld1q_f32(output0_tm_3); float32x4_t _out0tm4 = vld1q_f32(output0_tm_4); float32x4_t _out0tm5 = vld1q_f32(output0_tm_5); float32x4_t _out0tm6 = vld1q_f32(output0_tm_6); float32x4_t _out0tm7 = vld1q_f32(output0_tm_7); float32x4_t _tmp024a = vaddq_f32(_out0tm1, _out0tm2); float32x4_t _tmp135a = vsubq_f32(_out0tm1, _out0tm2); // float tmp024a = output0_tm[1] + output0_tm[2]; // float tmp135a = output0_tm[1] - output0_tm[2]; float32x4_t _tmp024b = vaddq_f32(_out0tm3, _out0tm4); float32x4_t _tmp135b = vsubq_f32(_out0tm3, _out0tm4); // float tmp024b = output0_tm[3] + output0_tm[4]; // float tmp135b = output0_tm[3] - output0_tm[4]; float32x4_t _tmp024c = vaddq_f32(_out0tm5, _out0tm6); float32x4_t _tmp135c = vsubq_f32(_out0tm5, _out0tm6); // float tmp024c = output0_tm[5] + output0_tm[6]; // float tmp135c = output0_tm[5] - output0_tm[6]; float32x4_t _tmp0m = vaddq_f32(vaddq_f32(_out0tm0, _tmp024a), vmlaq_n_f32(_tmp024b, _tmp024c, 32.f)); float32x4_t _tmp2m = vmlaq_n_f32(vmlaq_n_f32(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f); float32x4_t _tmp4m = vmlaq_n_f32(vmlaq_n_f32(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f); vst1q_f32(tmp[0][m], _tmp0m); vst1q_f32(tmp[2][m], _tmp2m); vst1q_f32(tmp[4][m], _tmp4m); // tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; // tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; // tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; float32x4_t _tmp1m = vmlaq_n_f32(vmlaq_n_f32(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f); float32x4_t _tmp3m = vmlaq_n_f32(vmlaq_n_f32(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f); float32x4_t _tmp5m = vaddq_f32(vaddq_f32(_out0tm7, _tmp135a), vmlaq_n_f32(_tmp135c, _tmp135b, 32.f)); vst1q_f32(tmp[1][m], _tmp1m); vst1q_f32(tmp[3][m], _tmp3m); vst1q_f32(tmp[5][m], _tmp5m); // tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; // tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; // tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm_0 += tiles * 32; output0_tm_1 += tiles * 32; output0_tm_2 += tiles * 32; output0_tm_3 += tiles * 32; output0_tm_4 += tiles * 32; output0_tm_5 += tiles * 32; output0_tm_6 += tiles * 32; output0_tm_7 += tiles * 32; } for (int m = 0; m < 6; m++) { float32x4_t _tmp00 = vld1q_f32(tmp[m][0]); float32x4_t _tmp01 = vld1q_f32(tmp[m][1]); float32x4_t _tmp02 = vld1q_f32(tmp[m][2]); float32x4_t _tmp03 = vld1q_f32(tmp[m][3]); float32x4_t _tmp04 = vld1q_f32(tmp[m][4]); float32x4_t _tmp05 = vld1q_f32(tmp[m][5]); float32x4_t _tmp06 = vld1q_f32(tmp[m][6]); float32x4_t _tmp07 = vld1q_f32(tmp[m][7]); float32x4_t _tmp024a = vaddq_f32(_tmp01, _tmp02); float32x4_t _tmp135a = vsubq_f32(_tmp01, _tmp02); // float tmp024a = tmp0[1] + tmp0[2]; // float tmp135a = tmp0[1] - tmp0[2]; float32x4_t _tmp024b = vaddq_f32(_tmp03, _tmp04); float32x4_t _tmp135b = vsubq_f32(_tmp03, _tmp04); // float tmp024b = tmp0[3] + tmp0[4]; // float tmp135b = tmp0[3] - tmp0[4]; float32x4_t _tmp024c = vaddq_f32(_tmp05, _tmp06); float32x4_t _tmp135c = vsubq_f32(_tmp05, _tmp06); // float tmp024c = tmp0[5] + tmp0[6]; // float tmp135c = tmp0[5] - tmp0[6]; float32x4_t _out00 = vaddq_f32(_bias0, vaddq_f32(vaddq_f32(_tmp00, _tmp024a), vmlaq_n_f32(_tmp024b, _tmp024c, 32.f))); float32x4_t _out02 = vaddq_f32(_bias0, vmlaq_n_f32(vmlaq_n_f32(_tmp024a, _tmp024b, 4.f), _tmp024c, 8.f)); float32x4_t _out04 = vaddq_f32(_bias0, vmlaq_n_f32(vmlaq_n_f32(_tmp024a, _tmp024b, 16.f), _tmp024c, 2.f)); vst1q_f32(output0, _out00); vst1q_f32(output0 + 8, _out02); vst1q_f32(output0 + 16, _out04); // output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; // output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; // output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; float32x4_t _out01 = vaddq_f32(_bias0, vmlaq_n_f32(vmlaq_n_f32(_tmp135a, _tmp135b, 2.f), _tmp135c, 16.f)); float32x4_t _out03 = vaddq_f32(_bias0, vmlaq_n_f32(vmlaq_n_f32(_tmp135a, _tmp135b, 8.f), _tmp135c, 4.f)); float32x4_t _out05 = vaddq_f32(_bias0, vaddq_f32(vaddq_f32(_tmp07, _tmp135a), vmlaq_n_f32(_tmp135c, _tmp135b, 32.f))); vst1q_f32(output0 + 4, _out01); vst1q_f32(output0 + 12, _out03); vst1q_f32(output0 + 20, _out05); // output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; // output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; // output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw * 4; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_winograd42_transform_kernel_pack4_neon(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch) { // winograd43 transform kernel Mat kernel_tm(6 * 6, inch, outch); const float ktm[6][3] = { {1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6}, {1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = 4b-4a-inch/4a-36-outch/4b; #if __aarch64__ kernel_tm_pack4.create(2 * inch / 4, 36, (outch / 4) / 2 + (outch / 4) % 2, (size_t)4u * 16, 16); #else kernel_tm_pack4.create(inch / 4, 36, outch / 4, (size_t)4u * 16, 16); #endif int q = 0; #if __aarch64__ for (; q + 7 < outch; q += 8) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); const Mat k4 = kernel_tm.channel(q + 4); const Mat k5 = kernel_tm.channel(q + 5); const Mat k6 = kernel_tm.channel(q + 6); const Mat k7 = kernel_tm.channel(q + 7); Mat g0 = kernel_tm_pack4.channel(q / 8); for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p + 3 < inch; p += 4) { 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* 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* 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* 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* 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* 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* 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* 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); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k40[k]; g00[5] = k50[k]; g00[6] = k60[k]; g00[7] = k70[k]; g00[8] = k01[k]; g00[9] = k11[k]; g00[10] = k21[k]; g00[11] = k31[k]; g00[12] = k41[k]; g00[13] = k51[k]; g00[14] = k61[k]; g00[15] = k71[k]; g00[16] = k02[k]; g00[17] = k12[k]; g00[18] = k22[k]; g00[19] = k32[k]; g00[20] = k42[k]; g00[21] = k52[k]; g00[22] = k62[k]; g00[23] = k72[k]; g00[24] = k03[k]; g00[25] = k13[k]; g00[26] = k23[k]; g00[27] = k33[k]; g00[28] = k43[k]; g00[29] = k53[k]; g00[30] = k63[k]; g00[31] = k73[k]; g00 += 32; } } } #endif // __aarch64__ for (; q + 3 < outch; q += 4) { const Mat k0 = kernel_tm.channel(q); const Mat k1 = kernel_tm.channel(q + 1); const Mat k2 = kernel_tm.channel(q + 2); const Mat k3 = kernel_tm.channel(q + 3); #if __aarch64__ Mat g0 = kernel_tm_pack4.channel(q / 8 + (q % 8) / 4); #else Mat g0 = kernel_tm_pack4.channel(q / 4); #endif for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p + 3 < inch; p += 4) { 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* 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* 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* 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); g00[0] = k00[k]; g00[1] = k10[k]; g00[2] = k20[k]; g00[3] = k30[k]; g00[4] = k01[k]; g00[5] = k11[k]; g00[6] = k21[k]; g00[7] = k31[k]; g00[8] = k02[k]; g00[9] = k12[k]; g00[10] = k22[k]; g00[11] = k32[k]; g00[12] = k03[k]; g00[13] = k13[k]; g00[14] = k23[k]; g00[15] = k33[k]; g00 += 16; } } } } static void conv3x3s1_winograd42_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); // const float itm[4][4] = { // {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f}, // {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f}, // {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f}, // {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f}, // {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f} // }; // 0 = 4 * r00 - 5 * r02 + r04 // 1 = -4 * (r01 + r02) + r04 + r03 // 2 = 4 * (r01 - r02) + r04 - r03 // 3 = -2 * (r01 - r03) + r04 - r02 // 4 = 2 * (r01 - r03) + r04 - r02 // 5 = 4 * r01 - 5 * r03 + r05 #pragma omp parallel for num_threads(opt.num_threads) for (int q = 0; q < inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[6][6][4]; // tile for (int i = 0; i < h_tm / 6; i++) { for (int j = 0; j < w_tm / 6; j++) { const float* r0 = img0.row(i * 4) + (j * 4) * 4; for (int m = 0; m < 6; m++) { float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r01 = vld1q_f32(r0 + 4); float32x4_t _r02 = vld1q_f32(r0 + 8); float32x4_t _r03 = vld1q_f32(r0 + 12); float32x4_t _r04 = vld1q_f32(r0 + 16); float32x4_t _r05 = vld1q_f32(r0 + 20); float32x4_t _tmp0m = vmlsq_n_f32(vmlaq_n_f32(_r04, _r00, 4.f), _r02, 5.f); float32x4_t _tmp1m = vmlsq_n_f32(vaddq_f32(_r04, _r03), vaddq_f32(_r01, _r02), 4.f); float32x4_t _tmp2m = vmlaq_n_f32(vsubq_f32(_r04, _r03), vsubq_f32(_r01, _r02), 4.f); float32x4_t _tmp3m = vmlsq_n_f32(vsubq_f32(_r04, _r02), vsubq_f32(_r01, _r03), 2.f); float32x4_t _tmp4m = vmlaq_n_f32(vsubq_f32(_r04, _r02), vsubq_f32(_r01, _r03), 2.f); float32x4_t _tmp5m = vmlsq_n_f32(vmlaq_n_f32(_r05, _r01, 4.f), _r03, 5.f); vst1q_f32(tmp[0][m], _tmp0m); vst1q_f32(tmp[1][m], _tmp1m); vst1q_f32(tmp[2][m], _tmp2m); vst1q_f32(tmp[3][m], _tmp3m); vst1q_f32(tmp[4][m], _tmp4m); vst1q_f32(tmp[5][m], _tmp5m); r0 += w * 4; } float* r0_tm_0 = (float*)img0_tm + (i * w_tm / 6 + j) * 4; float* r0_tm_1 = r0_tm_0 + tiles * 4; float* r0_tm_2 = r0_tm_0 + tiles * 8; float* r0_tm_3 = r0_tm_0 + tiles * 12; float* r0_tm_4 = r0_tm_0 + tiles * 16; float* r0_tm_5 = r0_tm_0 + tiles * 20; for (int m = 0; m < 6; m++) { float32x4_t _tmp00 = vld1q_f32(tmp[m][0]); float32x4_t _tmp01 = vld1q_f32(tmp[m][1]); float32x4_t _tmp02 = vld1q_f32(tmp[m][2]); float32x4_t _tmp03 = vld1q_f32(tmp[m][3]); float32x4_t _tmp04 = vld1q_f32(tmp[m][4]); float32x4_t _tmp05 = vld1q_f32(tmp[m][5]); float32x4_t _r0tm0 = vmlsq_n_f32(vmlaq_n_f32(_tmp04, _tmp00, 4.f), _tmp02, 5.f); float32x4_t _r0tm1 = vmlsq_n_f32(vaddq_f32(_tmp04, _tmp03), vaddq_f32(_tmp01, _tmp02), 4.f); float32x4_t _r0tm2 = vmlaq_n_f32(vsubq_f32(_tmp04, _tmp03), vsubq_f32(_tmp01, _tmp02), 4.f); float32x4_t _r0tm3 = vmlsq_n_f32(vsubq_f32(_tmp04, _tmp02), vsubq_f32(_tmp01, _tmp03), 2.f); float32x4_t _r0tm4 = vmlaq_n_f32(vsubq_f32(_tmp04, _tmp02), vsubq_f32(_tmp01, _tmp03), 2.f); float32x4_t _r0tm5 = vmlsq_n_f32(vmlaq_n_f32(_tmp05, _tmp01, 4.f), _tmp03, 5.f); vst1q_f32(r0_tm_0, _r0tm0); vst1q_f32(r0_tm_1, _r0tm1); vst1q_f32(r0_tm_2, _r0tm2); vst1q_f32(r0_tm_3, _r0tm3); vst1q_f32(r0_tm_4, _r0tm4); vst1q_f32(r0_tm_5, _r0tm5); r0_tm_0 += tiles * 24; r0_tm_1 += tiles * 24; r0_tm_2 += tiles * 24; r0_tm_3 += tiles * 24; r0_tm_4 += tiles * 24; r0_tm_5 += tiles * 24; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute // bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; #if __aarch64__ if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 36, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, elemsize, elempack, opt.workspace_allocator); #else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, elemsize, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, elemsize, elempack, opt.workspace_allocator); #endif #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { float* tm2p = tm2.row(i / 12); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld4 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld4 {v8.4s, v9.4s, v10.4s, v11.4s}, [%0] \n" "st1 {v0.4s}, [%1], #16 \n" "st1 {v4.4s}, [%1], #16 \n" "st1 {v8.4s}, [%1], #16 \n" "sub %0, %0, #128 \n" "st1 {v1.4s}, [%1], #16 \n" "st1 {v5.4s}, [%1], #16 \n" "st1 {v9.4s}, [%1], #16 \n" "st1 {v2.4s}, [%1], #16 \n" "st1 {v6.4s}, [%1], #16 \n" "st1 {v10.4s}, [%1], #16 \n" "st1 {v3.4s}, [%1], #16 \n" "st1 {v7.4s}, [%1], #16 \n" "st1 {v11.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11"); r0 += bottom_blob_tm.cstep * 4; } } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8); #else float* tm2p = tm2.row(i / 8); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "prfm pldl1keep, [%0, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%0] \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" "sub %0, %0, #64 \n" "st1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7"); #else asm volatile( "pld [%0, #512] \n" "vldm %0!, {d0-d7} \n" "pld [%0, #512] \n" "vldm %0, {d16-d23} \n" // transpose 8x4 "vtrn.32 q0, q1 \n" "vtrn.32 q2, q3 \n" "vtrn.32 q8, q9 \n" "vtrn.32 q10, q11 \n" "vswp d1, d4 \n" "vswp d3, d6 \n" "vswp d17, d20 \n" "vswp d19, d22 \n" "vswp q1, q8 \n" "vswp q3, q10 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "sub %0, %0, #64 \n" "vst1.f32 {d4-d7}, [%1 :128]! \n" "vst1.f32 {d20-d23}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11"); #endif r0 += bottom_blob_tm.cstep * 4; } } for (; i + 3 < tiles; i += 4) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0] \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1", "v2", "v3"); #else asm volatile( "pld [%0, #512] \n" "vldm %0, {d0-d7} \n" "vstm %1!, {d0-d7} \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1", "q2", "q3"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } for (; i + 1 < tiles; i += 2) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v0.4s, v1.4s}, [%0] \n" "st1 {v0.4s, v1.4s}, [%1], #32 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0", "v1"); #else asm volatile( "pld [%0, #256] \n" "vld1.f32 {d0-d3}, [%0 :128] \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0", "q1"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } for (; i < tiles; i++) { #if __aarch64__ float* tm2p = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else float* tm2p = tm2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v0.4s}, [%0] \n" "st1 {v0.4s}, [%1], #16 \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "v0"); #else asm volatile( "pld [%0, #128] \n" "vld1.f32 {d0-d1}, [%0 :128] \n" "vst1.f32 {d0-d1}, [%1 :128]! \n" : "=r"(r0), // %0 "=r"(tm2p) // %1 : "0"(r0), "1"(tm2p) : "memory", "q0"); #endif // __aarch64__ r0 += bottom_blob_tm.cstep * 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, elemsize, elempack, opt.workspace_allocator); int remain_outch_start = 0; #if __ARM_NEON && __aarch64__ int nn_outch = 0; nn_outch = outch >> 1; remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); const Mat kernel01_tm = kernel_tm.channel(pp); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w0011_01 "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "fmla v16.4s, v4.4s, v2.s[0] \n" "fmla v17.4s, v4.4s, v2.s[1] \n" "fmla v18.4s, v4.4s, v2.s[2] \n" "fmla v19.4s, v4.4s, v2.s[3] \n" "fmla v20.4s, v5.4s, v0.s[0] \n" "fmla v21.4s, v5.4s, v0.s[1] \n" "fmla v22.4s, v5.4s, v0.s[2] \n" "fmla v23.4s, v5.4s, v0.s[3] \n" "fmla v24.4s, v5.4s, v1.s[0] \n" "fmla v25.4s, v5.4s, v1.s[1] \n" "fmla v26.4s, v5.4s, v1.s[2] \n" "fmla v27.4s, v5.4s, v1.s[3] \n" "fmla v28.4s, v5.4s, v2.s[0] \n" "fmla v29.4s, v5.4s, v2.s[1] \n" "fmla v30.4s, v5.4s, v2.s[2] \n" "fmla v31.4s, v5.4s, v2.s[3] \n" "fmla v8.4s, v6.4s, v3.s[0] \n" "fmla v9.4s, v6.4s, v3.s[1] \n" "fmla v10.4s, v6.4s, v3.s[2] \n" "fmla v11.4s, v6.4s, v3.s[3] \n" "fmla v20.4s, v7.4s, v3.s[0] \n" "fmla v21.4s, v7.4s, v3.s[1] \n" "fmla v22.4s, v7.4s, v3.s[2] \n" "fmla v23.4s, v7.4s, v3.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "fmla v12.4s, v6.4s, v0.s[0] \n" "fmla v13.4s, v6.4s, v0.s[1] \n" "fmla v14.4s, v6.4s, v0.s[2] \n" "fmla v15.4s, v6.4s, v0.s[3] \n" "fmla v16.4s, v6.4s, v1.s[0] \n" "fmla v17.4s, v6.4s, v1.s[1] \n" "fmla v18.4s, v6.4s, v1.s[2] \n" "fmla v19.4s, v6.4s, v1.s[3] \n" "fmla v24.4s, v7.4s, v0.s[0] \n" "fmla v25.4s, v7.4s, v0.s[1] \n" "fmla v26.4s, v7.4s, v0.s[2] \n" "fmla v27.4s, v7.4s, v0.s[3] \n" "fmla v28.4s, v7.4s, v1.s[0] \n" "fmla v29.4s, v7.4s, v1.s[1] \n" "fmla v30.4s, v7.4s, v1.s[2] \n" "fmla v31.4s, v7.4s, v1.s[3] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%4], #64 \n" // w2233_01 "fmla v8.4s, v4.4s, v2.s[0] \n" "fmla v9.4s, v4.4s, v2.s[1] \n" "fmla v10.4s, v4.4s, v2.s[2] \n" "fmla v11.4s, v4.4s, v2.s[3] \n" "fmla v12.4s, v4.4s, v3.s[0] \n" "fmla v13.4s, v4.4s, v3.s[1] \n" "fmla v14.4s, v4.4s, v3.s[2] \n" "fmla v15.4s, v4.4s, v3.s[3] \n" "fmla v20.4s, v5.4s, v2.s[0] \n" "fmla v21.4s, v5.4s, v2.s[1] \n" "fmla v22.4s, v5.4s, v2.s[2] \n" "fmla v23.4s, v5.4s, v2.s[3] \n" "fmla v24.4s, v5.4s, v3.s[0] \n" "fmla v25.4s, v5.4s, v3.s[1] \n" "fmla v26.4s, v5.4s, v3.s[2] \n" "fmla v27.4s, v5.4s, v3.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" "fmla v16.4s, v4.4s, v0.s[0] \n" "fmla v17.4s, v4.4s, v0.s[1] \n" "fmla v18.4s, v4.4s, v0.s[2] \n" "fmla v19.4s, v4.4s, v0.s[3] \n" "fmla v28.4s, v5.4s, v0.s[0] \n" "fmla v29.4s, v5.4s, v0.s[1] \n" "fmla v30.4s, v5.4s, v0.s[2] \n" "fmla v31.4s, v5.4s, v0.s[3] \n" "fmla v8.4s, v6.4s, v1.s[0] \n" "fmla v9.4s, v6.4s, v1.s[1] \n" "fmla v10.4s, v6.4s, v1.s[2] \n" "fmla v11.4s, v6.4s, v1.s[3] \n" "fmla v12.4s, v6.4s, v2.s[0] \n" "fmla v13.4s, v6.4s, v2.s[1] \n" "fmla v14.4s, v6.4s, v2.s[2] \n" "fmla v15.4s, v6.4s, v2.s[3] \n" "fmla v16.4s, v6.4s, v3.s[0] \n" "fmla v17.4s, v6.4s, v3.s[1] \n" "fmla v18.4s, v6.4s, v3.s[2] \n" "fmla v19.4s, v6.4s, v3.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v20.4s, v7.4s, v1.s[0] \n" "fmla v21.4s, v7.4s, v1.s[1] \n" "fmla v22.4s, v7.4s, v1.s[2] \n" "fmla v23.4s, v7.4s, v1.s[3] \n" "fmla v24.4s, v7.4s, v2.s[0] \n" "fmla v25.4s, v7.4s, v2.s[1] \n" "fmla v26.4s, v7.4s, v2.s[2] \n" "fmla v27.4s, v7.4s, v2.s[3] \n" "fmla v28.4s, v7.4s, v3.s[0] \n" "fmla v29.4s, v7.4s, v3.s[1] \n" "fmla v30.4s, v7.4s, v3.s[2] \n" "fmla v31.4s, v7.4s, v3.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" "st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "eor v24.16b, v24.16b, v24.16b \n" "eor v25.16b, v25.16b, v25.16b \n" "eor v26.16b, v26.16b, v26.16b \n" "eor v27.16b, v27.16b, v27.16b \n" "eor v28.16b, v28.16b, v28.16b \n" "eor v29.16b, v29.16b, v29.16b \n" "eor v30.16b, v30.16b, v30.16b \n" "eor v31.16b, v31.16b, v31.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "prfm pldl1keep, [%3, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // r4 r5 r6 r7 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v20.4s, v8.4s, v4.s[0] \n" "fmla v21.4s, v8.4s, v5.s[0] \n" "fmla v22.4s, v8.4s, v6.s[0] \n" "fmla v23.4s, v8.4s, v7.s[0] \n" "fmla v24.4s, v9.4s, v0.s[0] \n" "fmla v25.4s, v9.4s, v1.s[0] \n" "fmla v26.4s, v9.4s, v2.s[0] \n" "fmla v27.4s, v9.4s, v3.s[0] \n" "fmla v28.4s, v9.4s, v4.s[0] \n" "fmla v29.4s, v9.4s, v5.s[0] \n" "fmla v30.4s, v9.4s, v6.s[0] \n" "fmla v31.4s, v9.4s, v7.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v19.4s, v10.4s, v3.s[1] \n" "fmla v20.4s, v10.4s, v4.s[1] \n" "fmla v21.4s, v10.4s, v5.s[1] \n" "fmla v22.4s, v10.4s, v6.s[1] \n" "fmla v23.4s, v10.4s, v7.s[1] \n" "fmla v24.4s, v11.4s, v0.s[1] \n" "fmla v25.4s, v11.4s, v1.s[1] \n" "fmla v26.4s, v11.4s, v2.s[1] \n" "fmla v27.4s, v11.4s, v3.s[1] \n" "fmla v28.4s, v11.4s, v4.s[1] \n" "fmla v29.4s, v11.4s, v5.s[1] \n" "fmla v30.4s, v11.4s, v6.s[1] \n" "fmla v31.4s, v11.4s, v7.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v12.4s, v2.s[2] \n" "fmla v19.4s, v12.4s, v3.s[2] \n" "fmla v20.4s, v12.4s, v4.s[2] \n" "fmla v21.4s, v12.4s, v5.s[2] \n" "fmla v22.4s, v12.4s, v6.s[2] \n" "fmla v23.4s, v12.4s, v7.s[2] \n" "fmla v24.4s, v13.4s, v0.s[2] \n" "fmla v25.4s, v13.4s, v1.s[2] \n" "fmla v26.4s, v13.4s, v2.s[2] \n" "fmla v27.4s, v13.4s, v3.s[2] \n" "fmla v28.4s, v13.4s, v4.s[2] \n" "fmla v29.4s, v13.4s, v5.s[2] \n" "fmla v30.4s, v13.4s, v6.s[2] \n" "fmla v31.4s, v13.4s, v7.s[2] \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v14.4s, v2.s[3] \n" "fmla v19.4s, v14.4s, v3.s[3] \n" "fmla v20.4s, v14.4s, v4.s[3] \n" "fmla v21.4s, v14.4s, v5.s[3] \n" "fmla v22.4s, v14.4s, v6.s[3] \n" "fmla v23.4s, v14.4s, v7.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v24.4s, v15.4s, v0.s[3] \n" "fmla v25.4s, v15.4s, v1.s[3] \n" "fmla v26.4s, v15.4s, v2.s[3] \n" "fmla v27.4s, v15.4s, v3.s[3] \n" "fmla v28.4s, v15.4s, v4.s[3] \n" "fmla v29.4s, v15.4s, v5.s[3] \n" "fmla v30.4s, v15.4s, v6.s[3] \n" "fmla v31.4s, v15.4s, v7.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n" "st1 {v28.4s, v29.4s, v30.4s, v31.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"); } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v20.4s, v9.4s, v0.s[0] \n" "fmla v21.4s, v9.4s, v1.s[0] \n" "fmla v22.4s, v9.4s, v2.s[0] \n" "fmla v23.4s, v9.4s, v3.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v10.4s, v2.s[1] \n" "fmla v19.4s, v10.4s, v3.s[1] \n" "fmla v20.4s, v11.4s, v0.s[1] \n" "fmla v21.4s, v11.4s, v1.s[1] \n" "fmla v22.4s, v11.4s, v2.s[1] \n" "fmla v23.4s, v11.4s, v3.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v12.4s, v2.s[2] \n" "fmla v19.4s, v12.4s, v3.s[2] \n" "fmla v20.4s, v13.4s, v0.s[2] \n" "fmla v21.4s, v13.4s, v1.s[2] \n" "fmla v22.4s, v13.4s, v2.s[2] \n" "fmla v23.4s, v13.4s, v3.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v14.4s, v2.s[3] \n" "fmla v19.4s, v14.4s, v3.s[3] \n" "fmla v20.4s, v15.4s, v0.s[3] \n" "fmla v21.4s, v15.4s, v1.s[3] \n" "fmla v22.4s, v15.4s, v2.s[3] \n" "fmla v23.4s, v15.4s, v3.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); } for (; i + 1 < tiles; i += 2) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%3, #256] \n" "ld1 {v0.4s, v1.4s}, [%3], #32 \n" // r0 r1 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v9.4s, v0.s[0] \n" "fmla v19.4s, v9.4s, v1.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v10.4s, v1.s[1] \n" "fmla v18.4s, v11.4s, v0.s[1] \n" "fmla v19.4s, v11.4s, v1.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v12.4s, v1.s[2] \n" "fmla v18.4s, v13.4s, v0.s[2] \n" "fmla v19.4s, v13.4s, v1.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v14.4s, v1.s[3] \n" "fmla v18.4s, v15.4s, v0.s[3] \n" "fmla v19.4s, v15.4s, v1.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" "st1 {v18.4s, v19.4s}, [%2], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19"); } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* k01 = kernel01_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "0: \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v0.4s}, [%3], #16 \n" // r0 "prfm pldl1keep, [%4, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%4], #64 \n" // w0011_01 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v9.4s, v0.s[0] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%4], #64 \n" // w2233_01 "fmla v16.4s, v10.4s, v0.s[1] \n" "fmla v17.4s, v11.4s, v0.s[1] \n" "fmla v16.4s, v12.4s, v0.s[2] \n" "fmla v17.4s, v13.4s, v0.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v14.4s, v0.s[3] \n" "fmla v17.4s, v15.4s, v0.s[3] \n" "bne 0b \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(k01) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(k01) : "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17"); } } } #endif // __ARM_NEON && __aarch64__ #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); #if __aarch64__ const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2); #else const Mat kernel0_tm = kernel_tm.channel(p); #endif for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __aarch64__ for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 asm volatile( "eor v8.16b, v8.16b, v8.16b \n" "eor v9.16b, v9.16b, v9.16b \n" "eor v10.16b, v10.16b, v10.16b \n" "eor v11.16b, v11.16b, v11.16b \n" "eor v12.16b, v12.16b, v12.16b \n" "eor v13.16b, v13.16b, v13.16b \n" "eor v14.16b, v14.16b, v14.16b \n" "eor v15.16b, v15.16b, v15.16b \n" "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // w0123_0 "fmla v8.4s, v4.4s, v0.s[0] \n" "fmla v9.4s, v4.4s, v0.s[1] \n" "fmla v10.4s, v4.4s, v0.s[2] \n" "fmla v11.4s, v4.4s, v0.s[3] \n" "fmla v12.4s, v4.4s, v1.s[0] \n" "fmla v13.4s, v4.4s, v1.s[1] \n" "fmla v14.4s, v4.4s, v1.s[2] \n" "fmla v15.4s, v4.4s, v1.s[3] \n" "fmla v16.4s, v4.4s, v2.s[0] \n" "fmla v17.4s, v4.4s, v2.s[1] \n" "fmla v18.4s, v4.4s, v2.s[2] \n" "fmla v19.4s, v4.4s, v2.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%2], #64 \n" "fmla v8.4s, v5.4s, v3.s[0] \n" "fmla v9.4s, v5.4s, v3.s[1] \n" "fmla v10.4s, v5.4s, v3.s[2] \n" "fmla v11.4s, v5.4s, v3.s[3] \n" "fmla v12.4s, v5.4s, v20.s[0] \n" "fmla v13.4s, v5.4s, v20.s[1] \n" "fmla v14.4s, v5.4s, v20.s[2] \n" "fmla v15.4s, v5.4s, v20.s[3] \n" "fmla v16.4s, v5.4s, v21.s[0] \n" "fmla v17.4s, v5.4s, v21.s[1] \n" "fmla v18.4s, v5.4s, v21.s[2] \n" "fmla v19.4s, v5.4s, v21.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%2], #64 \n" "fmla v8.4s, v6.4s, v22.s[0] \n" "fmla v9.4s, v6.4s, v22.s[1] \n" "fmla v10.4s, v6.4s, v22.s[2] \n" "fmla v11.4s, v6.4s, v22.s[3] \n" "fmla v12.4s, v6.4s, v23.s[0] \n" "fmla v13.4s, v6.4s, v23.s[1] \n" "fmla v14.4s, v6.4s, v23.s[2] \n" "fmla v15.4s, v6.4s, v23.s[3] \n" "fmla v16.4s, v6.4s, v24.s[0] \n" "fmla v17.4s, v6.4s, v24.s[1] \n" "fmla v18.4s, v6.4s, v24.s[2] \n" "fmla v19.4s, v6.4s, v24.s[3] \n" "subs %w0, %w0, #1 \n" "fmla v8.4s, v7.4s, v25.s[0] \n" "fmla v9.4s, v7.4s, v25.s[1] \n" "fmla v10.4s, v7.4s, v25.s[2] \n" "fmla v11.4s, v7.4s, v25.s[3] \n" "fmla v12.4s, v7.4s, v26.s[0] \n" "fmla v13.4s, v7.4s, v26.s[1] \n" "fmla v14.4s, v7.4s, v26.s[2] \n" "fmla v15.4s, v7.4s, v26.s[3] \n" "fmla v16.4s, v7.4s, v27.s[0] \n" "fmla v17.4s, v7.4s, v27.s[1] \n" "fmla v18.4s, v7.4s, v27.s[2] \n" "fmla v19.4s, v7.4s, v27.s[3] \n" "bne 0b \n" "st1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%1], #64 \n" "st1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%1], #64 \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); } #endif for (; i + 7 < tiles; i += 8) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8); #else const float* r0 = bb2.row(i / 8); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "eor v20.16b, v20.16b, v20.16b \n" "eor v21.16b, v21.16b, v21.16b \n" "eor v22.16b, v22.16b, v22.16b \n" "eor v23.16b, v23.16b, v23.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%2], #64 \n" // r4 r5 r6 r7 "fmla v20.4s, v8.4s, v4.s[0] \n" "fmla v21.4s, v8.4s, v5.s[0] \n" "fmla v22.4s, v8.4s, v6.s[0] \n" "fmla v23.4s, v8.4s, v7.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v18.4s, v9.4s, v2.s[1] \n" "fmla v19.4s, v9.4s, v3.s[1] \n" "fmla v20.4s, v9.4s, v4.s[1] \n" "fmla v21.4s, v9.4s, v5.s[1] \n" "fmla v22.4s, v9.4s, v6.s[1] \n" "fmla v23.4s, v9.4s, v7.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "fmla v18.4s, v10.4s, v2.s[2] \n" "fmla v19.4s, v10.4s, v3.s[2] \n" "fmla v20.4s, v10.4s, v4.s[2] \n" "fmla v21.4s, v10.4s, v5.s[2] \n" "fmla v22.4s, v10.4s, v6.s[2] \n" "fmla v23.4s, v10.4s, v7.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "fmla v18.4s, v11.4s, v2.s[3] \n" "fmla v19.4s, v11.4s, v3.s[3] \n" "fmla v20.4s, v11.4s, v4.s[3] \n" "fmla v21.4s, v11.4s, v5.s[3] \n" "fmla v22.4s, v11.4s, v6.s[3] \n" "fmla v23.4s, v11.4s, v7.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "veor q12, q12 \n" "veor q13, q13 \n" "veor q14, q14 \n" "veor q15, q15 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d0[1] \n" "vmla.f32 q10, q4, d1[0] \n" "vmla.f32 q11, q4, d1[1] \n" "vmla.f32 q12, q4, d2[0] \n" "vmla.f32 q13, q4, d2[1] \n" "vmla.f32 q14, q4, d3[0] \n" "vmla.f32 q15, q4, d3[1] \n" "vmla.f32 q8, q5, d4[0] \n" "vmla.f32 q9, q5, d4[1] \n" "vmla.f32 q10, q5, d5[0] \n" "vmla.f32 q11, q5, d5[1] \n" "vmla.f32 q12, q5, d6[0] \n" "vmla.f32 q13, q5, d6[1] \n" "vmla.f32 q14, q5, d7[0] \n" "vmla.f32 q15, q5, d7[1] \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "vmla.f32 q8, q6, d0[0] \n" "vmla.f32 q9, q6, d0[1] \n" "vmla.f32 q10, q6, d1[0] \n" "vmla.f32 q11, q6, d1[1] \n" "vmla.f32 q12, q6, d2[0] \n" "vmla.f32 q13, q6, d2[1] \n" "vmla.f32 q14, q6, d3[0] \n" "vmla.f32 q15, q6, d3[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d4[0] \n" "vmla.f32 q9, q7, d4[1] \n" "vmla.f32 q10, q7, d5[0] \n" "vmla.f32 q11, q7, d5[1] \n" "vmla.f32 q12, q7, d6[0] \n" "vmla.f32 q13, q7, d6[1] \n" "vmla.f32 q14, q7, d7[0] \n" "vmla.f32 q15, q7, d7[1] \n" "bne 0b \n" "vstm %1!, {d16-d23} \n" "vstm %1!, {d24-d31} \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif } for (; i + 3 < tiles; i += 4) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "eor v18.16b, v18.16b, v18.16b \n" "eor v19.16b, v19.16b, v19.16b \n" "0: \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r0 r1 r2 r3 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v18.4s, v8.4s, v2.s[0] \n" "fmla v19.4s, v8.4s, v3.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v18.4s, v9.4s, v2.s[1] \n" "fmla v19.4s, v9.4s, v3.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "fmla v18.4s, v10.4s, v2.s[2] \n" "fmla v19.4s, v10.4s, v3.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "fmla v18.4s, v11.4s, v2.s[3] \n" "fmla v19.4s, v11.4s, v3.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%1], #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v16", "v17", "v18", "v19"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "veor q10, q10 \n" "veor q11, q11 \n" "0: \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d2[0] \n" "vmla.f32 q10, q4, d4[0] \n" "vmla.f32 q11, q4, d6[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q10, q5, d4[1] \n" "vmla.f32 q11, q5, d6[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q9, q6, d3[0] \n" "vmla.f32 q10, q6, d5[0] \n" "vmla.f32 q11, q6, d7[0] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d1[1] \n" "vmla.f32 q9, q7, d3[1] \n" "vmla.f32 q10, q7, d5[1] \n" "vmla.f32 q11, q7, d7[1] \n" "bne 0b \n" "vstm %1!, {d16-d23} \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11"); #endif } for (; i + 1 < tiles; i += 2) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "eor v17.16b, v17.16b, v17.16b \n" "0: \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v0.4s, v1.4s}, [%2], #32 \n" // r0 r1 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v17.4s, v8.4s, v1.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "fmla v17.4s, v9.4s, v1.s[1] \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v17.4s, v10.4s, v1.s[2] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "fmla v17.4s, v11.4s, v1.s[3] \n" "bne 0b \n" "st1 {v16.4s, v17.4s}, [%1], #32 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v1", "v8", "v9", "v10", "v11", "v16", "v17"); #else asm volatile( "veor q8, q8 \n" "veor q9, q9 \n" "0: \n" "pld [%2, #256] \n" "vld1.f32 {d0-d3}, [%2 :128]! \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q9, q4, d2[0] \n" "vmla.f32 q8, q5, d0[1] \n" "vmla.f32 q9, q5, d2[1] \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q9, q6, d3[0] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q7, d1[1] \n" "vmla.f32 q9, q7, d3[1] \n" "bne 0b \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9"); #endif } for (; i < tiles; i++) { #if __aarch64__ const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); #else const float* r0 = bb2.row(i / 8 + (i % 8) / 4 + (i % 4) / 2 + i % 2); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 #if __aarch64__ asm volatile( "eor v16.16b, v16.16b, v16.16b \n" "0: \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v0.4s}, [%2], #16 \n" // r0 "prfm pldl1keep, [%3, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%3], #64 \n" // w0123 "fmla v16.4s, v8.4s, v0.s[0] \n" "fmla v16.4s, v9.4s, v0.s[1] \n" "subs %w0, %w0, #1 \n" "fmla v16.4s, v10.4s, v0.s[2] \n" "fmla v16.4s, v11.4s, v0.s[3] \n" "bne 0b \n" "st1 {v16.4s}, [%1], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "v0", "v8", "v9", "v10", "v11", "v16"); #else asm volatile( "veor q8, q8 \n" "0: \n" "pld [%2, #128] \n" "vld1.f32 {d0-d1}, [%2 :128]! \n" "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" "vmla.f32 q8, q4, d0[0] \n" "vmla.f32 q8, q5, d0[1] \n" "subs %0, %0, #1 \n" "vmla.f32 q8, q6, d1[0] \n" "vmla.f32 q8, q7, d1[1] \n" "bne 0b \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(k0) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(k0) : "cc", "memory", "q0", "q4", "q5", "q6", "q7", "q8"); #endif } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator); } { // const float otm[4][6] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f} // }; // 0 = r00 + (r01 + r02) + (r03 + r04) // 1 = (r01 - r02) + (r03 - r04) * 2 // 2 = (r01 + r02) + (r03 + r04) * 4 // 3 = r05 + (r01 - r02) + (r03 - r04) * 8 int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = w_tm / 6 * h_tm / 6; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); // const float bias0 = bias ? bias[p] : 0.f; float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(0.f); float tmp[4][6][4]; // tile for (int i = 0; i < outh / 4; i++) { for (int j = 0; j < outw / 4; j++) { // top_blob_tm.create(tiles, 36, outch, elemsize, elempack); const float* output0_tm_0 = (const float*)out0_tm + (i * w_tm / 6 + j) * 4; const float* output0_tm_1 = output0_tm_0 + tiles * 4; const float* output0_tm_2 = output0_tm_0 + tiles * 8; const float* output0_tm_3 = output0_tm_0 + tiles * 12; const float* output0_tm_4 = output0_tm_0 + tiles * 16; const float* output0_tm_5 = output0_tm_0 + tiles * 20; float* output0 = out0.row(i * 4) + (j * 4) * 4; // TODO neon optimize for (int m = 0; m < 6; m++) { float32x4_t _out0tm0 = vld1q_f32(output0_tm_0); float32x4_t _out0tm1 = vld1q_f32(output0_tm_1); float32x4_t _out0tm2 = vld1q_f32(output0_tm_2); float32x4_t _out0tm3 = vld1q_f32(output0_tm_3); float32x4_t _out0tm4 = vld1q_f32(output0_tm_4); float32x4_t _out0tm5 = vld1q_f32(output0_tm_5); float32x4_t _tmp02a = vaddq_f32(_out0tm1, _out0tm2); float32x4_t _tmp13a = vsubq_f32(_out0tm1, _out0tm2); float32x4_t _tmp02b = vaddq_f32(_out0tm3, _out0tm4); float32x4_t _tmp13b = vsubq_f32(_out0tm3, _out0tm4); float32x4_t _tmp0m = vaddq_f32(vaddq_f32(_out0tm0, _tmp02a), _tmp02b); float32x4_t _tmp1m = vmlaq_n_f32(_tmp13a, _tmp13b, 2.f); float32x4_t _tmp2m = vmlaq_n_f32(_tmp02a, _tmp02b, 4.f); float32x4_t _tmp3m = vmlaq_n_f32(vaddq_f32(_out0tm5, _tmp13a), _tmp13b, 8.f); vst1q_f32(tmp[0][m], _tmp0m); vst1q_f32(tmp[1][m], _tmp1m); vst1q_f32(tmp[2][m], _tmp2m); vst1q_f32(tmp[3][m], _tmp3m); output0_tm_0 += tiles * 24; output0_tm_1 += tiles * 24; output0_tm_2 += tiles * 24; output0_tm_3 += tiles * 24; output0_tm_4 += tiles * 24; output0_tm_5 += tiles * 24; } for (int m = 0; m < 4; m++) { float32x4_t _tmp00 = vld1q_f32(tmp[m][0]); float32x4_t _tmp01 = vld1q_f32(tmp[m][1]); float32x4_t _tmp02 = vld1q_f32(tmp[m][2]); float32x4_t _tmp03 = vld1q_f32(tmp[m][3]); float32x4_t _tmp04 = vld1q_f32(tmp[m][4]); float32x4_t _tmp05 = vld1q_f32(tmp[m][5]); float32x4_t _tmp02a = vaddq_f32(_tmp01, _tmp02); float32x4_t _tmp13a = vsubq_f32(_tmp01, _tmp02); float32x4_t _tmp02b = vaddq_f32(_tmp03, _tmp04); float32x4_t _tmp13b = vsubq_f32(_tmp03, _tmp04); float32x4_t _out00 = vaddq_f32(_bias0, vaddq_f32(vaddq_f32(_tmp00, _tmp02a), _tmp02b)); float32x4_t _out01 = vaddq_f32(_bias0, vmlaq_n_f32(_tmp13a, _tmp13b, 2.f)); float32x4_t _out02 = vaddq_f32(_bias0, vmlaq_n_f32(_tmp02a, _tmp02b, 4.f)); float32x4_t _out03 = vaddq_f32(_bias0, vmlaq_n_f32(vaddq_f32(_tmp05, _tmp13a), _tmp13b, 8.f)); vst1q_f32(output0, _out00); vst1q_f32(output0 + 4, _out01); vst1q_f32(output0 + 8, _out02); vst1q_f32(output0 + 12, _out03); output0 += outw * 4; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s2_pack4_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = (w - 2 * outw + w) * 4; 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); float32x4_t _bias0 = bias ? vld1q_f32((const float*)bias + p * 4) : vdupq_n_f32(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 float* r2 = img0.row(2); const float* kptr = (const float*)kernel.channel(p).row(q); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #512] \n" "ld1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%0] \n" // sum0 sum1 sum2 sum3 "prfm pldl1keep, [%1, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" // r00 r01 r02 r03 "prfm pldl1keep, [%1, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%1], #64 \n" // r04 r05 r06 r07 "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v20.4s, v16.4s, v0.s[0] \n" "fmla v21.4s, v16.4s, v2.s[0] \n" "fmla v22.4s, v16.4s, v4.s[0] \n" "fmla v23.4s, v16.4s, v6.s[0] \n" "fmla v20.4s, v17.4s, v0.s[1] \n" "fmla v21.4s, v17.4s, v2.s[1] \n" "fmla v22.4s, v17.4s, v4.s[1] \n" "fmla v23.4s, v17.4s, v6.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v20.4s, v18.4s, v0.s[2] \n" "fmla v21.4s, v18.4s, v2.s[2] \n" "fmla v22.4s, v18.4s, v4.s[2] \n" "fmla v23.4s, v18.4s, v6.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v19.4s, v2.s[3] \n" "fmla v22.4s, v19.4s, v4.s[3] \n" "fmla v23.4s, v19.4s, v6.s[3] \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v28.4s}, [%1] \n" // r08 "fmla v20.4s, v24.4s, v1.s[0] \n" "fmla v21.4s, v24.4s, v3.s[0] \n" "fmla v22.4s, v24.4s, v5.s[0] \n" "fmla v23.4s, v24.4s, v7.s[0] \n" "fmla v20.4s, v25.4s, v1.s[1] \n" "fmla v21.4s, v25.4s, v3.s[1] \n" "fmla v22.4s, v25.4s, v5.s[1] \n" "fmla v23.4s, v25.4s, v7.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v20.4s, v26.4s, v1.s[2] \n" "fmla v21.4s, v26.4s, v3.s[2] \n" "fmla v22.4s, v26.4s, v5.s[2] \n" "fmla v23.4s, v26.4s, v7.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "fmla v21.4s, v27.4s, v3.s[3] \n" "fmla v22.4s, v27.4s, v5.s[3] \n" "fmla v23.4s, v27.4s, v7.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v8.4s, v9.4s, v10.4s, v11.4s}, [%2], #64 \n" // r10 r11 r12 r13 "fmla v20.4s, v16.4s, v2.s[0] \n" "fmla v21.4s, v16.4s, v4.s[0] \n" "fmla v22.4s, v16.4s, v6.s[0] \n" "fmla v23.4s, v16.4s, v28.s[0] \n" "fmla v20.4s, v17.4s, v2.s[1] \n" "fmla v21.4s, v17.4s, v4.s[1] \n" "fmla v22.4s, v17.4s, v6.s[1] \n" "fmla v23.4s, v17.4s, v28.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v20.4s, v18.4s, v2.s[2] \n" "fmla v21.4s, v18.4s, v4.s[2] \n" "fmla v22.4s, v18.4s, v6.s[2] \n" "fmla v23.4s, v18.4s, v28.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "fmla v21.4s, v19.4s, v4.s[3] \n" "fmla v22.4s, v19.4s, v6.s[3] \n" "fmla v23.4s, v19.4s, v28.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v12.4s, v13.4s, v14.4s, v15.4s}, [%2], #64 \n" // r14 r15 r16 r17 "fmla v20.4s, v24.4s, v8.s[0] \n" "fmla v21.4s, v24.4s, v10.s[0] \n" "fmla v22.4s, v24.4s, v12.s[0] \n" "fmla v23.4s, v24.4s, v14.s[0] \n" "fmla v20.4s, v25.4s, v8.s[1] \n" "fmla v21.4s, v25.4s, v10.s[1] \n" "fmla v22.4s, v25.4s, v12.s[1] \n" "fmla v23.4s, v25.4s, v14.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v20.4s, v26.4s, v8.s[2] \n" "fmla v21.4s, v26.4s, v10.s[2] \n" "fmla v22.4s, v26.4s, v12.s[2] \n" "fmla v23.4s, v26.4s, v14.s[2] \n" "fmla v20.4s, v27.4s, v8.s[3] \n" "fmla v21.4s, v27.4s, v10.s[3] \n" "fmla v22.4s, v27.4s, v12.s[3] \n" "fmla v23.4s, v27.4s, v14.s[3] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v28.4s}, [%2] \n" // r18 "fmla v20.4s, v16.4s, v9.s[0] \n" "fmla v21.4s, v16.4s, v11.s[0] \n" "fmla v22.4s, v16.4s, v13.s[0] \n" "fmla v23.4s, v16.4s, v15.s[0] \n" "fmla v20.4s, v17.4s, v9.s[1] \n" "fmla v21.4s, v17.4s, v11.s[1] \n" "fmla v22.4s, v17.4s, v13.s[1] \n" "fmla v23.4s, v17.4s, v15.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v20.4s, v18.4s, v9.s[2] \n" "fmla v21.4s, v18.4s, v11.s[2] \n" "fmla v22.4s, v18.4s, v13.s[2] \n" "fmla v23.4s, v18.4s, v15.s[2] \n" "fmla v20.4s, v19.4s, v9.s[3] \n" "fmla v21.4s, v19.4s, v11.s[3] \n" "fmla v22.4s, v19.4s, v13.s[3] \n" "fmla v23.4s, v19.4s, v15.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r20 r21 r22 r23 "fmla v20.4s, v24.4s, v10.s[0] \n" "fmla v21.4s, v24.4s, v12.s[0] \n" "fmla v22.4s, v24.4s, v14.s[0] \n" "fmla v23.4s, v24.4s, v28.s[0] \n" "fmla v20.4s, v25.4s, v10.s[1] \n" "fmla v21.4s, v25.4s, v12.s[1] \n" "fmla v22.4s, v25.4s, v14.s[1] \n" "fmla v23.4s, v25.4s, v28.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v20.4s, v26.4s, v10.s[2] \n" "fmla v21.4s, v26.4s, v12.s[2] \n" "fmla v22.4s, v26.4s, v14.s[2] \n" "fmla v23.4s, v26.4s, v28.s[2] \n" "fmla v20.4s, v27.4s, v10.s[3] \n" "fmla v21.4s, v27.4s, v12.s[3] \n" "fmla v22.4s, v27.4s, v14.s[3] \n" "fmla v23.4s, v27.4s, v28.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v4.4s, v5.4s, v6.4s, v7.4s}, [%3], #64 \n" // r24 r25 r26 r27 "fmla v20.4s, v16.4s, v0.s[0] \n" "fmla v21.4s, v16.4s, v2.s[0] \n" "fmla v22.4s, v16.4s, v4.s[0] \n" "fmla v23.4s, v16.4s, v6.s[0] \n" "fmla v20.4s, v17.4s, v0.s[1] \n" "fmla v21.4s, v17.4s, v2.s[1] \n" "fmla v22.4s, v17.4s, v4.s[1] \n" "fmla v23.4s, v17.4s, v6.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v20.4s, v18.4s, v0.s[2] \n" "fmla v21.4s, v18.4s, v2.s[2] \n" "fmla v22.4s, v18.4s, v4.s[2] \n" "fmla v23.4s, v18.4s, v6.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v19.4s, v2.s[3] \n" "fmla v22.4s, v19.4s, v4.s[3] \n" "fmla v23.4s, v19.4s, v6.s[3] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v28.4s}, [%3] \n" // r28 "fmla v20.4s, v24.4s, v1.s[0] \n" "fmla v21.4s, v24.4s, v3.s[0] \n" "fmla v22.4s, v24.4s, v5.s[0] \n" "fmla v23.4s, v24.4s, v7.s[0] \n" "fmla v20.4s, v25.4s, v1.s[1] \n" "fmla v21.4s, v25.4s, v3.s[1] \n" "fmla v22.4s, v25.4s, v5.s[1] \n" "fmla v23.4s, v25.4s, v7.s[1] \n" // "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4] \n" "fmla v20.4s, v26.4s, v1.s[2] \n" "fmla v21.4s, v26.4s, v3.s[2] \n" "fmla v22.4s, v26.4s, v5.s[2] \n" "fmla v23.4s, v26.4s, v7.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "fmla v21.4s, v27.4s, v3.s[3] \n" "fmla v22.4s, v27.4s, v5.s[3] \n" "fmla v23.4s, v27.4s, v7.s[3] \n" "fmla v20.4s, v16.4s, v2.s[0] \n" "fmla v21.4s, v16.4s, v4.s[0] \n" "fmla v22.4s, v16.4s, v6.s[0] \n" "fmla v23.4s, v16.4s, v28.s[0] \n" "fmla v20.4s, v17.4s, v2.s[1] \n" "fmla v21.4s, v17.4s, v4.s[1] \n" "fmla v22.4s, v17.4s, v6.s[1] \n" "fmla v23.4s, v17.4s, v28.s[1] \n" "fmla v20.4s, v18.4s, v2.s[2] \n" "fmla v21.4s, v18.4s, v4.s[2] \n" "fmla v22.4s, v18.4s, v6.s[2] \n" "fmla v23.4s, v18.4s, v28.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "fmla v21.4s, v19.4s, v4.s[3] \n" "fmla v22.4s, v19.4s, v6.s[3] \n" "fmla v23.4s, v19.4s, v28.s[3] \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "st1 {v20.4s, v21.4s, v22.4s, v23.4s}, [%0], #64 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28"); #else // __aarch64__ asm volatile( "pld [%0, #512] \n" "vldm %0, {d24-d31} \n" // sum0 sum1 sum2 sum3 "pld [%1, #512] \n" "vldm %1!, {d0-d7} \n" // r00 r01 r02 r03 "pld [%1, #512] \n" "vldm %1!, {d8-d15} \n" // r04 r05 r06 r07 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q12, q8, d0[0] \n" "vmla.f32 q13, q8, d4[0] \n" "vmla.f32 q14, q8, d8[0] \n" "vmla.f32 q15, q8, d12[0] \n" "vmla.f32 q12, q9, d0[1] \n" "vmla.f32 q13, q9, d4[1] \n" "vmla.f32 q14, q9, d8[1] \n" "vmla.f32 q15, q9, d12[1] \n" "vmla.f32 q12, q10, d1[0] \n" "vmla.f32 q13, q10, d5[0] \n" "vmla.f32 q14, q10, d9[0] \n" "vmla.f32 q15, q10, d13[0] \n" "vmla.f32 q12, q11, d1[1] \n" "vmla.f32 q13, q11, d5[1] \n" "vmla.f32 q14, q11, d9[1] \n" "vmla.f32 q15, q11, d13[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1 :128] \n" // r08 "vmla.f32 q12, q8, d2[0] \n" "vmla.f32 q13, q8, d6[0] \n" "vmla.f32 q14, q8, d10[0] \n" "vmla.f32 q15, q8, d14[0] \n" "vmla.f32 q12, q9, d2[1] \n" "vmla.f32 q13, q9, d6[1] \n" "vmla.f32 q14, q9, d10[1] \n" "vmla.f32 q15, q9, d14[1] \n" "vmla.f32 q12, q10, d3[0] \n" "vmla.f32 q13, q10, d7[0] \n" "vmla.f32 q14, q10, d11[0] \n" "vmla.f32 q15, q10, d15[0] \n" "vmla.f32 q12, q11, d3[1] \n" "vmla.f32 q13, q11, d7[1] \n" "vmla.f32 q14, q11, d11[1] \n" "vmla.f32 q15, q11, d15[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q12, q8, d4[0] \n" "vmla.f32 q13, q8, d8[0] \n" "vmla.f32 q14, q8, d12[0] \n" "vmla.f32 q15, q8, d0[0] \n" "vmla.f32 q12, q9, d4[1] \n" "vmla.f32 q13, q9, d8[1] \n" "vmla.f32 q14, q9, d12[1] \n" "vmla.f32 q15, q9, d0[1] \n" "vmla.f32 q12, q10, d5[0] \n" "vmla.f32 q13, q10, d9[0] \n" "vmla.f32 q14, q10, d13[0] \n" "vmla.f32 q15, q10, d1[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vmla.f32 q13, q11, d9[1] \n" "vmla.f32 q14, q11, d13[1] \n" "vmla.f32 q15, q11, d1[1] \n" "pld [%2, #512] \n" "vldm %2!, {d8-d15} \n" // r10 r11 r12 r13 "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" // r14 r15 r16 r17 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q12, q8, d8[0] \n" "vmla.f32 q13, q8, d12[0] \n" "vmla.f32 q14, q8, d0[0] \n" "vmla.f32 q15, q8, d4[0] \n" "vmla.f32 q12, q9, d8[1] \n" "vmla.f32 q13, q9, d12[1] \n" "vmla.f32 q14, q9, d0[1] \n" "vmla.f32 q15, q9, d4[1] \n" "vmla.f32 q12, q10, d9[0] \n" "vmla.f32 q13, q10, d13[0] \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d9[1] \n" "vmla.f32 q13, q11, d13[1] \n" "vmla.f32 q14, q11, d1[1] \n" "vmla.f32 q15, q11, d5[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%2, #128] \n" "vld1.f32 {d8-d9}, [%2 :128] \n" // r18 "vmla.f32 q12, q8, d10[0] \n" "vmla.f32 q13, q8, d14[0] \n" "vmla.f32 q14, q8, d2[0] \n" "vmla.f32 q15, q8, d6[0] \n" "vmla.f32 q12, q9, d10[1] \n" "vmla.f32 q13, q9, d14[1] \n" "vmla.f32 q14, q9, d2[1] \n" "vmla.f32 q15, q9, d6[1] \n" "vmla.f32 q12, q10, d11[0] \n" "vmla.f32 q13, q10, d15[0] \n" "vmla.f32 q14, q10, d3[0] \n" "vmla.f32 q15, q10, d7[0] \n" "vmla.f32 q12, q11, d11[1] \n" "vmla.f32 q13, q11, d15[1] \n" "vmla.f32 q14, q11, d3[1] \n" "vmla.f32 q15, q11, d7[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q12, q8, d12[0] \n" "vmla.f32 q13, q8, d0[0] \n" "vmla.f32 q14, q8, d4[0] \n" "vmla.f32 q15, q8, d8[0] \n" "vmla.f32 q12, q9, d12[1] \n" "vmla.f32 q13, q9, d0[1] \n" "vmla.f32 q14, q9, d4[1] \n" "vmla.f32 q15, q9, d8[1] \n" "vmla.f32 q12, q10, d13[0] \n" "vmla.f32 q13, q10, d1[0] \n" "vmla.f32 q14, q10, d5[0] \n" "vmla.f32 q15, q10, d9[0] \n" "vmla.f32 q12, q11, d13[1] \n" "vmla.f32 q13, q11, d1[1] \n" "vmla.f32 q14, q11, d5[1] \n" "vmla.f32 q15, q11, d9[1] \n" "pld [%3, #512] \n" "vldm %3!, {d0-d7} \n" // r20 r21 r22 r23 "pld [%3, #512] \n" "vldm %3!, {d8-d15} \n" // r24 r25 r26 r27 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q12, q8, d0[0] \n" "vmla.f32 q13, q8, d4[0] \n" "vmla.f32 q14, q8, d8[0] \n" "vmla.f32 q15, q8, d12[0] \n" "vmla.f32 q12, q9, d0[1] \n" "vmla.f32 q13, q9, d4[1] \n" "vmla.f32 q14, q9, d8[1] \n" "vmla.f32 q15, q9, d12[1] \n" "vmla.f32 q12, q10, d1[0] \n" "vmla.f32 q13, q10, d5[0] \n" "vmla.f32 q14, q10, d9[0] \n" "vmla.f32 q15, q10, d13[0] \n" "vmla.f32 q12, q11, d1[1] \n" "vmla.f32 q13, q11, d5[1] \n" "vmla.f32 q14, q11, d9[1] \n" "vmla.f32 q15, q11, d13[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%3, #128] \n" "vld1.f32 {d0-d1}, [%3 :128] \n" // r28 "vmla.f32 q12, q8, d2[0] \n" "vmla.f32 q13, q8, d6[0] \n" "vmla.f32 q14, q8, d10[0] \n" "vmla.f32 q15, q8, d14[0] \n" "vmla.f32 q12, q9, d2[1] \n" "vmla.f32 q13, q9, d6[1] \n" "vmla.f32 q14, q9, d10[1] \n" "vmla.f32 q15, q9, d14[1] \n" "vmla.f32 q12, q10, d3[0] \n" "vmla.f32 q13, q10, d7[0] \n" "vmla.f32 q14, q10, d11[0] \n" "vmla.f32 q15, q10, d15[0] \n" "vmla.f32 q12, q11, d3[1] \n" "vmla.f32 q13, q11, d7[1] \n" "vmla.f32 q14, q11, d11[1] \n" "vmla.f32 q15, q11, d15[1] \n" // "pld [%4, #512] \n" "vldm %4, {d16-d23} \n" "vmla.f32 q12, q8, d4[0] \n" "vmla.f32 q13, q8, d8[0] \n" "vmla.f32 q14, q8, d12[0] \n" "vmla.f32 q15, q8, d0[0] \n" "vmla.f32 q12, q9, d4[1] \n" "vmla.f32 q13, q9, d8[1] \n" "vmla.f32 q14, q9, d12[1] \n" "vmla.f32 q15, q9, d0[1] \n" "vmla.f32 q12, q10, d5[0] \n" "vmla.f32 q13, q10, d9[0] \n" "vmla.f32 q14, q10, d13[0] \n" "vmla.f32 q15, q10, d1[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vmla.f32 q13, q11, d9[1] \n" "vmla.f32 q14, q11, d13[1] \n" "vmla.f32 q15, q11, d1[1] \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "vstm %0!, {d24-d31} \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ } for (; j + 1 < outw; j += 2) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #256] \n" "ld1 {v20.4s, v21.4s}, [%0] \n" // sum0 sum1 "prfm pldl1keep, [%1, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%1], #64 \n" // r00 r01 r02 r03 "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmul v22.4s, v16.4s, v0.s[0] \n" "fmul v23.4s, v16.4s, v2.s[0] \n" "fmla v20.4s, v17.4s, v0.s[1] \n" "fmla v21.4s, v17.4s, v2.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v22.4s, v18.4s, v0.s[2] \n" "fmla v23.4s, v18.4s, v2.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v19.4s, v2.s[3] \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v4.4s}, [%1] \n" // r04 "fmla v22.4s, v24.4s, v1.s[0] \n" "fmla v23.4s, v24.4s, v3.s[0] \n" "fmla v20.4s, v25.4s, v1.s[1] \n" "fmla v21.4s, v25.4s, v3.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v22.4s, v26.4s, v1.s[2] \n" "fmla v23.4s, v26.4s, v3.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "fmla v21.4s, v27.4s, v3.s[3] \n" "fmla v22.4s, v16.4s, v2.s[0] \n" "fmla v23.4s, v16.4s, v4.s[0] \n" "fmla v20.4s, v17.4s, v2.s[1] \n" "fmla v21.4s, v17.4s, v4.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v22.4s, v18.4s, v2.s[2] \n" "fmla v23.4s, v18.4s, v4.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "fmla v21.4s, v19.4s, v4.s[3] \n" "prfm pldl1keep, [%2, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%2], #64 \n" // r10 r11 r12 r13 "fmla v22.4s, v24.4s, v0.s[0] \n" "fmla v23.4s, v24.4s, v2.s[0] \n" "fmla v20.4s, v25.4s, v0.s[1] \n" "fmla v21.4s, v25.4s, v2.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v22.4s, v26.4s, v0.s[2] \n" "fmla v23.4s, v26.4s, v2.s[2] \n" "fmla v20.4s, v27.4s, v0.s[3] \n" "fmla v21.4s, v27.4s, v2.s[3] \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v4.4s}, [%2] \n" // r14 "fmla v22.4s, v16.4s, v1.s[0] \n" "fmla v23.4s, v16.4s, v3.s[0] \n" "fmla v20.4s, v17.4s, v1.s[1] \n" "fmla v21.4s, v17.4s, v3.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v22.4s, v18.4s, v1.s[2] \n" "fmla v23.4s, v18.4s, v3.s[2] \n" "fmla v20.4s, v19.4s, v1.s[3] \n" "fmla v21.4s, v19.4s, v3.s[3] \n" "fmla v22.4s, v24.4s, v2.s[0] \n" "fmla v23.4s, v24.4s, v4.s[0] \n" "fmla v20.4s, v25.4s, v2.s[1] \n" "fmla v21.4s, v25.4s, v4.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v22.4s, v26.4s, v2.s[2] \n" "fmla v23.4s, v26.4s, v4.s[2] \n" "fmla v20.4s, v27.4s, v2.s[3] \n" "fmla v21.4s, v27.4s, v4.s[3] \n" "prfm pldl1keep, [%3, #512] \n" "ld1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%3], #64 \n" // r20 r21 r22 r23 "fmla v22.4s, v16.4s, v0.s[0] \n" "fmla v23.4s, v16.4s, v2.s[0] \n" "fmla v20.4s, v17.4s, v0.s[1] \n" "fmla v21.4s, v17.4s, v2.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v22.4s, v18.4s, v0.s[2] \n" "fmla v23.4s, v18.4s, v2.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v19.4s, v2.s[3] \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v4.4s}, [%3] \n" // r24 "fmla v22.4s, v24.4s, v1.s[0] \n" "fmla v23.4s, v24.4s, v3.s[0] \n" "fmla v20.4s, v25.4s, v1.s[1] \n" "fmla v21.4s, v25.4s, v3.s[1] \n" // "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4] \n" "fmla v22.4s, v26.4s, v1.s[2] \n" "fmla v23.4s, v26.4s, v3.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "fmla v21.4s, v27.4s, v3.s[3] \n" "fmla v22.4s, v16.4s, v2.s[0] \n" "fmla v23.4s, v16.4s, v4.s[0] \n" "fmla v20.4s, v17.4s, v2.s[1] \n" "fmla v21.4s, v17.4s, v4.s[1] \n" "fmla v22.4s, v18.4s, v2.s[2] \n" "fmla v23.4s, v18.4s, v4.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "fmla v21.4s, v19.4s, v4.s[3] \n" "fadd v20.4s, v20.4s, v22.4s \n" "fadd v21.4s, v21.4s, v23.4s \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "st1 {v20.4s, v21.4s}, [%0], #32 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); #else // __aarch64__ asm volatile( "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128] \n" // sum0 sum1 "pld [%1, #512] \n" "vldm %1!, {d0-d7} \n" // r00 r01 r02 r03 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmul.f32 q14, q8, d0[0] \n" "vmul.f32 q15, q8, d4[0] \n" "vmla.f32 q12, q9, d0[1] \n" "vmla.f32 q13, q9, d4[1] \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d1[1] \n" "vmla.f32 q13, q11, d5[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%1, #128] \n" "vld1.f32 {d8-d9}, [%1 :128] \n" // r04 "vmla.f32 q14, q8, d2[0] \n" "vmla.f32 q15, q8, d6[0] \n" "vmla.f32 q12, q9, d2[1] \n" "vmla.f32 q13, q9, d6[1] \n" "vmla.f32 q14, q10, d3[0] \n" "vmla.f32 q15, q10, d7[0] \n" "vmla.f32 q12, q11, d3[1] \n" "vmla.f32 q13, q11, d7[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q14, q8, d4[0] \n" "vmla.f32 q15, q8, d8[0] \n" "vmla.f32 q12, q9, d4[1] \n" "vmla.f32 q13, q9, d8[1] \n" "vmla.f32 q14, q10, d5[0] \n" "vmla.f32 q15, q10, d9[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vmla.f32 q13, q11, d9[1] \n" "pld [%2, #512] \n" "vldm %2!, {d0-d7} \n" // r10 r11 r12 r13 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q14, q8, d0[0] \n" "vmla.f32 q15, q8, d4[0] \n" "vmla.f32 q12, q9, d0[1] \n" "vmla.f32 q13, q9, d4[1] \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d1[1] \n" "vmla.f32 q13, q11, d5[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%2, #128] \n" "vld1.f32 {d8-d9}, [%2 :128] \n" // r14 "vmla.f32 q14, q8, d2[0] \n" "vmla.f32 q15, q8, d6[0] \n" "vmla.f32 q12, q9, d2[1] \n" "vmla.f32 q13, q9, d6[1] \n" "vmla.f32 q14, q10, d3[0] \n" "vmla.f32 q15, q10, d7[0] \n" "vmla.f32 q12, q11, d3[1] \n" "vmla.f32 q13, q11, d7[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q14, q8, d4[0] \n" "vmla.f32 q15, q8, d8[0] \n" "vmla.f32 q12, q9, d4[1] \n" "vmla.f32 q13, q9, d8[1] \n" "vmla.f32 q14, q10, d5[0] \n" "vmla.f32 q15, q10, d9[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vmla.f32 q13, q11, d9[1] \n" "pld [%3, #512] \n" "vldm %3!, {d0-d7} \n" // r20 r21 r22 r23 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q14, q8, d0[0] \n" "vmla.f32 q15, q8, d4[0] \n" "vmla.f32 q12, q9, d0[1] \n" "vmla.f32 q13, q9, d4[1] \n" "vmla.f32 q14, q10, d1[0] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d1[1] \n" "vmla.f32 q13, q11, d5[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "pld [%3, #128] \n" "vld1.f32 {d8-d9}, [%3 :128] \n" // r24 "vmla.f32 q14, q8, d2[0] \n" "vmla.f32 q15, q8, d6[0] \n" "vmla.f32 q12, q9, d2[1] \n" "vmla.f32 q13, q9, d6[1] \n" "vmla.f32 q14, q10, d3[0] \n" "vmla.f32 q15, q10, d7[0] \n" "vmla.f32 q12, q11, d3[1] \n" "vmla.f32 q13, q11, d7[1] \n" // "pld [%4, #512] \n" "vldm %4, {d16-d23} \n" "vmla.f32 q14, q8, d4[0] \n" "vmla.f32 q15, q8, d8[0] \n" "vmla.f32 q12, q9, d4[1] \n" "vmla.f32 q13, q9, d8[1] \n" "vmla.f32 q14, q10, d5[0] \n" "vmla.f32 q15, q10, d9[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vmla.f32 q13, q11, d9[1] \n" "vadd.f32 q12, q12, q14 \n" "vadd.f32 q13, q13, q15 \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "vst1.f32 {d24-d27}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ } for (; j < outw; j++) { #if __aarch64__ asm volatile( "prfm pldl1keep, [%0, #128] \n" "ld1 {v20.4s}, [%0] \n" // sum0 "prfm pldl1keep, [%1, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%1] \n" // r00 r01 r02 "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmul v21.4s, v16.4s, v0.s[0] \n" "fmul v22.4s, v17.4s, v0.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmul v23.4s, v18.4s, v0.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v24.4s, v1.s[0] \n" "fmla v22.4s, v25.4s, v1.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v23.4s, v26.4s, v1.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "prfm pldl1keep, [%2, #384] \n" "ld1 {v3.4s, v4.4s, v5.4s}, [%2] \n" // r10 r11 r12 "fmla v21.4s, v16.4s, v2.s[0] \n" "fmla v22.4s, v17.4s, v2.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v23.4s, v18.4s, v2.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "fmla v21.4s, v24.4s, v3.s[0] \n" "fmla v22.4s, v25.4s, v3.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v23.4s, v26.4s, v3.s[2] \n" "fmla v20.4s, v27.4s, v3.s[3] \n" "fmla v21.4s, v16.4s, v4.s[0] \n" "fmla v22.4s, v17.4s, v4.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v23.4s, v18.4s, v4.s[2] \n" "fmla v20.4s, v19.4s, v4.s[3] \n" "prfm pldl1keep, [%3, #384] \n" "ld1 {v0.4s, v1.4s, v2.4s}, [%3] \n" // r20 r21 r22 "fmla v21.4s, v24.4s, v5.s[0] \n" "fmla v22.4s, v25.4s, v5.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4], #64 \n" "fmla v23.4s, v26.4s, v5.s[2] \n" "fmla v20.4s, v27.4s, v5.s[3] \n" "fmla v21.4s, v16.4s, v0.s[0] \n" "fmla v22.4s, v17.4s, v0.s[1] \n" "prfm pldl1keep, [%4, #512] \n" "ld1 {v24.4s, v25.4s, v26.4s, v27.4s}, [%4], #64 \n" "fmla v23.4s, v18.4s, v0.s[2] \n" "fmla v20.4s, v19.4s, v0.s[3] \n" "fmla v21.4s, v24.4s, v1.s[0] \n" "fmla v22.4s, v25.4s, v1.s[1] \n" // "prfm pldl1keep, [%4, #512] \n" "ld1 {v16.4s, v17.4s, v18.4s, v19.4s}, [%4] \n" "fmla v23.4s, v26.4s, v1.s[2] \n" "fmla v20.4s, v27.4s, v1.s[3] \n" "fmla v21.4s, v16.4s, v2.s[0] \n" "fmla v22.4s, v17.4s, v2.s[1] \n" "fmla v23.4s, v18.4s, v2.s[2] \n" "fmla v20.4s, v19.4s, v2.s[3] \n" "add %1, %1, #32 \n" "fadd v22.4s, v21.4s, v22.4s \n" "add %2, %2, #32 \n" "fadd v23.4s, v23.4s, v22.4s \n" "add %3, %3, #32 \n" "fadd v20.4s, v20.4s, v23.4s \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "st1 {v20.4s}, [%0], #16 \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27"); #else // __aarch64__ asm volatile( "pld [%0, #128] \n" "vld1.f32 {d24-d25}, [%0 :128] \n" // sum0 "pld [%1, #384] \n" "vldm %1, {d0-d5} \n" // r00 r01 r02 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmul.f32 q13, q8, d0[0] \n" "vmul.f32 q14, q9, d0[1] \n" "vmul.f32 q15, q10, d1[0] \n" "vmla.f32 q12, q11, d1[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d2[0] \n" "vmla.f32 q14, q9, d2[1] \n" "vmla.f32 q15, q10, d3[0] \n" "vmla.f32 q12, q11, d3[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d4[0] \n" "vmla.f32 q14, q9, d4[1] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d5[1] \n" "pld [%2, #384] \n" "vldm %2, {d0-d5} \n" // r10 r11 r12 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d0[0] \n" "vmla.f32 q14, q9, d0[1] \n" "vmla.f32 q15, q10, d1[0] \n" "vmla.f32 q12, q11, d1[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d2[0] \n" "vmla.f32 q14, q9, d2[1] \n" "vmla.f32 q15, q10, d3[0] \n" "vmla.f32 q12, q11, d3[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d4[0] \n" "vmla.f32 q14, q9, d4[1] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d5[1] \n" "pld [%3, #384] \n" "vldm %3, {d0-d5} \n" // r20 r21 r22 "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d0[0] \n" "vmla.f32 q14, q9, d0[1] \n" "vmla.f32 q15, q10, d1[0] \n" "vmla.f32 q12, q11, d1[1] \n" "pld [%4, #512] \n" "vldm %4!, {d16-d23} \n" "vmla.f32 q13, q8, d2[0] \n" "vmla.f32 q14, q9, d2[1] \n" "vmla.f32 q15, q10, d3[0] \n" "vmla.f32 q12, q11, d3[1] \n" // "pld [%4, #512] \n" "vldm %4, {d16-d23} \n" "vmla.f32 q13, q8, d4[0] \n" "vmla.f32 q14, q9, d4[1] \n" "vmla.f32 q15, q10, d5[0] \n" "vmla.f32 q12, q11, d5[1] \n" "vadd.f32 q14, q14, q13 \n" "add %1, %1, #32 \n" "vadd.f32 q15, q15, q14 \n" "add %2, %2, #32 \n" "vadd.f32 q12, q12, q15 \n" "add %3, %3, #32 \n" "sub %4, %4, #512 \n" // kptr -= 8 * 16; "vst1.f32 {d24-d25}, [%0 :128]! \n" : "=r"(outptr0), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(kptr) // %4 : "0"(outptr0), "1"(r0), "2"(r1), "3"(r2), "4"(kptr) : "memory", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"); #endif // __aarch64__ } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } }
GB_unaryop__identity_int64_uint32.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__identity_int64_uint32 // op(A') function: GB_tran__identity_int64_uint32 // C type: int64_t // A type: uint32_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int64_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, aij) \ int64_t z = (int64_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_IDENTITY || GxB_NO_INT64 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int64_uint32 ( int64_t *Cx, // Cx and Ax may be aliased uint32_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__identity_int64_uint32 ( 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
data.h
/*! * Copyright (c) 2015 by Contributors * \file data.h * \brief The input data structure of xgboost. * \author Tianqi Chen */ #ifndef XGBOOST_DATA_H_ #define XGBOOST_DATA_H_ #include <dmlc/base.h> #include <dmlc/data.h> #include <rabit/rabit.h> #include <xgboost/base.h> #include <xgboost/span.h> #include <xgboost/host_device_vector.h> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <utility> #include <vector> namespace xgboost { // forward declare learner. class LearnerImpl; // forward declare dmatrix. class DMatrix; /*! \brief data type accepted by xgboost interface */ enum DataType { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4 }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of rows in the data */ uint64_t num_row_{0}; /*! \brief number of columns in the data */ uint64_t num_col_{0}; /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_group_t> group_ptr_; /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; /*! * \brief initialized margins, * if specified, xgboost will start from this init margin * can be used to specify initial prediction to boost from. */ HostDeviceVector<bst_float> base_margin_; /*! \brief default constructor */ MetaInfo() = default; /*! * \brief Get weight of each instances. * \param i Instance index. * \return The weight. */ inline bst_float GetWeight(size_t i) const { return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f; } /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */ inline const std::vector<size_t>& LabelAbsSort() const { if (label_order_cache_.size() == labels_.Size()) { return label_order_cache_; } label_order_cache_.resize(labels_.Size()); std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0); const auto& l = labels_.HostVector(); XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(), [&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);}); return label_order_cache_; } /*! \brief clear all the information */ void Clear(); /*! * \brief Load the Meta info from binary stream. * \param fi The input stream */ void LoadBinary(dmlc::Stream* fi); /*! * \brief Save the Meta info to binary stream * \param fo The output stream. */ void SaveBinary(dmlc::Stream* fo) const; /*! * \brief Set information in the meta info. * \param key The key of the information. * \param dptr The data pointer of the source array. * \param dtype The type of the source data. * \param num Number of elements in the source array. */ void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num); /*! * \brief Set information in the meta info with array interface. * \param key The key of the information. * \param interface_str String representation of json format array interface. * * [ column_0, column_1, ... column_n ] * * Right now only 1 column is permitted. */ void SetInfo(const char* key, std::string const& interface_str); private: /*! \brief argsort of labels */ mutable std::vector<size_t> label_order_cache_; }; /*! \brief Element from a sparse vector */ struct Entry { /*! \brief feature index */ bst_feature_t index; /*! \brief feature value */ bst_float fvalue; /*! \brief default constructor */ Entry() = default; /*! * \brief constructor with index and value * \param index The feature or row index. * \param fvalue The feature value. */ Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {} /*! \brief reversely compare feature values */ inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; } inline bool operator==(const Entry& other) const { return (this->index == other.index && this->fvalue == other.fvalue); } }; /*! * \brief Parameters for constructing batches. */ struct BatchParam { /*! \brief The GPU device to use. */ int gpu_id; /*! \brief Maximum number of bins per feature for histograms. */ int max_bin; /*! \brief Number of rows in a GPU batch, used for finding quantiles on GPU. */ int gpu_batch_nrows; /*! \brief Page size for external memory mode. */ size_t gpu_page_size; inline bool operator!=(const BatchParam& other) const { return gpu_id != other.gpu_id || max_bin != other.max_bin || gpu_batch_nrows != other.gpu_batch_nrows || gpu_page_size != other.gpu_page_size; } }; /*! * \brief In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<bst_row_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid{}; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; /*! \brief get i-th row from the batch */ inline Inst operator[](size_t i) const { const auto& data_vec = data.HostVector(); const auto& offset_vec = offset.HostVector(); size_t size; // in distributed mode, some partitions may not get any instance for a feature. Therefore // we should set the size as zero if (rabit::IsDistributed() && i + 1 >= offset_vec.size()) { size = 0; } else { size = offset_vec[i + 1] - offset_vec[i]; } return {data_vec.data() + offset_vec[i], static_cast<Inst::index_type>(size)}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return Number of instances in the page. */ inline size_t Size() const { return offset.Size() - 1; } /*! \return estimation of memory cost of this page */ inline size_t MemCostBytes() const { return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry); } /*! \brief clear the page */ inline void Clear() { base_rowid = 0; auto& offset_vec = offset.HostVector(); offset_vec.clear(); offset_vec.push_back(0); data.HostVector().clear(); } /*! \brief Set the base row id for this page. */ inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; } SparsePage GetTranspose(int num_columns) const; void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); #pragma omp parallel for default(none) shared(ncol) schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) { std::sort( this->data.HostVector().begin() + this->offset.HostVector()[i], this->data.HostVector().begin() + this->offset.HostVector()[i + 1], Entry::CmpValue); } } } /*! * \brief Push row block into the page. * \param batch the row batch. */ void Push(const dmlc::RowBlock<uint32_t>& batch); /*! * \brief Push a sparse page * \param batch the row page */ void Push(const SparsePage &batch); /*! * \brief Push a SparsePage stored in CSC format * \param batch The row batch to be pushed */ void PushCSC(const SparsePage& batch); }; class CSCPage: public SparsePage { public: CSCPage() : SparsePage() {} explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class SortedCSCPage : public SparsePage { public: SortedCSCPage() : SparsePage() {} explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class EllpackPageImpl; /*! * \brief A page stored in ELLPACK format. * * This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid * including CUDA-specific implementation details in the header. */ class EllpackPage { public: /*! * \brief Default constructor. * * This is used in the external memory case. An empty ELLPACK page is constructed with its content * set later by the reader. */ EllpackPage(); /*! * \brief Constructor from an existing DMatrix. * * This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix * in CSR format. */ explicit EllpackPage(DMatrix* dmat, const BatchParam& param); /*! \brief Destructor. */ ~EllpackPage(); /*! \return Number of instances in the page. */ size_t Size() const; /*! \brief Set the base row id for this page. */ void SetBaseRowId(size_t row_id); const EllpackPageImpl* Impl() const { return impl_.get(); } EllpackPageImpl* Impl() { return impl_.get(); } private: std::unique_ptr<EllpackPageImpl> impl_; }; template<typename T> class BatchIteratorImpl { public: virtual ~BatchIteratorImpl() = default; virtual T& operator*() = 0; virtual const T& operator*() const = 0; virtual void operator++() = 0; virtual bool AtEnd() const = 0; }; template<typename T> class BatchIterator { public: using iterator_category = std::forward_iterator_tag; explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); } void operator++() { CHECK(impl_ != nullptr); ++(*impl_); } T& operator*() { CHECK(impl_ != nullptr); return *(*impl_); } const T& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator& rhs) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } private: std::shared_ptr<BatchIteratorImpl<T>> impl_; }; template<typename T> class BatchSet { public: explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(begin_iter) {} BatchIterator<T> begin() { return begin_iter_; } BatchIterator<T> end() { return BatchIterator<T>(nullptr); } private: BatchIterator<T> begin_iter_; }; /*! * \brief This is data structure that user can pass to DMatrix::Create * to create a DMatrix for training, user can create this data structure * for customized Data Loading on single machine. * * On distributed setting, usually an customized dmlc::Parser is needed instead. */ template<typename T> class DataSource : public dmlc::DataIter<T> { public: /*! * \brief Meta information about the dataset * The subclass need to be able to load this correctly from data. */ MetaInfo info; }; /*! * \brief Internal data structured used by XGBoost during training. * There are two ways to create a customized DMatrix that reads in user defined-format. * * - Provide a dmlc::Parser and pass into the DMatrix::Create * - Alternatively, if data can be represented by an URL, define a new dmlc::Parser and register by * DMLC_REGISTER_DATA_PARSER; * - This works best for user defined data input source, such as data-base, filesystem. * - Provide a DataSource, that can be passed to DMatrix::Create * This can be used to re-use inmemory data structure into DMatrix. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /** * \brief Gets batches. Use range based for loop over BatchSet to access individual batches. */ template<typename T> BatchSet<T> GetBatches(const BatchParam& param = {}); // the following are column meta data, should be able to answer them fast. /*! \return Whether the data columns single column block. */ virtual bool SingleColBlock() const = 0; /*! \brief get column density */ virtual float GetColDensity(size_t cidx) = 0; /*! \brief virtual destructor */ virtual ~DMatrix() = default; /*! * \brief Save DMatrix to local file. * The saved file only works for non-sharded dataset(single machine training). * This API is deprecated and dis-encouraged to use. * \param fname The file name to be saved. * \return The created DMatrix. */ virtual void SaveToLocalFile(const std::string& fname); /*! \brief Whether the matrix is dense. */ bool IsDense() const { return Info().num_nonzero_ == Info().num_row_ * Info().num_col_; } /*! * \brief Load DMatrix from URI. * \param uri The URI of input. * \param silent Whether print information during loading. * \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode. * \param file_format The format type of the file, used for dmlc::Parser::Create. * By default "auto" will be able to load in both local binary file. * \param page_size Page size for external memory. * \return The created DMatrix. */ static DMatrix* Load(const std::string& uri, bool silent, bool load_row_split, const std::string& file_format = "auto", size_t page_size = kPageSize); /*! * \brief create a new DMatrix, by wrapping a row_iterator, and meta info. * \param source The source iterator of the data, the create function takes ownership of the source. * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \return a Created DMatrix. */ static DMatrix* Create(std::unique_ptr<DataSource<SparsePage>>&& source, const std::string& cache_prefix = ""); /** * \brief Creates a new DMatrix from an external data adapter. * * \tparam AdapterT Type of the adapter. * \param adapter View onto an external data. * \param missing Values to count as missing. * \param nthread Number of threads for construction. * * \return a Created DMatrix. */ template <typename AdapterT> static DMatrix* Create(AdapterT* adapter, float missing, int nthread); /*! * \brief Create a DMatrix by loading data from parser. * Parser can later be deleted after the DMatrix i created. * \param parser The input data parser * \param cache_prefix The path to prefix of temporary cache file of the DMatrix when used in external memory mode. * This can be nullptr for common cases, and in-memory mode will be used. * \param page_size Page size for external memory. * \sa dmlc::Parser * \note dmlc-core provides efficient distributed data parser for libsvm format. * User can create and register customized parser to load their own format using DMLC_REGISTER_DATA_PARSER. * See "dmlc-core/include/dmlc/data.h" for detail. * \return A created DMatrix. */ static DMatrix* Create(dmlc::Parser<uint32_t>* parser, const std::string& cache_prefix = "", size_t page_size = kPageSize); /*! \brief page size 32 MB */ static const size_t kPageSize = 32UL << 20UL; protected: virtual BatchSet<SparsePage> GetRowBatches() = 0; virtual BatchSet<CSCPage> GetColumnBatches() = 0; virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0; virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0; }; template<> inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) { return GetRowBatches(); } template<> inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) { return GetColumnBatches(); } template<> inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) { return GetSortedColumnBatches(); } template<> inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) { return GetEllpackBatches(param); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); } #endif // XGBOOST_DATA_H_
organismsbuffer.h
#pragma once #include "organism.h" #include "rng.h" #include <assert.h> #include "Parameters.h" namespace NEAT { template<typename TOrganism = Organism> class OrganismsBuffer { size_t _n; std::vector<TOrganism> _a; std::vector<TOrganism> _b; std::vector<TOrganism> *_curr; std::vector<TOrganism> *_prev; public: OrganismsBuffer(rng_t rng, std::vector<std::unique_ptr<Genome>> &seeds, size_t n, size_t population_index = 0) : _n(n) { _a.reserve(n); _b.reserve(n); _curr = &_a; _prev = &_b; for(size_t i = 0; i < n; i++) { _a.emplace_back(*seeds[i + population_index]); size_t ipop = i + population_index; _a[i].population_index = ipop; _a[i].net->population_index = ipop; _a[i].genome->genome_id = ipop; _a[i].genome->rng.seed(rng.integer()); } for(size_t i = 0; i < n; i++) { _b.emplace_back(*seeds[i + population_index]); size_t ipop = i + population_index; _b[i].population_index = ipop; _b[i].net->population_index = ipop; _b[i].genome->genome_id = ipop; _b[i].genome->rng.seed(rng.integer()); } } void init_phenotypes() { #pragma omp parallel for for(size_t i = 0; i < _n; i++) { Organism &org = curr()[i]; org.genome->init_phenotype(*org.net); } } size_t size(){ return _n; } std::vector<TOrganism> &curr() { return *_curr; } std::vector<TOrganism> &prev() { return *_prev; } void next_generation(int generation) { if(_curr == &_a) { _curr = &_b; _prev = &_a; } else { _curr = &_a; _prev = &_b; } assert( _curr->size() == _n ); for(TOrganism &org: curr()) org.init(generation); } }; }
2DConvolution.c
/** * 2DConvolution.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 <omp.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <time.h> #include <unistd.h> #include "../../common/polybenchUtilFuncts.h" // define the error threshold for the results "not matching" #define ERROR_THRESHOLD 0.05 #define GPU 1 /* Problem size */ #define NI 8192 #define NJ 8192 /* Can switch DATA_TYPE between float and double */ typedef float DATA_TYPE; void conv2D(DATA_TYPE *A, DATA_TYPE *B) { int i, j; DATA_TYPE c11, c12, c13, c21, c22, c23, c31, c32, c33; c11 = +0.2; c21 = +0.5; c31 = -0.8; c12 = -0.3; c22 = +0.6; c32 = -0.9; c13 = +0.4; c23 = +0.7; c33 = +0.10; for (i = 1; i < NI - 1; ++i) { for (j = 1; j < NJ - 1; ++j) { B[i * NJ + j] = c11 * A[(i - 1) * NJ + (j - 1)] + c12 * A[(i + 0) * NJ + (j - 1)] + c13 * A[(i + 1) * NJ + (j - 1)] + c21 * A[(i - 1) * NJ + (j + 0)] + c22 * A[(i + 0) * NJ + (j + 0)] + c23 * A[(i + 1) * NJ + (j + 0)] + c31 * A[(i - 1) * NJ + (j + 1)] + c32 * A[(i + 0) * NJ + (j + 1)] + c33 * A[(i + 1) * NJ + (j + 1)]; } } } void conv2D_OMP(DATA_TYPE *A, DATA_TYPE *B) { int i, j; DATA_TYPE c11, c12, c13, c21, c22, c23, c31, c32, c33; c11 = +0.2; c21 = +0.5; c31 = -0.8; c12 = -0.3; c22 = +0.6; c32 = -0.9; c13 = +0.4; c23 = +0.7; c33 = +0.10; #pragma omp target device(GPU) map(to : A[:NI * NJ]) map(from : B[:NI * NJ]) #pragma omp parallel for collapse(2) for (i = 1; i < NI - 1; ++i) { for (j = 1; j < NJ - 1; ++j) { B[i * NJ + j] = c11 * A[(i - 1) * NJ + (j - 1)] + c12 * A[(i + 0) * NJ + (j - 1)] + c13 * A[(i + 1) * NJ + (j - 1)] + c21 * A[(i - 1) * NJ + (j + 0)] + c22 * A[(i + 0) * NJ + (j + 0)] + c23 * A[(i + 1) * NJ + (j + 0)] + c31 * A[(i - 1) * NJ + (j + 1)] + c32 * A[(i + 0) * NJ + (j + 1)] + c33 * A[(i + 1) * NJ + (j + 1)]; } } } void init(DATA_TYPE *A) { int i, j; for (i = 0; i < NI; ++i) { for (j = 0; j < NJ; ++j) { A[i * NJ + j] = (float)rand() / RAND_MAX; } } } void compareResults(DATA_TYPE *B, DATA_TYPE *B_GPU) { int i, j, fail; fail = 0; // Compare B and B_GPU for (i = 1; i < (NI - 1); i++) { for (j = 1; j < (NJ - 1); j++) { if (percentDiff(B[i * NJ + j], B_GPU[i * NJ + j]) > ERROR_THRESHOLD) { fail++; } } } // Print results printf("Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f " "Percent: %d\n", ERROR_THRESHOLD, fail); } int main(int argc, char *argv[]) { double t_start, t_end, t_start_OMP, t_end_OMP; DATA_TYPE *A; DATA_TYPE *B; DATA_TYPE *B_OMP; A = (DATA_TYPE *)malloc(NI * NJ * sizeof(DATA_TYPE)); B = (DATA_TYPE *)malloc(NI * NJ * sizeof(DATA_TYPE)); B_OMP = (DATA_TYPE *)malloc(NI * NJ * sizeof(DATA_TYPE)); fprintf(stdout, ">> Two dimensional (2D) convolution <<\n"); // initialize the arrays init(A); t_start_OMP = rtclock(); conv2D_OMP(A, B_OMP); t_end_OMP = rtclock(); fprintf(stdout, "GPU Runtime: %0.6lfs\n", t_end_OMP - t_start_OMP); //); t_start = rtclock(); conv2D(A, B); t_end = rtclock(); fprintf(stdout, "CPU Runtime: %0.6lfs\n", t_end - t_start); //); compareResults(B, B_OMP); free(A); free(B); free(B_OMP); return 0; }
MathTools.h
/** * \file * \copyright * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ #pragma once #include <boost/math/constants/constants.hpp> #include <cstddef> #ifdef _OPENMP #include <omp.h> #endif namespace MathLib { /** * standard inner product in R^N * \param v0 array of type T representing the vector * \param v1 array of type T representing the vector * */ template<typename T, int N> inline T scalarProduct(T const * const v0, T const * const v1) { T res (v0[0] * v1[0]); #pragma omp parallel for reduction (+:res) for (int k = 1; k < N; k++) { res += v0[k] * v1[k]; } return res; } template <> inline double scalarProduct<double,3>(double const * const v0, double const * const v1) { double res (v0[0] * v1[0]); for (std::size_t k(1); k < 3; k++) { res += v0[k] * v1[k]; } return res; } template <typename T> inline T scalarProduct(T const* const v0, T const* const v1, int const n) { T res (v0[0] * v1[0]); #pragma omp parallel for reduction (+:res) for (int k = 1; k < n; k++) { res += v0[k] * v1[k]; } return res; } /** * calcProjPntToLineAndDists computes the orthogonal projection * of a point p to the line described by the points a and b, * \f$g(\lambda) = a + \lambda (b - a)\f$, * the distance between p and the projected point * and the distances between the projected point and the end * points a, b of the line * \param p the (mesh) point * \param a first point of line * \param b second point of line * \param lambda the projected point described by the line equation above * \param d0 distance to the line point a * \returns the distance between p and the orthogonal projection of p */ double calcProjPntToLineAndDists(const double p[3], const double a[3], const double b[3], double &lambda, double &d0); /** squared dist between double arrays p0 and p1 (size of arrays is 3) */ inline double sqrDist(const double* p0, const double* p1) { const double v[3] = {p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]}; return scalarProduct<double,3>(v,v); } /** * Let \f$p_0, p_1, p_2 \in R^3\f$. The function getAngle * computes the angle between the edges \f$(p_0,p_1)\f$ and \f$(p_1,p_2)\f$ * @param p0 start point of edge 0 * @param p1 end point of edge 0 and start point of edge 1 * @param p2 end point of edge 1 * @return the angle between the edges */ double getAngle (const double p0[3], const double p1[3], const double p2[3]); /// converts the given degrees to radians inline double to_radians(double degrees) { return degrees*boost::math::constants::pi<double>()/180.; } template<typename Type> Type limitValueInInterval(const Type variable, const Type lower_bound, const Type upper_bound) { if (variable < lower_bound) { return lower_bound; } if (variable > upper_bound) { return upper_bound; } return variable; } } // namespace MathLib
GB_unop__identity_fc64_int16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fc64_int16) // op(A') function: GB (_unop_tran__identity_fc64_int16) // C type: GxB_FC64_t // A type: int16_t // cast: GxB_FC64_t cij = GxB_CMPLX ((double) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC64 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc64_int16) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const int16_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++) { int16_t aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; int16_t aij = Ax [p] ; GxB_FC64_t z = GxB_CMPLX ((double) (aij), 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc64_int16) ( 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
for_simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 -verify %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 -verify=expected,omp50 -verify %s -Wuninitialized void xxx(int argc) { int x; // expected-note {{initialize the variable 'x' to silence this warning}} #pragma omp for simd for (int i = 0; i < 10; ++i) argc = x; // expected-warning {{variable 'x' is uninitialized when used here}} } // expected-error@+1 {{unexpected OpenMP directive '#pragma omp for simd'}} #pragma omp for simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp for simd'}} #pragma omp for simd foo void test_no_clause() { int i; #pragma omp for simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp for simd' must be a for loop}} #pragma omp for simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp parallel #pragma omp for simd 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; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp for simd' are ignored}} #pragma omp for simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp for simd' are ignored}} #pragma omp for simd; for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp for simd' are ignored}} #pragma omp for simd linear(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp for simd' are ignored}} #pragma omp for simd private(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp for simd' are ignored}} #pragma omp for simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp for simd safelen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd safelen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp for simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp for simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp for simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp for simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp for simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp for simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp for simd simdlen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd simdlen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp for simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp for simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp for simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp for simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp for simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp for simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp for simd simdlen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_safelen_simdlen() { int i; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp for simd simdlen(6) safelen(5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp for simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; #pragma omp parallel // expected-error@+1 {{expected '('}} #pragma omp for simd collapse for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd collapse( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd collapse() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd collapse(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd collapse(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+2 {{extra tokens at the end of '#pragma omp for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp for simd collapse 4) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel #pragma omp for simd 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(); #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp for simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp for simd', but found only 1}} #pragma omp parallel // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd collapse(2.5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp for simd collapse(foo()) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp for simd collapse(-5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp for simd collapse(0) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp for simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd collapse(2) for (i = 0; i < 16; ++i) // expected-note {{defined as lastprivate}} // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for simd' 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 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp for simd reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd linear( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp for simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp for simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp for simd linear(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp for simd linear(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp for simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp for simd linear(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp for simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp for simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd linear(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be linear}} #pragma omp for simd linear(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as private}} // expected-error@+1 {{private variable cannot be linear}} #pragma omp for simd private(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be private}} #pragma omp for simd linear(x) private(x) for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{zero linear step (x and other variables in clause should probably be const)}} #pragma omp for simd linear(x, y : 0) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be lastprivate}} #pragma omp for simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp for simd lastprivate(x) linear(x) for (i = 0; i < 16; ++i) ; } void test_aligned() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd aligned( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp for simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp for simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp for simd aligned(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp for simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp for simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp for simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp for simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp for simd aligned(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp for simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp for simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd aligned(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp for simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp for simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as aligned}} // expected-error@+1 {{a variable cannot appear in more than one aligned clause}} #pragma omp for simd aligned(x) aligned(z, x) for (i = 0; i < 16; ++i) ; // expected-note@+3 {{defined as aligned}} // expected-error@+2 {{a variable cannot appear in more than one aligned clause}} // expected-error@+1 2 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp for simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; #pragma omp parallel // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd private( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp for simd private(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp for simd private(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd private() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd private(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp for simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp for simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp for simd lastprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp for simd lastprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp for simd lastprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd lastprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd lastprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp for simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp for simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp for simd firstprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp for simd firstprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp for simd firstprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd firstprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp for simd firstprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp for simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp for simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp for simd 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]; #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp for simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp for simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void test_nontemporal() { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 2 {{expected expression}} #pragma omp for simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{expected expression}} #pragma omp for simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{expected expression}} #pragma omp for simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} omp50-error@+1 {{expected variable name}} #pragma omp for simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp for simd nontemporal(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp for simd nontemporal(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp for simd nontemporal(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp for simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp for simd nontemporal(x :, ) for (i = 0; i < 16; ++i) ; // omp50-note@+2 {{defined as nontemporal}} // omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp for simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} #pragma omp for simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} #pragma omp for simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp for simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; #pragma omp parallel // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} #pragma omp for simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp for simd'}} #pragma omp for simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; }
omp_for_schedule_auto_nothreadprivate.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdlib.h> #include <math.h> #include "omp_testsuite.h" int test_omp_for_auto() { int j; int sum; int sum0; int known_sum; int threadsnum; sum = 0; sum0 = 12345; // array which keeps track of which threads participated in the for loop // e.g., given 4 threads, [ 0 | 1 | 1 | 0 ] implies // threads 0 and 3 did not, threads 1 and 2 did int max_threads = omp_get_max_threads(); int* active_threads = (int*)malloc(sizeof(int)*max_threads); for(j = 0; j < max_threads; j++) active_threads[j] = 0; #pragma omp parallel { int i; int sum1 = 0; #pragma omp for firstprivate(sum0) schedule(auto) for (i = 1; i <= LOOPCOUNT; i++) { active_threads[omp_get_thread_num()] = 1; sum0 = sum0 + i; sum1 = sum0; } #pragma omp critical { sum = sum + sum1; } } // count the threads that participated (sum is stored in threadsnum) threadsnum=0; for(j = 0; j < max_threads; j++) { if(active_threads[j]) threadsnum++; } free(active_threads); known_sum = 12345 * threadsnum + (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; return (known_sum == sum); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_for_auto()) { num_failed++; } } return num_failed; }
convolution_pack8to4_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_pack8to4_int8_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_int8, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { int* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __m128i _sum0 = _mm_setzero_si128(); __m128i _sum1 = _mm_setzero_si128(); __m128i _sum2 = _mm_setzero_si128(); __m128i _sum3 = _mm_setzero_si128(); const signed char* kptr = weight_data_int8.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const signed char* sptr = m.row<signed char>(i * stride_h) + j * stride_w * 8; for (int k = 0; k < maxk; k++) { // TODO use _mm_cvtepi8_epi16 on sse4.1 __m128i _val = _mm_loadl_epi64((const __m128i*)(sptr + space_ofs[k] * 8)); _val = _mm_unpacklo_epi8(_val, _mm_cmpgt_epi8(_mm_setzero_si128(), _val)); // TODO use _mm_cvtepi8_epi16 on sse4.1 __m128i _w01 = _mm_loadu_si128((const __m128i*)kptr); __m128i _w23 = _mm_loadu_si128((const __m128i*)(kptr + 16)); __m128i _extw01 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w01); __m128i _extw23 = _mm_cmpgt_epi8(_mm_setzero_si128(), _w23); __m128i _w0 = _mm_unpacklo_epi8(_w01, _extw01); __m128i _w1 = _mm_unpackhi_epi8(_w01, _extw01); __m128i _w2 = _mm_unpacklo_epi8(_w23, _extw23); __m128i _w3 = _mm_unpackhi_epi8(_w23, _extw23); __m128i _sl0 = _mm_mullo_epi16(_val, _w0); __m128i _sh0 = _mm_mulhi_epi16(_val, _w0); __m128i _sl1 = _mm_mullo_epi16(_val, _w1); __m128i _sh1 = _mm_mulhi_epi16(_val, _w1); __m128i _sl2 = _mm_mullo_epi16(_val, _w2); __m128i _sh2 = _mm_mulhi_epi16(_val, _w2); __m128i _sl3 = _mm_mullo_epi16(_val, _w3); __m128i _sh3 = _mm_mulhi_epi16(_val, _w3); _sum0 = _mm_add_epi32(_sum0, _mm_unpacklo_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpacklo_epi16(_sl1, _sh1)); _sum2 = _mm_add_epi32(_sum2, _mm_unpacklo_epi16(_sl2, _sh2)); _sum3 = _mm_add_epi32(_sum3, _mm_unpacklo_epi16(_sl3, _sh3)); _sum0 = _mm_add_epi32(_sum0, _mm_unpackhi_epi16(_sl0, _sh0)); _sum1 = _mm_add_epi32(_sum1, _mm_unpackhi_epi16(_sl1, _sh1)); _sum2 = _mm_add_epi32(_sum2, _mm_unpackhi_epi16(_sl2, _sh2)); _sum3 = _mm_add_epi32(_sum3, _mm_unpackhi_epi16(_sl3, _sh3)); kptr += 32; } } // transpose 4x4 { __m128i _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = _mm_unpacklo_epi32(_sum0, _sum1); _tmp1 = _mm_unpacklo_epi32(_sum2, _sum3); _tmp2 = _mm_unpackhi_epi32(_sum0, _sum1); _tmp3 = _mm_unpackhi_epi32(_sum2, _sum3); _sum0 = _mm_unpacklo_epi64(_tmp0, _tmp1); _sum1 = _mm_unpackhi_epi64(_tmp0, _tmp1); _sum2 = _mm_unpacklo_epi64(_tmp2, _tmp3); _sum3 = _mm_unpackhi_epi64(_tmp2, _tmp3); } _sum0 = _mm_add_epi32(_sum0, _sum1); _sum2 = _mm_add_epi32(_sum2, _sum3); _sum0 = _mm_add_epi32(_sum0, _sum2); _mm_storeu_si128((__m128i*)(outptr + j * 4), _sum0); } outptr += outw * 4; } } }
pr38704.c
// RUN: %libomptarget-compile-run-and-check-aarch64-unknown-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-powerpc64le-ibm-linux-gnu // RUN: %libomptarget-compile-run-and-check-x86_64-pc-linux-gnu // RUN: %libomptarget-compile-run-and-check-nvptx64-nvidia-cuda // Clang 6.0 doesn't use the new map interface, undefined behavior when // the compiler emits "old" interface code for structures. // UNSUPPORTED: clang-6 #include <stdio.h> #include <stdlib.h> typedef struct { int *ptr1; int *ptr2; } StructWithPtrs; int main(int argc, char *argv[]) { StructWithPtrs s, s2; s.ptr1 = malloc(sizeof(int)); s.ptr2 = malloc(2 * sizeof(int)); s2.ptr1 = malloc(sizeof(int)); s2.ptr2 = malloc(2 * sizeof(int)); #pragma omp target enter data map(to: s2.ptr2[0:1]) #pragma omp target map(s.ptr1[0:1], s.ptr2[0:2]) { s.ptr1[0] = 1; s.ptr2[0] = 2; s.ptr2[1] = 3; } #pragma omp target exit data map(from: s2.ptr1[0:1], s2.ptr2[0:1]) // CHECK: s.ptr1[0] = 1 // CHECK: s.ptr2[0] = 2 // CHECK: s.ptr2[1] = 3 printf("s.ptr1[0] = %d\n", s.ptr1[0]); printf("s.ptr2[0] = %d\n", s.ptr2[0]); printf("s.ptr2[1] = %d\n", s.ptr2[1]); free(s.ptr1); free(s.ptr2); free(s2.ptr1); free(s2.ptr2); return 0; }
GB_assign_zombie1.c
//------------------------------------------------------------------------------ // GB_assign_zombie1: delete all entries in C(:,j) for GB_assign //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // C(:,j)<!> = anything: GrB_Row_assign or GrB_Col_assign with an empty // complemented mask requires all entries in the C(:,j) vector to be deleted. #include "GB_assign.h" void GB_assign_zombie1 ( GrB_Matrix C, const int64_t j, GB_Context Context ) { //-------------------------------------------------------------------------- // get C(:,j) //-------------------------------------------------------------------------- int64_t *GB_RESTRICT Ci = C->i ; int64_t pC_start, pC_end, pleft = 0, pright = C->nvec-1 ; GB_lookup (C->is_hyper, C->h, C->p, &pleft, pright, j, &pC_start, &pC_end) ; int64_t cjnz = pC_end - pC_start ; int64_t nzombies = C->nzombies ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (cjnz, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // C(:,j) = empty //-------------------------------------------------------------------------- int64_t pC ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(+:nzombies) for (pC = pC_start ; pC < pC_end ; pC++) { int64_t i = Ci [pC] ; if (!GB_IS_ZOMBIE (i)) { // delete C(i,j) by marking it as a zombie nzombies++ ; Ci [pC] = GB_FLIP (i) ; } } //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- C->nzombies = nzombies ; }
omp6.c
// note not doing O0 below as to ensure we get tbaa // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // note not doing O0 below as to ensure we get tbaa // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 -Xclang -disable-llvm-optzns %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O1 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O2 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi // RUN: if [ %llvmver -ge 9 ]; then %clang -fopenmp -std=c11 -fno-vectorize -fno-unroll-loops -O3 %s -S -emit-llvm -o - | %opt - %loadEnzyme -enzyme -enzyme-inline=1 -S | %clang -fopenmp -x ir - -o %s.out && %s.out ; fi # include <stdio.h> # include <stdlib.h> #include <math.h> #include "test_utils.h" __attribute__((noinline)) void set(double *a, double x){ a[0] = x; } void msg(double* in) { #pragma omp parallel for for (unsigned long long i=0; i<20; i++) { double m; set(&m, in[i]); in[i] = m * m; } } void __enzyme_autodiff(void*, ...); int main ( int argc, char *argv[] ) { double array[20]; for(int i=0; i<20; i++) array[i] = i+1; double darray[20]; for(int i=0; i<20; i++) darray[i] = 1.0; __enzyme_autodiff((void*)msg, &array, &darray); for(int i=0; i<20; i++) { APPROX_EQ(darray[i], 2 * (i+1), 1e-10); } return 0; }
Example_nthrs_dynamic.1.c
/* * @@name: nthrs_dynamic.1c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success */ #include <omp.h> int main() { omp_set_dynamic(0); #pragma omp parallel num_threads(10) { /* do work here */ } return 0; }
6.doacross.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include <omp.h> /* OpenMP */ #define N 16 #define M 5 /* Q1: In which order are the "Outside" and "Inside" messages printed? */ /* Q2: In which order are the iterations in the second loop nest executed? */ /* Q3: What would happen if you remove the invocation of sleep(1). Execute */ /* several times to answer in the general case. */ int main() { float a[N], b[N], c[N]; float a1[M][M], b1[M][M], c1[M][M]; omp_set_num_threads(8); #pragma omp parallel for ordered(1) schedule(dynamic) for (int i=1; i<N; i++) { a[i] = 1.3; printf("Outside from %d executing %d\n", omp_get_thread_num(), i); #pragma omp ordered depend(sink: i-2) { printf("Inside from %d executing %d\n", omp_get_thread_num(), i); b[i] = a[i] * b[i-1]; } #pragma omp ordered depend(source) c[i] = b[i] * 0.1234; } #pragma omp parallel for ordered(2) schedule(dynamic) for (int i=1; i<M; i++) { for (int j=1; j<M; j++) { a1[i][j] = 3.45; #pragma omp ordered depend(sink: i-1,j) depend(sink: i,j-1) { printf("Computing iteration %d %d\n", i, j); b1[i][j] = a1[i][j] * (b1[i-1][j] + b1[i][j-1]); // sleep(1); } #pragma omp ordered depend(source) c1[i][j] = b1[i][j] / 2.19; } } return 0; }
DRB061-matrixvector1-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Matrix-vector multiplication: outer-level loop parallelization */ #include "omprace.h" #include <omp.h> #define N 100 double a[N][N],v[N],v_out[N]; int mv() { int i,j; #pragma omp parallel for private (i,j) for (i = 0; i < N; i++) { float sum = 0.0; for (j = 0; j < N; j++) { sum += a[i][j]*v[j]; } v_out[i] = sum; } return 0; } int main() { omprace_init(); mv(); omprace_fini(); return 0; }
DRB019-plusplus-var-yes.c
/* Copyright (C) 1991-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it andor 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 Unicode 10.0.0. Version 10.0 of the Unicode Standard is synchronized with ISOIEC 10646:2017, fifth edition, plus the following additions from Amendment 1 to the fifth edition: - 56 emoji characters - 285 hentaigana - 3 additional Zanabazar Square characters */ /* 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.comLLNL/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. */ /* Race condition on outLen due to unprotected writes. Adding private (outLen) can avoid race condition. But it is wrong semantically. Data race pairs: we allow two pair to preserve the original code pattern. 1. outLen@72:12 vs. outLen@72:12 2. output[]@72:5 vs. output[]@72:5 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char * argv[]) { int i; int inLen = 1000; int outLen = 0; int input[inLen]; int output[inLen]; int _ret_val_0; if (argc>1) { inLen=atoi(argv[1]); } #pragma cetus private(i) #pragma loop name main#0 #pragma cetus parallel #pragma omp parallel for private(i) for (i=0; i<inLen; ++ i) { input[i]=i; } #pragma cetus private(i) #pragma loop name main#1 for (i=0; i<inLen; ++ i) { output[outLen ++ ]=input[i]; } printf("output[0]=%d\n", output[0]); _ret_val_0=0; return _ret_val_0; }
GB_unaryop__minv_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_fp32_fp32 // op(A') function: GB_tran__minv_fp32_fp32 // C type: float // A type: float // cast: float cij = (float) aij // unaryop: cij = (1.0F)/aij #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = (1.0F)/x ; // casting #define GB_CASTING(z, aij) \ float z = (float) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp32_fp32 ( float *Cx, // Cx and Ax may be aliased float *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp32_fp32 ( 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
convolution_1x1_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // author:BUG1989 (https://github.com/BUG1989/) Long-term support. // author:FuGuangping (https://github.com/fu1899) Implemented the first version of INT8 quantization on ARMv7. // // Copyright (C) 2019 BUG1989. 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 inline signed char float2int8(float v) { int int32 = round(v); if (int32 > 127) return 127; if (int32 < -127) return -127; return (signed char)int32; } #if __aarch64__ #if 1 #include "gemm_symm_int8.h" static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(outch, inch, (size_t)1u); const int8_t *a = _kernel; int8_t *sa = kernel_tm; reorder_a((int8_t*)a, sa, outch, inch, inch); } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t* pData = bottom_blob; int8_t *pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int32_t *pc = top_blob; const int8_t *pa = kernel; const int8_t *pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, 0, 0, opt); } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat scales_tm(m); ncnn::Mat bias_tm(m); float* scales = scales_tm; const float* bias = _bias; // outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); // the equation could convert to: // out = float2int8( (float)sum * (scale_requant_in * scale_requant_out) + (bias * scale_requant_out) ) // prebuild the list of (scales_requant_in*scale_requant_out) for (size_t i = 0; i < m; ++i) { scales_tm[i] = scales_requant[2*i] * scales_requant[2*i + 1]; } if (!_bias.empty()) { for (size_t i = 0; i < m; ++i) { bias_tm[i] = bias[i] * scales_requant[2*i + 1]; } bias = bias_tm; } ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t *pData = bottom_blob; int8_t *pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int8_t *pc = top_blob; const int8_t *pa = kernel; const int8_t *pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, scales, (float*)bias, opt); } #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; // kernel memory packed 4 x 4 kernel_tm.create(4*4, inch/4 + inch%4, outch/4 + outch%4, (size_t)1u); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; const signed char* k0 = kernel + (p+0)*inch; const signed char* k1 = kernel + (p+1)*inch; const signed char* k2 = kernel + (p+2)*inch; const signed char* k3 = kernel + (p+3)*inch; signed char* ktmp = kernel_tm.channel(p/4); int q=0; for (; q+1<inch; q+=2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp[2] = k1[0]; ktmp[3] = k1[1]; ktmp[4] = k2[0]; ktmp[5] = k2[1]; ktmp[6] = k3[0]; ktmp[7] = k3[1]; ktmp += 8; k0 += 2; k1 += 2; k2 += 2; k3 += 2; } for (; q<inch; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch; signed char* ktmp = kernel_tm.channel(p/4 + p%4); int q=0; for (; q+1<inch; q=q+2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp += 2; k0 += 2; } for (; q<inch; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size/4 + size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p+1); int* outptr2 = top_blob.channel(p+2); int* outptr3 = top_blob.channel(p+3); int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" "st1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if 0//__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+3<inch; q=q+4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } vst1q_lane_s32(outptr0, _sum, 0); vst1q_lane_s32(outptr1, _sum, 1); vst1q_lane_s32(outptr2, _sum, 2); vst1q_lane_s32(outptr3, _sum, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } vst1q_s32(outptr0, _sum); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; #endif outptr0 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size/4 + size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p+1); signed char* outptr2 = top_blob.channel(p+2); signed char* outptr3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float scale_requant_in0 = scales_requant[2*p]; const float scale_requant_out0 = scales_requant[2*p+1]; const float scale_requant_in1 = scales_requant[2*(p+1)]; const float scale_requant_out1 = scales_requant[2*(p+1)+1]; const float scale_requant_in2 = scales_requant[2*(p+2)]; const float scale_requant_out2 = scales_requant[2*(p+2)+1]; const float scale_requant_in3 = scales_requant[2*(p+3)]; const float scale_requant_out3 = scales_requant[2*(p+3)+1]; float32x4_t _bias03, _scale_in03, _scale_out03; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _bias1 = vdupq_n_f32(bias1); float32x4_t _bias2 = vdupq_n_f32(bias2); float32x4_t _bias3 = vdupq_n_f32(bias3); _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4); #if 1 //__ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" "scvtf v22.4s, v22.4s \n" "scvtf v23.4s, v23.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, %17.s[0] \n" "fmul v21.4s, v21.4s, %17.s[1] \n" "fmul v22.4s, v22.4s, %17.s[2] \n" "fmul v23.4s, v23.4s, %17.s[3] \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, %13.4s \n" "fadd v21.4s, v21.4s, %14.4s \n" "fadd v22.4s, v22.4s, %15.4s \n" "fadd v23.4s, v23.4s, %16.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, %18.s[0] \n" "fmul v21.4s, v21.4s, %18.s[1] \n" "fmul v22.4s, v22.4s, %18.s[2] \n" "fmul v23.4s, v23.4s, %18.s[3] \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" "fcvtas v22.4s, v22.4s \n" "fcvtas v23.4s, v23.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn2 v7.8h, v21.4s \n" "sqxtn v8.4h, v22.4s \n" "sqxtn2 v8.8h, v23.4s \n" // top_s16 -> top_s8 "sqxtn v0.8b, v7.8h \n" "sqxtn v1.8b, v8.8h \n" // save top_s8 "st1 {v0.s}[0], [%0] \n" "st1 {v0.s}[1], [%1] \n" "st1 {v1.s}[0], [%2] \n" "st1 {v1.s}[1], [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias0), // %13 "w"(_bias1), // %14 "w"(_bias2), // %15 "w"(_bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = float2int8(((float)sum0_0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[1] = float2int8(((float)sum0_1 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[2] = float2int8(((float)sum0_2 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[3] = float2int8(((float)sum0_3 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1_0 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[1] = float2int8(((float)sum1_1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[2] = float2int8(((float)sum1_2 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[3] = float2int8(((float)sum1_3 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2_0 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[1] = float2int8(((float)sum2_1 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[2] = float2int8(((float)sum2_2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[3] = float2int8(((float)sum2_3 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3_0 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[1] = float2int8(((float)sum3_1 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[2] = float2int8(((float)sum3_2 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[3] = float2int8(((float)sum3_3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+3<inch; q=q+4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in03); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias03); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out03); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_lane_s8(outptr0, _sum_s8, 0); vst1_lane_s8(outptr1, _sum_s8, 1); vst1_lane_s8(outptr2, _sum_s8, 2); vst1_lane_s8(outptr3, _sum_s8, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias0); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_s8(outptr0, _sum_s8); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0[1] = float2int8(((float)sum1 * scale_requant_in + bias0) * scale_requant_out); outptr0[2] = float2int8(((float)sum2 * scale_requant_in + bias0) * scale_requant_out); outptr0[3] = float2int8(((float)sum3 * scale_requant_in + bias0) * scale_requant_out); #endif outptr0 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0++; } } } #endif #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; kernel_tm.create(4*4, inch/4 + inch%4, outch/4 + outch%4, (size_t)1u); int p = 0; for (; p+3<outch; p+=4) { const signed char* kernel0 = kernel + (p+0)*inch; const signed char* kernel1 = kernel + (p+1)*inch; const signed char* kernel2 = kernel + (p+2)*inch; const signed char* kernel3 = kernel + (p+3)*inch; signed char* ktmp = kernel_tm.channel(p/4); for (int q=0; q<inch; q++) { // kernel0...3 0 ktmp[0] = kernel0[0]; ktmp[1] = kernel1[0]; ktmp[2] = kernel2[0]; ktmp[3] = kernel3[0]; ktmp += 4; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; } } for (; p<outch; p++) { const signed char* kernel0 = kernel + p*inch; signed char* ktmp = kernel_tm.channel(p/4 + p%4); for (int q=0; q<inch; q++) { ktmp[0] = kernel0[0]; ktmp++; kernel0++; } } } /* * Convolution 1x1 quantized with sgemm int8 */ static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // interleave Mat tmp(8*4, inch/4+inch%4, size/8 + (size%8)/4 + size%4, 1u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 8; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8); for (int q=0; q<inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0" ); img0 += bottom_blob.cstep; #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = remain_size_start + ii * 4; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p+1); int* outptr2 = top_blob.channel(p+2); int* outptr3 = top_blob.channel(p+3); int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d7}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q8, d4, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q9, d5, d0[1] \n" "vmlal.s16 q10, d4, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q11, d5, d0[2] \n" "vmlal.s16 q12, d4, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q13, d5, d0[3] \n" "vmlal.s16 q6, d6, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q7, d7, d1[0] \n" "vmlal.s16 q8, d6, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q9, d7, d1[1] \n" "vmlal.s16 q10, d6, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q11, d7, d1[2] \n" "vmlal.s16 q12, d6, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q13, d7, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n"// sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n"// sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n"// sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" "vst1.s32 {d16-d19}, [%1]! \n" "vst1.s32 {d20-d23}, [%2]! \n" "vst1.s32 {d24-d27}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d5}, [%4]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n"// sum0 = (a00-a03) * k00 "vmlal.s16 q7, d4, d0[1] \n"// sum1 = (a00-a03) * k10 "vmlal.s16 q8, d4, d0[2] \n"// sum2 = (a00-a03) * k20 "vmlal.s16 q9, d4, d0[3] \n"// sum3 = (a00-a03) * k30 "vmlal.s16 q6, d5, d1[0] \n"// sum0 += (a10-a13) * k01 "vmlal.s16 q7, d5, d1[1] \n"// sum1 += (a10-a13) * k11 "vmlal.s16 q8, d5, d1[2] \n"// sum2 += (a10-a13) * k21 "vmlal.s16 q9, d5, d1[3] \n"// sum3 += (a10-a13) * k31 "vmlal.s16 q6, d6, d2[0] \n"// sum0 += (a20-a23) * k02 "vmlal.s16 q7, d6, d2[1] \n"// sum1 += (a20-a23) * k12 "vmlal.s16 q8, d6, d2[2] \n"// sum2 += (a20-a23) * k22 "vmlal.s16 q9, d6, d2[3] \n"// sum3 += (a20-a23) * k32 "vmlal.s16 q6, d7, d3[0] \n"// sum0 += (a30-a33) * k03 "vmlal.s16 q7, d7, d3[1] \n"// sum1 += (a30-a33) * k13 "vmlal.s16 q8, d7, d3[2] \n"// sum2 += (a30-a33) * k23 "vmlal.s16 q9, d7, d3[3] \n"// sum3 += (a30-a33) * k33 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n"// sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n"// sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n"// sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" "vst1.s32 {d14-d15}, [%1]! \n" "vst1.s32 {d16-d17}, [%2]! \n" "vst1.s32 {d18-d19}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n"// tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n"// a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n"// (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n"// (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n"// (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \n" "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d20[0]}, [%0]! \n" "vst1.s32 {d20[1]}, [%1]! \n" "vst1.s32 {d21[0]}, [%2]! \n" "vst1.s32 {d21[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n"// (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n"// (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n"// (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm int8 // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // int* outptr0 = out0; // // for (int i=0; i<size; i++) // { // int sum = 0; // // const signed char* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const signed char* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // interleave Mat tmp(8*4, inch/4+inch%4, size/8 + (size%8)/4 + size%4, 1u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 8; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8); for (int q=0; q<inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0" ); img0 += bottom_blob.cstep; #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = remain_size_start + ii * 4; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p+1); signed char* outptr2 = top_blob.channel(p+2); signed char* outptr3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float scale_requant_in0 = scales_requant[2*p]; const float scale_requant_out0 = scales_requant[2*p+1]; const float scale_requant_in1 = scales_requant[2*(p+1)]; const float scale_requant_out1 = scales_requant[2*(p+1)+1]; const float scale_requant_in2 = scales_requant[2*(p+2)]; const float scale_requant_out2 = scales_requant[2*(p+2)+1]; const float scale_requant_in3 = scales_requant[2*(p+3)]; const float scale_requant_out3 = scales_requant[2*(p+3)+1]; #if __ARM_NEON float32x4_t _bias03, _scale_in03, _scale_out03; _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; #endif // __ARM_NEON int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d31}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d31 \n"// a30-a37 "vmovl.s8 q4, d30 \n"// a20-a27 "vmovl.s8 q15, d29 \n"// a10-a17 "vmovl.s8 q14, d28 \n"// a00-a07 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q7, d29, d0[0] \n" "vmlal.s16 q8, d28, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q9, d29, d0[1] \n" "vmlal.s16 q10, d28, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q11, d29, d0[2] \n" "vmlal.s16 q12, d28, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q13, d29, d0[3] \n" "vmlal.s16 q6, d30, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q7, d31, d1[0] \n" "vmlal.s16 q8, d30, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q9, d31, d1[1] \n" "vmlal.s16 q10, d30, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q11, d31, d1[2] \n" "vmlal.s16 q12, d30, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q13, d31, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n"// sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n"// sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n"// sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[0] \n" "vmul.f32 q8, q8, %e17[1] \n" "vmul.f32 q9, q9, %e17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q14 \n" "vadd.f32 q8, q8, q15 \n" "vadd.f32 q9, q9, q15 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" // sum1 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %e18[1] \n" "vmul.f32 q1, q9, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.8 {d16}, [%1]! \n" // sum2 // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" "vcvt.f32.s32 q11, q11 \n" "vcvt.f32.s32 q12, q12 \n" "vcvt.f32.s32 q13, q13 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %f17[0] \n" "vmul.f32 q11, q11, %f17[0] \n" "vmul.f32 q12, q12, %f17[1] \n" "vmul.f32 q13, q13, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, q4 \n" "vadd.f32 q11, q11, q4 \n" "vadd.f32 q12, q12, q5 \n" "vadd.f32 q13, q13, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %f18[0] \n" "vmul.f32 q1, q11, %f18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d20, q0 \n" "vqmovn.s32 d21, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d20, q10 \n" // save top_s8 "vst1.8 {d20}, [%2]! \n" // sum3 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q12, %f18[1] \n" "vmul.f32 q1, q13, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d24, q0 \n" "vqmovn.s32 d25, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d24, q12 \n" // save top_s8 "vst1.8 {d24}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13" ,"q14" ,"q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d29}, [%4]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q15, d29 \n"// a20-a23,a30-a33 "vmovl.s8 q14, d28 \n"// a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n"// sum0 = (a00-a03) * k00 "vmlal.s16 q7, d28, d0[1] \n"// sum1 = (a00-a03) * k10 "vmlal.s16 q8, d28, d0[2] \n"// sum2 = (a00-a03) * k20 "vmlal.s16 q9, d28, d0[3] \n"// sum3 = (a00-a03) * k30 "vmlal.s16 q6, d29, d1[0] \n"// sum0 += (a10-a13) * k01 "vmlal.s16 q7, d29, d1[1] \n"// sum1 += (a10-a13) * k11 "vmlal.s16 q8, d29, d1[2] \n"// sum2 += (a10-a13) * k21 "vmlal.s16 q9, d29, d1[3] \n"// sum3 += (a10-a13) * k31 "vmlal.s16 q6, d30, d2[0] \n"// sum0 += (a20-a23) * k02 "vmlal.s16 q7, d30, d2[1] \n"// sum1 += (a20-a23) * k12 "vmlal.s16 q8, d30, d2[2] \n"// sum2 += (a20-a23) * k22 "vmlal.s16 q9, d30, d2[3] \n"// sum3 += (a20-a23) * k32 "vmlal.s16 q6, d31, d3[0] \n"// sum0 += (a30-a33) * k03 "vmlal.s16 q7, d31, d3[1] \n"// sum1 += (a30-a33) * k13 "vmlal.s16 q8, d31, d3[2] \n"// sum2 += (a30-a33) * k23 "vmlal.s16 q9, d31, d3[3] \n"// sum3 += (a30-a33) * k33 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n"// sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n"// sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n"// sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0-1 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[1] \n" "vmul.f32 q8, q8, %f17[0] \n" "vmul.f32 q9, q9, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q15 \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.s32 {d12[0]}, [%0]! \n" "vst1.s32 {d12[1]}, [%1]! \n" // sum1-2 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %f18[0] \n" "vmul.f32 q1, q9, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.s32 {d16[0]}, [%2]! \n" "vst1.s32 {d16[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n"// tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n"// a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n"// (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n"// (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n"// (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \n" "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, %q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12[0]}, [%0]! \n" "vst1.8 {d12[1]}, [%1]! \n" "vst1.8 {d12[2]}, [%2]! \n" "vst1.8 {d12[3]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias03), // %13 "w"(_scale_in03), // %14 "w"(_scale_out03) // %15 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; #if __ARM_NEON float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); #endif // __ARM_NEON int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" "vmul.f32 q7, q7, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" "vadd.f32 q7, q7, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" "vmul.f32 q1, q7, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n"// (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n"// (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n"// (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" "vst1.s32 {d12[0]}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } #endif
boundary.c
#include "boundary.h" #include "LBDefinitions.h" #include "helper.h" #include "computeCellValues.h" /** * Set NOSLIP condition */ void setNoSlip(float * collideField, int * flagField, int * node, int * n) { int i, coord_dest[3], flag; float * cell_ptr; /* for each lattice */ for (i = 0; i < Q; i++) { /* compute a cell where lattice is pointing*/ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; /* does the pointed cell lay in our domain? */ if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0) { flag = *getFlag(flagField, coord_dest, n); /* if pointed cell is FLUID or INTERFACE */ if (flag == FLUID || flag == INTERFACE) { /* get pointer to the i-th lattice of boundary cell */ cell_ptr = getEl(collideField, node, i, n); /* NOSLIP */ /* set i-th lattice to inverse lattice of the computed inner cell */ *cell_ptr= *getEl(collideField, coord_dest, Q-1-i, n); } } } } /** * Set MOVING_WALL condition */ void setMovingWall(float * collideField, int * flagField, const float * const wallVelocity, int * node, int * n) { int i, coord_dest[3], flag; float * cell_ptr; float dotProd; float density; /* for each lattice */ for (i = 0; i < Q; i++) { /* compute a cell where lattice is pointing*/ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; /* does the pointed cell lay in our domain? */ if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0 ) { flag = *getFlag(flagField, coord_dest, n); /* if pointed cell is FLUID */ if (flag == FLUID || flag == INTERFACE) { /* get pointer to the i-th lattice of boundary cell */ cell_ptr = getEl(collideField, node, i, n); /* NOSLIP */ /* set i-th lattice to inverse lattice of the computed inner cell */ *cell_ptr= *getEl(collideField, coord_dest, 18-i, n); dotProd = 0; /* compute inner product of wall velocity and i-th lattice velocity */ for (int j = 0; j < 3; ++j) { dotProd += LATTICEVELOCITIES[i][j] * wallVelocity[j]; } computeDensity(getEl(collideField, coord_dest, 0, n), &density); /* Set boundary i-th lattice with respect to the formula for MOVING_WALL */ *cell_ptr += 2.0 * LATTICEWEIGHTS[i] * dotProd * density / (C_S*C_S); } } } } /** * Set OUTFLOW condition */ void setOutflow(float * collideField, int * flagField, const float * const ro_ref, int * node, int * n) { int i, coord_dest[3], flag; float * cell_ptr; float feq[Q]; float velocity[D]; float * fluidCell; /* for each lattice */ for (i = 0; i < Q; i++) { /* compute a cell where lattice is pointing*/ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; /* does the pointed cell lay in our domain? */ if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0 ) { flag = *getFlag(flagField, coord_dest, n); if (flag == FLUID || flag == INTERFACE) { /* get pointer to the fluid cell */ fluidCell = getEl(collideField, coord_dest, 0, n); /* compute velocity of the fluid cell */ computeVelocity(fluidCell, ro_ref, velocity); /* compute f-equilibrium of the fluid cell */ computeFeq(ro_ref, velocity, feq); /* pointer to the i-th lattice of the boundary cell */ cell_ptr = getEl(collideField, node, i, n); /* set boundary */ *cell_ptr = feq[Q - i -1] + feq[i] - fluidCell[Q - 1 - i]; } } } } /** * Set INFLOW condition */ void setInflow(float * collideField, int * flagField, const char * const scenario, const float * const Re, const float * const ro_ref, const float * const ro_in, const float * const inVelocity, int * node, int * n) { int i, coord_dest[3], flag; float * cell_ptr; float feq[Q]; float velocity[3]; /* If scenario is parabolic */ if (strcmp(scenario, PARABOLIC_SCENARIO) == 0) { velocity[0] = 0; velocity[1] = 0; velocity[2] = - 0.5 * (*Re) * (*ro_in - *ro_ref) / n[0] * node[0] * (node[0] - n[2]); } else { velocity[0] = inVelocity[0]; velocity[1] = inVelocity[1]; velocity[2] = inVelocity[2]; } /* for each lattice */ for (i = 0; i < Q; i++) { /* compute a cell where lattice is pointing*/ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; /* does the pointed cell lay in our domain? */ if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0) { flag = *getFlag(flagField, coord_dest, n); if (flag == FLUID || flag == INTERFACE) { computeFeq(ro_ref, velocity, feq); cell_ptr = getEl(collideField, node, i, n); *cell_ptr = feq[i]; } } } } /** * Set FREE-SLIP condition */ void setFreeSlip(float * collideField, int * flagField, int * node, int * n) { int i, j, k, coord_dest[3], non_fluid_cell[3], flag; float * cell_ptr, sum, lv0, lv1, lv2; for (i = 0; i < Q; i++) { /* Initialize the cell with a flag, that will later make possible to know if some lattice was modified*/ *getEl(collideField, node, i, n) = 0; } for (i = 0; i < Q; i++) { lv0 = LATTICEVELOCITIES[i][0]; lv1 = LATTICEVELOCITIES[i][1]; lv2 = LATTICEVELOCITIES[i][2]; sum = lv0 * lv0 + lv1 * lv1 + lv2 * lv2; /* In this part we are interested only in the face of the cell, thus the lattice has just one component */ if (sum == 1.0){ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; /* If the pointed cell does not fall out of bounds */ if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0) { flag = *getFlag(flagField, coord_dest, n); /* if pointed cell is FLUID */ if (flag == FLUID || flag == INTERFACE) { for (j = 0; j < Q; j++) { /* looking for a direction with one of the components inverse to the direction of the face */ if(LATTICEVELOCITIES[i][0]*LATTICEVELOCITIES[j][0] == -1.0 || LATTICEVELOCITIES[i][1]*LATTICEVELOCITIES[j][1] == -1.0 || LATTICEVELOCITIES[i][2]*LATTICEVELOCITIES[j][2] == -1.0) { /* If the selected direction of the fluid cell falls on another fluid cell, they will interact in the streaming step */ non_fluid_cell[0] = coord_dest[0] + LATTICEVELOCITIES[j][0]; non_fluid_cell[1] = coord_dest[1] + LATTICEVELOCITIES[j][1]; non_fluid_cell[2] = coord_dest[2] + LATTICEVELOCITIES[j][0]; flag = *getFlag(flagField, non_fluid_cell, n); if (flag != FLUID && flag != INTERFACE) { for (k = 0; k < Q; k++) { /* Search for a (unique) direction in the boundary cell which is the reflection of the fluid cell */ if(( LATTICEVELOCITIES[k][0]*LATTICEVELOCITIES[i][0] == 1.0 || LATTICEVELOCITIES[k][1]*LATTICEVELOCITIES[i][1] == 1.0 || LATTICEVELOCITIES[k][2]*LATTICEVELOCITIES[i][2] == 1.0 ) && ( LATTICEVELOCITIES[k][0]*LATTICEVELOCITIES[j][0] == 1.0 || LATTICEVELOCITIES[k][1]*LATTICEVELOCITIES[j][1] == 1.0 || LATTICEVELOCITIES[k][2]*LATTICEVELOCITIES[j][2] == 1.0 )){ cell_ptr = getEl(collideField, node, k, n); *cell_ptr = *getEl(collideField, coord_dest, j, n); break; } } } } } } } } } /* for each lattice */ for (i = 0; i < Q; i++) { /* If the lattice was not modified in the previous process, this happens for the inverse direction of the lattice going out of the face * is also possible that the boundary does not share a facet with the fluid but it shares an edge or vertex. * In those cases the boundary behaves as non slip, bouncing back everything*/ if (*getEl(collideField, node, i, n) == 0){ /* compute a cell where lattice is pointing*/ coord_dest[0] = node[0] + LATTICEVELOCITIES[i][0]; coord_dest[1] = node[1] + LATTICEVELOCITIES[i][1]; coord_dest[2] = node[2] + LATTICEVELOCITIES[i][2]; if (coord_dest[0] < n[0] && coord_dest[1] < n[1] && coord_dest[2] < n[2] && coord_dest[0] >= 0 && coord_dest[1] >= 0 && coord_dest[2] >= 0) { flag = *getFlag(flagField, coord_dest, n); /* if pointed cell is FLUID */ if (flag == FLUID || flag == INTERFACE) { /* get pointer to the i-th lattice of boundary cell */ cell_ptr = getEl(collideField, node, i, n); /* NOSLIP */ /* set i-th lattice to inverse lattice of the computed inner cell */ *cell_ptr= *getEl(collideField, coord_dest, Q-1-i, n); } } } } } void boundaryCell(float * collideField, int * flagField, const char * const scenario, const float * const Re, const float * const ro_ref, const float * const ro_in, const float * const velocity, int * node, int flag, int * n) { if (flag == GAS) { return; } else if (flag == NOSLIP) { setNoSlip(collideField, flagField, node, n); } else if (flag == MOVING_WALL) { setMovingWall(collideField, flagField, velocity, node, n); } else if (flag == INFLOW) { setInflow(collideField, flagField, scenario, Re, ro_ref, ro_in, velocity, node, n); } else if (flag == OUTFLOW) { setOutflow(collideField, flagField, ro_ref, node, n); } else if (flag == FREESLIP) { setFreeSlip(collideField, flagField, node, n); } else if (flag == PRESSURE_IN) { setOutflow(collideField, flagField, ro_in, node, n); } } void treatBoundary(float *collideField, int *flagField, const char * const scenario, const float * const Re, const float * const ro_ref, const float * const ro_in, const float * const velocity, int * length, int n_threads) { int x, y, z, flag, node[3]; int n[3] = { length[0] + 2, length[1] + 2, length[2] + 2 }; /* Pragma to parallelize the for loops for z and y using the indicated number of threads*/ #pragma omp parallel for schedule(dynamic) collapse(2) private(node, x, flag) num_threads(n_threads) for (z = 0; z < n[2]; z++) { for (y = 0; y < n[1]; y++) { node[2] = z; node[1] = y; for (x = 0; x < n[0]; x++) { node[0] = x; flag = *getFlag(flagField, node, n); /* If the cell is fluid, obstacle or interface then it does not require boundary treatment */ if (flag != FLUID && flag != OBSTACLE && flag != INTERFACE) { boundaryCell(collideField, flagField, scenario, Re, ro_ref, ro_in, velocity, node, flag, n); } } } } }
BaseDetector.h
#pragma once #include <memory> #include "defines.h" /// /// \brief The BaseDetector class /// struct KeyVal { KeyVal() = default; void Add(const std::string& key, const std::string& val) { m_config.emplace_back(key, val); } std::vector<std::pair<std::string, std::string>> m_config; }; /// /// \brief The BaseDetector class /// class BaseDetector { public: /// /// \brief BaseDetector /// \param frame /// BaseDetector(const cv::UMat& frame) { m_minObjectSize.width = std::max(5, frame.cols / 100); m_minObjectSize.height = m_minObjectSize.width; } /// /// \brief BaseDetector /// \param frame /// BaseDetector(const cv::Mat& frame) { m_minObjectSize.width = std::max(5, frame.cols / 100); m_minObjectSize.height = m_minObjectSize.width; } /// /// \brief ~BaseDetector /// virtual ~BaseDetector(void) = default; /// /// \brief Init /// \param config /// virtual bool Init(const config_t& config) = 0; /// /// \brief Detect /// \param frame /// virtual void Detect(const cv::UMat& frame) = 0; virtual void DetectMat(cv::Mat frame) { cv::UMat um = frame.getUMat(cv::ACCESS_READ); return Detect(um); } /// /// \brief Detect /// \param frames /// \param regions /// virtual void Detect(const std::vector<cv::UMat>& frames, std::vector<regions_t>& regions) { for (size_t i = 0; i < frames.size(); ++i) { Detect(frames[i]); auto res = GetDetects(); regions[i].assign(std::begin(res), std::end(res)); } } /// /// \brief ResetModel /// \param img /// \param roiRect /// virtual void ResetModel(const cv::UMat& /*img*/, const cv::Rect& /*roiRect*/) { } /// /// \brief ResetIgnoreMask /// virtual void ResetIgnoreMask() { if (!m_ignoreMask.empty()) m_ignoreMask = 255; } /// /// \brief UpdateIgnoreMask /// \param img /// \param roiRect /// virtual void UpdateIgnoreMask(const cv::UMat& img, cv::Rect roiRect) { if (m_ignoreMask.empty()) m_ignoreMask = cv::Mat(img.size(), CV_8UC1, cv::Scalar(255)); auto Clamp = [](int& v, int& size, int hi) { if (v < 0) { size += v; v = 0; } else if (v + size > hi - 1) { size = hi - 1 - v; } }; Clamp(roiRect.x, roiRect.width, m_ignoreMask.cols); Clamp(roiRect.y, roiRect.height, m_ignoreMask.rows); m_ignoreMask(roiRect) = 0; } /// /// \brief CanGrayProcessing /// virtual bool CanGrayProcessing() const = 0; /// /// \brief SetMinObjectSize /// \param minObjectSize /// void SetMinObjectSize(cv::Size minObjectSize) { m_minObjectSize = minObjectSize; } /// /// \brief GetDetects /// \return /// const regions_t& GetDetects() const { return m_regions; } /// /// \brief CalcMotionMap /// \param frame /// virtual void CalcMotionMap(cv::Mat& frame) { if (m_motionMap.size() != frame.size()) m_motionMap = cv::Mat(frame.size(), CV_32FC1, cv::Scalar(0, 0, 0)); cv::Mat foreground(m_motionMap.size(), CV_8UC1, cv::Scalar(0, 0, 0)); for (const auto& region : m_regions) { #if (CV_VERSION_MAJOR < 4) cv::ellipse(foreground, region.m_rrect, cv::Scalar(255, 255, 255), CV_FILLED); #else cv::ellipse(foreground, region.m_rrect, cv::Scalar(255, 255, 255), cv::FILLED); #endif } if (!m_ignoreMask.empty()) cv::bitwise_and(foreground, m_ignoreMask, foreground); cv::normalize(foreground, m_normFor, 255, 0, cv::NORM_MINMAX, m_motionMap.type()); double alpha = 0.95; cv::addWeighted(m_motionMap, alpha, m_normFor, 1 - alpha, 0, m_motionMap); const int chans = frame.channels(); const int height = frame.rows; #pragma omp parallel for for (int y = 0; y < height; ++y) { uchar* imgPtr = frame.ptr(y); const float* moPtr = reinterpret_cast<float*>(m_motionMap.ptr(y)); for (int x = 0; x < frame.cols; ++x) { for (int ci = chans - 1; ci < chans; ++ci) { imgPtr[ci] = cv::saturate_cast<uchar>(imgPtr[ci] + moPtr[0]); } imgPtr += chans; ++moPtr; } } #if 0 if (!m_ignoreMask.empty()) cv::imshow("ignoreMask", m_ignoreMask); #endif } /// static std::unique_ptr<BaseDetector> CreateDetector(tracking::Detectors detectorType, const config_t& config, const cv::UMat& gray); static std::unique_ptr<BaseDetector> CreateDetectorKV(tracking::Detectors detectorType, const KeyVal& config, const cv::Mat& gray); protected: regions_t m_regions; cv::Size m_minObjectSize; cv::Mat m_ignoreMask; // Motion map for visualization current detections cv::Mat m_motionMap; cv::Mat m_normFor; std::set<objtype_t> m_classesWhiteList; std::vector<cv::Rect> GetCrops(float maxCropRatio, cv::Size netSize, cv::Size imgSize) const { std::vector<cv::Rect> crops; const float whRatio = static_cast<float>(netSize.width) / static_cast<float>(netSize.height); int cropHeight = cvRound(maxCropRatio * netSize.height); int cropWidth = cvRound(maxCropRatio * netSize.width); if (imgSize.width / (float)imgSize.height > whRatio) { if (cropHeight >= imgSize.height) cropHeight = imgSize.height; cropWidth = cvRound(cropHeight * whRatio); } else { if (cropWidth >= imgSize.width) cropWidth = imgSize.width; cropHeight = cvRound(cropWidth / whRatio); } //std::cout << "Frame size " << imgSize << ", crop size = " << cv::Size(cropWidth, cropHeight) << ", ratio = " << maxCropRatio << std::endl; const int stepX = 3 * cropWidth / 4; const int stepY = 3 * cropHeight / 4; for (int y = 0; y < imgSize.height; y += stepY) { bool needBreakY = false; if (y + cropHeight >= imgSize.height) { y = imgSize.height - cropHeight; needBreakY = true; } for (int x = 0; x < imgSize.width; x += stepX) { bool needBreakX = false; if (x + cropWidth >= imgSize.width) { x = imgSize.width - cropWidth; needBreakX = true; } crops.emplace_back(x, y, cropWidth, cropHeight); if (needBreakX) break; } if (needBreakY) break; } return crops; } /// bool FillTypesMap(const std::vector<std::string>& classNames) { bool res = true; m_typesMap.resize(classNames.size(), bad_type); for (size_t i = 0; i < classNames.size(); ++i) { objtype_t type = TypeConverter::Str2Type(classNames[i]); m_typesMap[i] = type; res &= (type != bad_type); } return res; } /// objtype_t T2T(size_t typeInd) const { objtype_t res = (typeInd < m_typesMap.size()) ? m_typesMap[typeInd] : bad_type; return res; } private: std::vector<objtype_t> m_typesMap; };
BenchUtils.h
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <chrono> #include <vector> #ifdef _OPENMP #include <omp.h> #endif #include "AlignedVec.h" namespace fbgemm { template <typename T> void randFill(aligned_vector<T>& vec, T low, T high); void llc_flush(std::vector<char>& llc); int fbgemm_get_num_threads(); int fbgemm_get_thread_num(); /** * @params llc if not nullptr, flush llc */ template <class Fn> double measureWithWarmup( Fn&& fn, int warmupIterations, int measuredIterations, std::vector<char>* llc = nullptr, bool useOpenMP = false) { for (int i = 0; i < warmupIterations; ++i) { if (llc) { llc_flush(*llc); } fn(); } double ttot = 0.0; #ifdef _OPENMP #pragma omp parallel if (useOpenMP) #endif for (int i = 0; i < measuredIterations; ++i) { int thread_id = 0; std::chrono::time_point<std::chrono::high_resolution_clock> start, end; #ifdef _OPENMP if (useOpenMP) { thread_id = omp_get_thread_num(); } #endif if (llc && thread_id == 0) { llc_flush(*llc); } #ifdef _OPENMP if (useOpenMP) { #pragma omp barrier } #endif start = std::chrono::high_resolution_clock::now(); fn(); end = std::chrono::high_resolution_clock::now(); auto dur = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start); if (thread_id == 0) { // TODO: measure load imbalance ttot += dur.count(); } } return ttot / 1e9 / measuredIterations; } } // namespace fbgemm
movementPolicies.h
#pragma once #include <iostream> #include "timeHandler.h" #include "datatypes.h" #include "cxxopts.hpp" #include "operators.h" #include "locationTypesFormat.h" template<typename SimulationType> class NoMovement { public: // add program parameters if we need any, this function got called already // from Simulation static void addProgramParameters(cxxopts::Options& options) {} void initializeArgs(const cxxopts::ParseResult& result) {} void init(const parser::LocationTypes& data, unsigned cemeteryID) {} void planLocations(Timehandler simTime, unsigned timeStep) {} void movement(Timehandler simTime, unsigned timeStep) {} }; template<typename SimulationType> class DummyMovement { protected: thrust::device_vector<unsigned> stepsUntilMove; public: // add program parameters if we need any, this function got called already // from Simulation static void addProgramParameters(cxxopts::Options& options) {} void initializeArgs(const cxxopts::ParseResult& result) {} void init(const parser::LocationTypes& data, unsigned cemeteryID) {} void planLocations(Timehandler simTime, unsigned timeStep) { auto realThis = static_cast<SimulationType*>(this); thrust::device_vector<unsigned>& agentLocations = realThis->agents->location; unsigned numberOfAgents = agentLocations.size(); if (stepsUntilMove.size() == 0) stepsUntilMove.resize(numberOfAgents); thrust::fill(stepsUntilMove.begin(), stepsUntilMove.end(), 0u); } void movement(Timehandler simTime, unsigned timeStep) { // PROFILE_FUNCTION(); auto realThis = static_cast<SimulationType*>(this); thrust::device_vector<unsigned>& locationAgentList = realThis->locs->locationAgentList; thrust::device_vector<unsigned>& locationListOffsets = realThis->locs->locationListOffsets; thrust::device_vector<unsigned>& locationIdsOfAgents = realThis->locs->locationIdsOfAgents; thrust::device_vector<unsigned>& agentLocations = realThis->agents->location; unsigned numberOfAgents = agentLocations.size(); unsigned numberOfLocations = locationListOffsets.size() - 1; thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple(agentLocations.begin(), stepsUntilMove.begin())), thrust::make_zip_iterator(thrust::make_tuple(agentLocations.end(), stepsUntilMove.end())), [numberOfLocations] HD(thrust::tuple<unsigned&, unsigned&> tuple) { auto& location = thrust::get<0>(tuple); auto& stepsUntilMove = thrust::get<1>(tuple); if (stepsUntilMove == 0) { location = RandomGenerator::randomUnsigned(numberOfLocations); stepsUntilMove = RandomGenerator::randomUnsigned(144 / 4);// Move 4 times per day on average } stepsUntilMove--; }); Util::updatePerLocationAgentLists(agentLocations, locationIdsOfAgents, locationAgentList, locationListOffsets); } }; namespace RealMovementOps { [[nodiscard]] HD unsigned findActualLocationForType(unsigned agent, unsigned locType, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned homeType, unsigned schoolType, unsigned workType, int retry, bool* locationStatesPtr) { if (locType == homeType || locType == schoolType || locType == workType) { for (unsigned i = locationOffsetPtr[agent]; i < locationOffsetPtr[agent + 1]; i++) { if (locType == possibleTypesPtr[i]) return possibleLocationsPtr[i]; } return std::numeric_limits<unsigned>::max(); } // count number of possible locations unsigned counter = 0; unsigned pos = 0; for (unsigned i = locationOffsetPtr[agent]; i < locationOffsetPtr[agent + 1]; i++) { if (locType == possibleTypesPtr[i]) { if (counter == 0) pos = i; counter++; } } if (counter == 1) return possibleLocationsPtr[pos]; else if (counter > 1) { // Pick one at random unsigned counter2 = counter; unsigned randIdx = counter2; while (true) { while (randIdx == counter2) randIdx = RandomGenerator::randomUnsigned(counter); counter2 = 0; for (unsigned i = pos; i < locationOffsetPtr[agent + 1]; i++) { if (locType == possibleTypesPtr[i]) { if (counter2 == randIdx) { if (retry && locationStatesPtr[possibleLocationsPtr[i]] == false) { retry = 0; break; } else return possibleLocationsPtr[i]; } counter2++; } } } } return std::numeric_limits<unsigned>::max(); // printf("locType %d not found for agent %d - locationOffsets: // %d-%d\n", locType, agent, locationOffsetPtr[agent], // locationOffsetPtr[agent+1]); } template<typename PPState, typename AgentMeta, typename LocationType> struct MovementArguments { MovementArguments() : simTime(0u) {} unsigned* stepsUntilMovePtr; PPState* agentStatesPtr; AgentMeta* agentMetaDataPtr; unsigned* agentTypesPtr; bool* diagnosedPtr; bool* quarantinedPtr; AgentStats* agentStatsPtr; unsigned* eventOffsetPtr; AgentTypeList::Event* eventsPtr; unsigned* agentLocationsPtr; unsigned long* locationOffsetPtr; unsigned* possibleLocationsPtr; unsigned* possibleTypesPtr; bool* locationStatesPtr; bool* stayedHomePtr; unsigned* closedUntilPtr; unsigned* locationCapacitiesPtr; unsigned* locationQuarantineUntilPtr; unsigned quarantinePolicy; unsigned quarantineLength; Days day; unsigned hospitalType; unsigned homeType; unsigned publicPlaceType; unsigned doctorType; TimeDay simTime; unsigned timeStep; unsigned timestamp; unsigned tracked; unsigned cemeteryLoc; unsigned schoolType; unsigned classroomType; unsigned workType; LocationType* locationTypePtr; uint8_t* noWorkAgentPtr; uint8_t* essentialLocPtr; unsigned curfewBegin; unsigned curfewEnd; bool enableCurfew; unsigned schoolAgeRestriction; bool quarantineImmuneActive; bool lockdownNonvaccActive; }; template<typename PPState, typename AgentMeta, typename LocationType> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void quarantineAgent(unsigned i, MovementArguments<PPState, AgentMeta, LocationType>& a, unsigned until, bool quarantineImmuneActive) { if (a.quarantinePolicy == 0) return; if (a.agentStatsPtr[i].diagnosedTimestamp > 0 && a.agentStatesPtr[i].isInfected() == false && quarantineImmuneActive == false) return; if (a.agentStatsPtr[i].immunizationTimestamp > 0 && quarantineImmuneActive == false) return; a.quarantinedPtr[i] = true; a.agentStatsPtr[i].quarantinedTimestamp = a.timestamp; unsigned previousQuarantineUntil = a.agentStatsPtr[i].quarantinedUntilTimestamp; a.agentStatsPtr[i].quarantinedUntilTimestamp = until; a.agentStatsPtr[i].daysInQuarantine += (until - a.timestamp) / (24 * 60 / a.timeStep); // If agent was also diagnosed (is sick with COVID) if (a.diagnosedPtr[i]) { // Place home under quarantine unsigned myHome = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (a.quarantinePolicy > 1) {// Home under quarantine for 2 weeks from now a.locationQuarantineUntilPtr[myHome] = until;// TODO: quarantine period if (i == a.tracked) printf("\tFlagging home as quarantined: %d\n", myHome); // if (myHome==2149) printf("LOCATION 2149 quarantined until %d // because agent %d got // hospitalized\n",a.locationQuarantineUntilPtr[myHome],i); }// Place work/classroom under quarantine if (a.quarantinePolicy > 2 && previousQuarantineUntil < a.timestamp) { unsigned classroom = RealMovementOps::findActualLocationForType(i, a.classroomType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); unsigned work = RealMovementOps::findActualLocationForType(i, a.workType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); unsigned toClose[2] = { classroom, work }; for (unsigned loc : toClose) { if (loc != std::numeric_limits<unsigned>::max() && (a.locationTypePtr[loc] == a.workType || a.locationTypePtr[loc] == a.classroomType) // only quarantining work & classrooms //&& a.locationTypePtr[loc] != a.doctorType //&& a.locationTypePtr[loc] != a.hospitalType && a.locationQuarantineUntilPtr[loc] < a.timestamp && a.locationStatesPtr[loc] == true && a.closedUntilPtr[loc] < a.timestamp) { if (i == a.tracked) printf("\tFlagging work/classroom as quarantined: %d\n", loc); a.locationQuarantineUntilPtr[loc] = until;// TODO: quarantine period } } } } } template<typename PPState, typename AgentMeta, typename LocationType> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void checkLarger(unsigned i, MovementArguments<PPState, AgentMeta, LocationType>& a) { /* if (a.stepsUntilMovePtr[i] > a.simTime.getStepsUntilMidnight(a.timeStep)) { printf("WARN LARGER %d > %d\n", a.stepsUntilMovePtr[i], a.simTime.getStepsUntilMidnight(a.timeStep)); }*/ } template<typename PPState, typename AgentMeta, typename LocationType> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void doMovement(unsigned i, MovementArguments<PPState, AgentMeta, LocationType>& a) { unsigned& agentType = a.agentTypesPtr[i]; // if not dead or not in hospital (covid or non-covid) go home at curfew if (a.enableCurfew && a.curfewBegin == a.simTime.getMinutes() / a.timeStep) { states::WBStates wBState = a.agentStatesPtr[i].getWBState(); bool deadOrHospitalized = (wBState == states::WBStates::D || wBState == states::WBStates::S); bool hospitalizedWithNonCOVID = (a.agentStatsPtr[i].hospitalizedTimestamp <= a.timestamp && a.agentStatsPtr[i].hospitalizedUntilTimestamp > a.timestamp); if (!deadOrHospitalized && !hospitalizedWithNonCOVID) if (agentType + 1 == 7) {// afternoon shift worker // if currently at work, do nothing unsigned workplace = RealMovementOps::findActualLocationForType(i, a.workType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); // if not at workplace, move home, but allow movement later if (a.agentLocationsPtr[i] != workplace) a.agentLocationsPtr[i] = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); } else { a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); a.agentLocationsPtr[i] = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (a.tracked == i) printf("Agent %d day %d at %d:%d WBState %d moved to home %d due to curfew\n", i, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.agentLocationsPtr[i]); return; } } if (a.stepsUntilMovePtr[i] > 0) { a.stepsUntilMovePtr[i]--; return; } //Check if quarantine is over if (a.agentStatsPtr[i].quarantinedUntilTimestamp <= a.timestamp) { a.quarantinedPtr[i] = false; } states::WBStates wBState = a.agentStatesPtr[i].getWBState(); if (wBState == states::WBStates::D) {// If dead, do not go anywhere a.stepsUntilMovePtr[i] = std::numeric_limits<unsigned>::max(); a.agentLocationsPtr[i] = a.cemeteryLoc; return; } unsigned agentHome = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); // if non-COVID hospitalization, go to hospital if (a.agentStatsPtr[i].hospitalizedTimestamp <= a.timestamp && a.agentStatsPtr[i].hospitalizedUntilTimestamp > a.timestamp && wBState != states::WBStates::S && wBState != states::WBStates::D) { a.stepsUntilMovePtr[i] = MIN( a.agentStatsPtr[i].hospitalizedUntilTimestamp - a.timestamp - 1, a.simTime.getStepsUntilMidnight(a.timeStep)); a.agentLocationsPtr[i] = RealMovementOps::findActualLocationForType(i, a.hospitalType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (i == a.tracked) { printf( "Agent %d of type %d day %d at %d:%d WBState %d in hospital %d due to non-COVID hospitalization between " "%d-%d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.agentLocationsPtr[i], a.agentStatsPtr[i].hospitalizedTimestamp, a.agentStatsPtr[i].hospitalizedUntilTimestamp); } checkLarger(i, a); return; } if (wBState == states::WBStates::S) {// go to hospital if in serious condition a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); a.agentLocationsPtr[i] = RealMovementOps::findActualLocationForType(i, a.hospitalType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (i == a.tracked) { printf( "Agent %d of type %d day %d at %d:%d WBState %d in " "hospital %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.agentLocationsPtr[i]); } // If not diagnosed before, diagnose & quarantine if (!a.diagnosedPtr[i] && a.agentStatesPtr[i].isInfectious()) { a.diagnosedPtr[i] = true; a.agentStatsPtr[i].diagnosedTimestamp = a.timestamp; if (a.simTime.getStepsUntilMidnight(a.timeStep) == 24 * 60 / a.timeStep)// is it midnight, and agent got S // due to disease progression? a.agentStatsPtr[i].diagnosedTimestamp++;// shift timestamp by 1 to avoid // being counted as random test in // TestingPolicy RealMovementOps::quarantineAgent(i, a, a.timestamp + a.quarantineLength * 24 * 60 / a.timeStep, a.quarantineImmuneActive); } checkLarger(i, a); return; } // Is agent currently in a place under quarantine if (a.quarantinePolicy > 1 && a.timestamp < a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] && (a.locationTypePtr[a.agentLocationsPtr[i]] == a.homeType || a.locationTypePtr[a.agentLocationsPtr[i]] == a.schoolType// Only send agent to quarantine if this // is home, work or school || a.locationTypePtr[a.agentLocationsPtr[i]] == a.classroomType || a.locationTypePtr[a.agentLocationsPtr[i]] == a.workType)) { if (a.quarantinedPtr[i] == false) { if (i == a.tracked) printf( "Agent %d of type %d day %d at %d:%d location %d is " "quarantined, staying at home until %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, a.agentLocationsPtr[i], a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]]); RealMovementOps::quarantineAgent(i, a, a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]], a.quarantineImmuneActive); } // if now quarantined if (a.quarantinedPtr[i] == true) { a.stepsUntilMovePtr[i] = MIN(a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] - a.timestamp - 1, a.simTime.getStepsUntilMidnight(a.timeStep)); if (i == a.tracked) { printf( "Agent %d of type %d day %d at %d:%d WBState %d at " "location %d under quarantine (1), quarantined %d-%d " "locationQuarantineUntil %d timestamp %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.agentLocationsPtr[i], a.agentStatsPtr[i].quarantinedTimestamp, a.agentStatsPtr[i].quarantinedUntilTimestamp, a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]], a.timestamp); } // If not home, send home unsigned homeLocation = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (homeLocation != a.agentLocationsPtr[i]) { a.agentLocationsPtr[i] = homeLocation; // TODO: quarantine whole home?? // unsigned until = // a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]]; // a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] = until; } checkLarger(i, a); if (agentHome != std::numeric_limits<unsigned>::max() && a.agentLocationsPtr[i] != agentHome && a.stepsUntilMovePtr[i] > 60 / a.timeStep) a.stayedHomePtr[i] = false; return; } } // Should agent still be quarantined due to recent diagnosis if ((a.quarantinePolicy > 0 && (a.diagnosedPtr[i] || (a.agentStatsPtr[i].diagnosedTimestamp > 0 && (a.timestamp - a.agentStatsPtr[i].diagnosedTimestamp) < a.quarantineLength * 24 * 60 / a.timeStep)))// stay home if diagnosed or // quarantine has not // expired || (a.quarantinePolicy > 0 && a.quarantinedPtr[i])) { // Diagnosed, but not yet quarantined if (a.quarantinePolicy > 0 && !a.quarantinedPtr[i]) { RealMovementOps::quarantineAgent(i, a, a.timestamp + a.quarantineLength * 24 * 60 / a.timeStep, a.quarantineImmuneActive); if (i == a.tracked && a.quarantinedPtr[i]) { printf( "Agent %d of type %d day %d at %d:%d WBState %d was " "recently diagnosed, enforcing quarantine: diagnosed " "%d diagnosedTimestamp %d, current timestamp %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.diagnosedPtr[i], a.agentStatsPtr[i].diagnosedTimestamp, a.timestamp); } } if (a.quarantinedPtr[i]) { // Stay in quarantine at home a.agentLocationsPtr[i] = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); // if less than 2 weeks since diagnosis/quarantine, stay where agent // already is a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); if (i == a.tracked) { printf( "Agent %d of type %d day %d at %d:%d WBState %d still " "quarantined (2): diagnosed %d diagnosedTimestamp %d, " "personal quarantine until %d, current timestamp %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.diagnosedPtr[i], a.agentStatsPtr[i].diagnosedTimestamp, a.agentStatsPtr[i].quarantinedUntilTimestamp, a.timestamp); } checkLarger(i, a); if (agentHome != std::numeric_limits<unsigned>::max() && a.agentLocationsPtr[i] != agentHome && a.stepsUntilMovePtr[i] > 60 / a.timeStep) a.stayedHomePtr[i] = false; return; } } unsigned agentTypeOffset = AgentTypeList::getOffsetIndex(agentType, wBState, a.day); unsigned eventsBegin = a.eventOffsetPtr[agentTypeOffset]; unsigned eventsEnd = a.eventOffsetPtr[agentTypeOffset + 1]; int activeEventsBegin = -1; int activeEventsEnd = -1; // Here we assume if multiple events are given for the same timeslot, // they all start & end at the same time for (unsigned j = eventsBegin; j < eventsEnd; j++) { if (a.simTime >= a.eventsPtr[j].start && a.simTime < a.eventsPtr[j].end && activeEventsBegin == -1) activeEventsBegin = j; if (a.simTime < a.eventsPtr[j].start) { activeEventsEnd = j; break; } if (j == eventsEnd - 1) { if (a.simTime >= a.eventsPtr[j].start && a.simTime < a.eventsPtr[j].end) activeEventsEnd = eventsEnd; } } if (i == a.tracked) printf( "Agent %d of type %d day %d at %d:%d WBState %d activeEvents: " "%d-%d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, activeEventsBegin, activeEventsEnd); // Possibilities: // 1 both are -1 -> no more events for that day. Should be home if // wBState != S, or at hospital if S // 2 Begin != -1, End == -1 -> last event for the day. Move there (if needed pick randomly) // 3 Begin == -1, End != -1 -> no events right now, but there will be some later // 3a if less than 30 mins until next possible event, then stay // here 3b if 30-60 to next possible event, should go to public // place (type 0) 3c more than 60 mins, then go home // 4 neither -1, then pick randomly between one of the events // ISSUES: // do we forcibly finish at midnight?? What if the duration goes beyond // that? unsigned newLocationType = std::numeric_limits<unsigned>::max(); // Case 1 if (activeEventsBegin == -1 && activeEventsEnd == -1) { newLocationType = wBState == states::WBStates::S ? a.hospitalType : a.homeType;// Hostpital if sick, home otherwise unsigned myHome = RealMovementOps::findActualLocationForType(i, newLocationType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); a.agentLocationsPtr[i] = myHome; a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); checkLarger(i, a); if (i == a.tracked) printf( "\tCase 1- moving to locType %d location %d until midnight " "(for %d steps)\n", newLocationType, myHome, a.stepsUntilMovePtr[i] - 1); } // Case 2 and 4 if (activeEventsBegin != -1) { unsigned numPotentialEvents = (activeEventsEnd == -1 ? activeEventsBegin + 1 : activeEventsEnd) - activeEventsBegin; unsigned pickedEventIdx = 0; TimeDayDuration basicDuration(0.0); if (numPotentialEvents == 1) { newLocationType = a.eventsPtr[activeEventsBegin].locationType; basicDuration = a.eventsPtr[activeEventsBegin].duration; } else { double rand = RandomGenerator::randomReal(1.0); double threshhold = a.eventsPtr[activeEventsBegin].chance; unsigned idx = 0; while (rand > threshhold && idx < numPotentialEvents) { idx++; threshhold += a.eventsPtr[activeEventsBegin + idx].chance; } if (idx == numPotentialEvents) { /*printf("Error, overrun1: %g, agentType %d WB %d, day %d, time %d:%d\n",rand, agentType + 1, wBState, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60);*/ idx--; } pickedEventIdx = idx; newLocationType = a.eventsPtr[activeEventsBegin + idx].locationType; basicDuration = a.eventsPtr[activeEventsBegin + idx].duration; } // if agent has to stay home with children, then check to see if is work, and set it to home if (a.noWorkAgentPtr[i] != 0 && newLocationType == a.workType) { newLocationType = a.homeType; numPotentialEvents = 1; if (a.quarantinedPtr[i] == false) a.agentStatsPtr[i].daysInQuarantine++; if (i == a.tracked) printf("Agent %d not going to work because child at home\n", i); } unsigned newLocation = RealMovementOps::findActualLocationForType(i, newLocationType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, numPotentialEvents == 1, a.locationStatesPtr); // Check if location is open/closed. If closed, go home instead unsigned wasClosed = std::numeric_limits<unsigned>::max(); bool schoolAndTooOld = (newLocationType == a.schoolType || newLocationType == a.classroomType) && a.agentMetaDataPtr[i].getAge() >= a.schoolAgeRestriction; if (schoolAndTooOld //school is closed for student || ((a.locationStatesPtr[newLocation] == false || a.closedUntilPtr[newLocation] > a.timestamp) && newLocationType != a.workType) //or destination is closed and it's not agent's workplace || (a.lockdownNonvaccActive && a.agentStatsPtr[i].immunizationTimestamp==0)) //or non-immune should be locked down, and this is nonessential { // If closed, but there is another option to go to different type location, try that if (numPotentialEvents > 1) { double rand = RandomGenerator::randomReal(1.0); double threshhold = (pickedEventIdx == 0) ? 0.0 : a.eventsPtr[activeEventsBegin].chance / (1.0 - a.eventsPtr[activeEventsBegin + pickedEventIdx].chance); unsigned idx = 0; while (rand > threshhold && idx < numPotentialEvents) { idx++; threshhold += (pickedEventIdx == idx) ? 0.0 : a.eventsPtr[activeEventsBegin + idx].chance / (1.0 - a.eventsPtr[activeEventsBegin + pickedEventIdx].chance); } if (idx == numPotentialEvents) { idx--; } newLocationType = a.eventsPtr[activeEventsBegin + idx].locationType; basicDuration = a.eventsPtr[activeEventsBegin + idx].duration; newLocation = RealMovementOps::findActualLocationForType(i, newLocationType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); wasClosed = std::numeric_limits<unsigned>::max(); bool schoolAndTooOld2 = (newLocationType == a.schoolType || newLocationType == a.classroomType) && a.agentMetaDataPtr[i].getAge() >= a.schoolAgeRestriction; // is that closed too? if (schoolAndTooOld || ((a.locationStatesPtr[newLocation] == false || a.closedUntilPtr[newLocation] > a.timestamp) && newLocationType != a.workType) || (a.lockdownNonvaccActive && a.agentStatsPtr[i].immunizationTimestamp==0)) { wasClosed = newLocation; newLocation = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); } } else { wasClosed = newLocation; newLocation = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); } } else if (newLocationType == a.schoolType) { // if classroom closed, don't go to school either unsigned myClassroom = RealMovementOps::findActualLocationForType(i, a.classroomType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (myClassroom != std::numeric_limits<unsigned>::max() && a.closedUntilPtr[myClassroom] > a.timestamp) { wasClosed = newLocation; newLocation = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); } } a.agentLocationsPtr[i] = newLocation; if (basicDuration.getHours() > 24) { a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); } else if (activeEventsEnd == -1) { if ((a.simTime + basicDuration).isOverMidnight()) { a.stepsUntilMovePtr[i] = a.simTime.getStepsUntilMidnight(a.timeStep); } else { // does not last till midnight, but no events afterwards - // spend full duration there a.stepsUntilMovePtr[i] = basicDuration.steps(a.timeStep); } } else { // If duration is less then the beginning of the next move // window, then spend full duration here if (a.simTime + basicDuration < a.eventsPtr[activeEventsEnd].start) { a.stepsUntilMovePtr[i] = basicDuration.steps(a.timeStep); checkLarger(i, a); } else if (a.simTime + basicDuration > a.eventsPtr[activeEventsEnd].end) { a.stepsUntilMovePtr[i] = (a.eventsPtr[activeEventsEnd].end - a.simTime).steps(a.timeStep) - 1; checkLarger(i, a); } else { // Otherwise I need to move again randomly between the end // of this duration and the end of next movement window TimeDayDuration window = a.eventsPtr[activeEventsEnd].end - (a.simTime + basicDuration); unsigned st = window.steps(a.timeStep); unsigned randExtra = RandomGenerator::randomUnsigned(st); a.stepsUntilMovePtr[i] = basicDuration.steps(a.timeStep) + randExtra; checkLarger(i, a); } } if (agentType + 1 == 7 && a.enableCurfew && (a.curfewBegin <= a.simTime.getMinutes() / a.timeStep || a.curfewEnd > a.simTime.getMinutes() / a.timeStep)) { bool workButClosed = (newLocationType == a.workType && (a.locationStatesPtr[newLocation] == false || a.closedUntilPtr[newLocation] > a.timestamp)); if (workButClosed || (newLocationType != a.workType && newLocationType != a.homeType)) { a.agentLocationsPtr[i] = agentHome; if (i == a.tracked) { printf( "\tCase 2&4- Night shift worker tried moving to locType %d location %d, " "but it's curfew, moving home to %d for %d steps\n", newLocationType, newLocation, agentHome, a.stepsUntilMovePtr[i] - 1); } } } if (i == a.tracked) { if (wasClosed == std::numeric_limits<unsigned>::max()) printf( "\tCase 2&4- moving to locType %d location %d for %d " "steps\n", newLocationType, newLocation, a.stepsUntilMovePtr[i] - 1); else printf( "\tCase 2&4- tried moving to locType %d location %d, " "but was closed, moving home to %d for %d steps\n", newLocationType, wasClosed, newLocation, a.stepsUntilMovePtr[i] - 1); } } // Case 3 if (activeEventsBegin == -1 && activeEventsEnd != -1) { // Randomly decide when the move will occur in the next window: TimeDayDuration length = a.eventsPtr[activeEventsEnd].end - a.eventsPtr[activeEventsEnd].start; unsigned length_steps = length.steps(a.timeStep); unsigned randDelay = RandomGenerator::randomUnsigned(length_steps); a.stepsUntilMovePtr[i] = (a.eventsPtr[activeEventsEnd].start - a.simTime).steps(a.timeStep) + randDelay; unsigned timeLeft = a.stepsUntilMovePtr[i]; // Case 3.a -- less than 30 mins -> stay here if (timeLeft < TimeDayDuration(0.3).steps(a.timeStep)) { if (i == a.tracked) printf("\tCase 3a- staying in place for %d steps\n", a.stepsUntilMovePtr[i] - 1); // Do nothing - location stays the same } else if (timeLeft < TimeDayDuration(1.0).steps(a.timeStep)) { newLocationType = a.publicPlaceType; unsigned myPublicPlace = RealMovementOps::findActualLocationForType(i, a.publicPlaceType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); a.agentLocationsPtr[i] = myPublicPlace; if (i == a.tracked) printf( "\tCase 3b- moving to public Place type 1 location %d " "for %d steps\n", myPublicPlace, a.stepsUntilMovePtr[i] - 1); } else { newLocationType = a.homeType; unsigned myHome = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); a.agentLocationsPtr[i] = myHome; if (i == a.tracked) printf( "\tCase 3c- moving to home type 2 location %d for %d " "steps\n", myHome, a.stepsUntilMovePtr[i] - 1); } } // Has agent just gone someplace currently under quarantine if (a.quarantinePolicy > 1 && a.timestamp < a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] && (a.locationTypePtr[a.agentLocationsPtr[i]] == a.homeType || a.locationTypePtr[a.agentLocationsPtr[i]] == a.schoolType// Only send agent to quarantine if this // is home, work or school || a.locationTypePtr[a.agentLocationsPtr[i]] == a.classroomType || a.locationTypePtr[a.agentLocationsPtr[i]] == a.workType)) { // if not currently under quarantine if (!a.quarantinedPtr[i]) { RealMovementOps::quarantineAgent(i, a, a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]], a.quarantineImmuneActive); if (i == a.tracked && a.quarantinedPtr[i]) printf( "Agent %d of type %d day %d at %d:%d location %d is " "quarantined, staying at home until %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, a.agentLocationsPtr[i], a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]]); } if (a.quarantinedPtr[i]) { a.stepsUntilMovePtr[i] = MIN(a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] - a.timestamp - 1, a.simTime.getStepsUntilMidnight(a.timeStep)); checkLarger(i, a); if (i == a.tracked) { printf( "Agent %d of type %d day %d at %d:%d WBState %d at " "location %d under quarantine (1), quarantined %d-%d " "locationQuarantineUntil %d timestamp %d\n", i, agentType + 1, (int)a.day, a.simTime.getMinutes() / 60, a.simTime.getMinutes() % 60, (int)wBState, a.agentLocationsPtr[i], a.agentStatsPtr[i].quarantinedTimestamp, a.agentStatsPtr[i].quarantinedUntilTimestamp, a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]], a.timestamp); } // If not home, send home unsigned homeLocation = RealMovementOps::findActualLocationForType(i, a.homeType, a.locationOffsetPtr, a.possibleLocationsPtr, a.possibleTypesPtr, a.homeType, a.schoolType, a.workType, 0, nullptr); if (homeLocation != a.agentLocationsPtr[i]) { // unsigned until = // a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]]; a.agentLocationsPtr[i] = homeLocation; // TODO: quarantine whole home?? // a.locationQuarantineUntilPtr[a.agentLocationsPtr[i]] = until; } checkLarger(i, a); if (agentHome != std::numeric_limits<unsigned>::max() && a.agentLocationsPtr[i] != agentHome && a.stepsUntilMovePtr[i] > 60 / a.timeStep) a.stayedHomePtr[i] = false; return; } } // if (a.locationTypePtr[a.agentLocationsPtr[i]] == a.workType) { // printf("Agent %d of type %d moved to work type location %d at day %d %d:%d\n", // i, agentType+1, a.agentLocationsPtr[i], // (int)a.day, // a.simTime.getMinutes() / 60, // a.simTime.getMinutes() % 60); // }76030 // if (a.agentLocationsPtr[i] == 76030) { // printf("Agent %d of type %d moved to location %d type %d at day %d %d:%d\n", // i, agentType+1, a.agentLocationsPtr[i], // a.locationTypePtr[a.agentLocationsPtr[i]], // (int)a.day, // a.simTime.getMinutes() / 60, // a.simTime.getMinutes() % 60); // } // Diagnosis-related operations if (newLocationType == a.hospitalType || newLocationType == a.doctorType) { // If previously undiagnosed and if (!a.diagnosedPtr[i] && a.agentStatesPtr[i].isInfectious()) { a.diagnosedPtr[i] = true; a.agentStatsPtr[i].diagnosedTimestamp = a.timestamp; if (a.simTime.getStepsUntilMidnight(a.timeStep) == 24 * 60 / a.timeStep)// is it midnight, and agent got S // due to disease progression? a.agentStatsPtr[i].diagnosedTimestamp++;// shift timestamp by 1 to avoid // being counted as random test in // TestingPolicy if (i == a.tracked) printf("\tDiagnosed at location %d\n", a.agentLocationsPtr[i]); RealMovementOps::quarantineAgent(i, a, a.timestamp + a.quarantineLength * 24 * 60 / a.timeStep, a.quarantineImmuneActive);// TODO: quarantine period // We are not moving the agent - stay here for full duration, // potentially infect others when moving next, he will go into // quarantine anyway (if enabled) } } checkLarger(i, a); if (agentHome != std::numeric_limits<unsigned>::max() && a.agentLocationsPtr[i] != agentHome && a.stepsUntilMovePtr[i] > 60 / a.timeStep) { a.stayedHomePtr[i] = false; if (i == a.tracked) printf("\tdid not stay home %d %d\n", a.agentLocationsPtr[i], agentHome); } a.stepsUntilMovePtr[i]--; } #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA template<typename PPState, typename AgentMeta, typename LocationType> __global__ void doMovementDriver(unsigned numberOfAgents, MovementArguments<PPState, AgentMeta, LocationType> a) { unsigned i = threadIdx.x + blockIdx.x * blockDim.x; if (i < numberOfAgents) { RealMovementOps::doMovement(i, a); } } #endif template<typename AgentMeta> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void checkUnderageAtHome(unsigned i, unsigned* noWorkPtr, AgentMeta* agentMetaDataPtr, bool* quarantinedPtr, bool* locationStatesPtr, unsigned* closedUntilPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home, unsigned school, unsigned classroom, unsigned timestamp, unsigned schoolAgeRestriction) { if (agentMetaDataPtr[i].getAge() > 14) return;// Only underage if (quarantinedPtr[i]) { // If quarantined unsigned homeLocation = RealMovementOps::findActualLocationForType( i, home, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); if (homeLocation != std::numeric_limits<unsigned>::max()) noWorkPtr[homeLocation] = 1; } else { // Check if school open/closed unsigned schoolLocation = RealMovementOps::findActualLocationForType( i, school, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); unsigned classroomLocation = RealMovementOps::findActualLocationForType( i, classroom, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); bool schoolAndTooOld = agentMetaDataPtr[i].getAge() >= schoolAgeRestriction; if (schoolAndTooOld || (schoolLocation != std::numeric_limits<unsigned>::max() && (locationStatesPtr[schoolLocation] == false || closedUntilPtr[schoolLocation] > timestamp)) || (classroomLocation != std::numeric_limits<unsigned>::max() && (locationStatesPtr[classroomLocation] == false || closedUntilPtr[classroomLocation] > timestamp))) {// School closed unsigned homeLocation = RealMovementOps::findActualLocationForType( i, home, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); if (homeLocation != std::numeric_limits<unsigned>::max()) noWorkPtr[homeLocation] = 1; } } } #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA template<typename AgentMeta> __global__ void checkUnderageAtHomeDriver(unsigned numberOfAgents, unsigned* noWorkPtr, AgentMeta* agentMetaDataPtr, bool* quarantinedPtr, bool* locationStatesPtr, unsigned* closedUntilPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home, unsigned school, unsigned classroom, unsigned timestamp, unsigned schoolAgeRestriction) { unsigned i = threadIdx.x + blockIdx.x * blockDim.x; if (i < numberOfAgents) { RealMovementOps::checkUnderageAtHome(i, noWorkPtr, agentMetaDataPtr, quarantinedPtr, locationStatesPtr, closedUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, timestamp, schoolAgeRestriction); } } #endif template<typename AgentMeta> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void setNoWorkToday(unsigned i, unsigned* noWorkLocPtr, uint8_t* noWorkAgentPtr, AgentMeta* agentMetaDataPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home) { if (agentMetaDataPtr[i].getAge() > 26 && agentMetaDataPtr[i].getAge() < 65) { unsigned homeLocation = RealMovementOps::findActualLocationForType( i, home, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, home, home, 0, nullptr); if (homeLocation != std::numeric_limits<unsigned>::max()) if (noWorkLocPtr[homeLocation] == 1) {// TODO this is not exactly thread safe on the CPU.... #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA if (atomicAdd(&noWorkLocPtr[homeLocation], 1) == 1) #else noWorkLocPtr[homeLocation] = 2; #endif noWorkAgentPtr[i] = 1; } } } #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA template<typename AgentMeta> __global__ void setNoWorkTodayDriver(unsigned numberOfAgents, unsigned* noWorkLocPtr, uint8_t* noWorkAgentPtr, AgentMeta* agentMetaDataPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home) { unsigned i = threadIdx.x + blockIdx.x * blockDim.x; if (i < numberOfAgents) { RealMovementOps::setNoWorkToday(i, noWorkLocPtr, noWorkAgentPtr, agentMetaDataPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home); } } #endif template<typename PPValues> #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void checkSchoolWorkQuarantine(unsigned i, AgentStats* agentStatsPtr, PPValues* agentStatesPtr, bool* quarantinedPtr, unsigned* locationQuarantineUntilPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home, unsigned work, unsigned school, unsigned classroom, unsigned timestamp, unsigned timeStep, unsigned tracked) { // If already quarantined, do nothing if (quarantinedPtr[i]) return; // If immune, do nothing if (agentStatsPtr[i].diagnosedTimestamp > 0 && agentStatesPtr[i].isInfected() == false) return; // Get work/school/classroom ID unsigned workLocation = RealMovementOps::findActualLocationForType( i, work, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); unsigned schoolLocation = RealMovementOps::findActualLocationForType( i, school, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); unsigned classroomLocation = RealMovementOps::findActualLocationForType( i, classroom, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, 0, nullptr); // Check if school/classroom/work quarantined unsigned until = 0; if (schoolLocation != std::numeric_limits<unsigned>::max() && locationQuarantineUntilPtr[schoolLocation] > timestamp) until = locationQuarantineUntilPtr[schoolLocation]; else if (classroomLocation != std::numeric_limits<unsigned>::max() && locationQuarantineUntilPtr[classroomLocation] > timestamp) until = locationQuarantineUntilPtr[classroomLocation]; else if (workLocation != std::numeric_limits<unsigned>::max() && locationQuarantineUntilPtr[workLocation] > timestamp) until = locationQuarantineUntilPtr[workLocation]; // If so, quarantine agent if (until > 0) { quarantinedPtr[i] = true; agentStatsPtr[i].quarantinedTimestamp = timestamp; agentStatsPtr[i].quarantinedUntilTimestamp = until; agentStatsPtr[i].daysInQuarantine += (until - timestamp) / (24 * 60 / timeStep); if (i == tracked) { printf( "Agent %d at %d: " "school/class/work under quarantine, going to quarantine until %d ", i, timestamp, agentStatsPtr[i].quarantinedUntilTimestamp); } } } #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA template<typename PPValues> __global__ void checkSchoolWorkQuarantineDriver(unsigned numberOfAgents, AgentStats* agentStatsPtr, PPValues* agentStatesPtr, bool* quarantinedPtr, unsigned* locationQuarantineUntilPtr, unsigned long* locationOffsetPtr, unsigned* possibleLocationsPtr, unsigned* possibleTypesPtr, unsigned home, unsigned work, unsigned school, unsigned classroom, unsigned timestamp, unsigned timeStep, unsigned tracked) { unsigned i = threadIdx.x + blockIdx.x * blockDim.x; if (i < numberOfAgents) { RealMovementOps::checkSchoolWorkQuarantine(i, agentStatsPtr, agentStatesPtr, quarantinedPtr, locationQuarantineUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, work, school, classroom, timestamp, timeStep, tracked); } } #endif #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __device__ #endif void checkSchoolQuarantine(unsigned i, unsigned* schoolsPtr, unsigned* classroomsPtr, unsigned* classroomOffsetsPtr, unsigned* locationQuarantineUntilPtr, unsigned timestamp) { unsigned schoolIdx = schoolsPtr[i]; if (locationQuarantineUntilPtr[schoolIdx] > timestamp) return; unsigned counter = 0; unsigned max = 0; for (unsigned classOffset = classroomOffsetsPtr[i]; classOffset < classroomOffsetsPtr[i + 1]; classOffset++) { unsigned classIdx = classroomsPtr[classOffset]; if (locationQuarantineUntilPtr[classIdx] > timestamp) { counter++; max = max > locationQuarantineUntilPtr[classIdx] ? max : locationQuarantineUntilPtr[classIdx]; } } if (counter > 1) { // printf("School %d has %d quarantined classes, quarantining entire school until %d\n", schoolIdx, counter, max); locationQuarantineUntilPtr[schoolIdx] = max; for (unsigned classOffset = classroomOffsetsPtr[i]; classOffset < classroomOffsetsPtr[i + 1]; classOffset++) { unsigned classIdx = classroomsPtr[classOffset]; locationQuarantineUntilPtr[classIdx] = max; } } } #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA __global__ void checkSchoolQuarantineDriver(unsigned numSchools, unsigned* schoolsPtr, unsigned* classroomsPtr, unsigned* classroomOffsetsPtr, unsigned* locationQuarantineUntilPtr, unsigned timestamp) { unsigned i = threadIdx.x + blockIdx.x * blockDim.x; if (i < numSchools) { RealMovementOps::checkSchoolQuarantine( i, schoolsPtr, classroomsPtr, classroomOffsetsPtr, locationQuarantineUntilPtr, timestamp); } } #endif }// namespace RealMovementOps template<typename SimulationType> class RealMovement { thrust::device_vector<unsigned> stepsUntilMove; thrust::device_vector<unsigned> noWorkLoc;// indicating children at home thrust::device_vector<uint8_t> noWorkAgent;// indicating agent staying home because children at home unsigned publicSpace; unsigned home; unsigned hospital; unsigned cemeteryLoc; unsigned doctor; unsigned tracked; unsigned quarantineLength; unsigned school; unsigned classroom; unsigned work; std::string dumpLocationAgentList; public: bool enableCurfew = false; unsigned curfewBegin = 0; unsigned curfewEnd = 0; bool curfewTimeConverted = false; unsigned schoolAgeRestriction = 99; bool holidayModeActive = false; bool quarantineImmuneActive = false; bool lockdownNonvaccActive = false; unsigned quarantinePolicy; // add program parameters if we need any, this function got called already // from Simulation static void addProgramParameters(cxxopts::Options& options) { options.add_options()("trace", "Trace movements of agent", cxxopts::value<unsigned>()->default_value(std::to_string(std::numeric_limits<unsigned>::max())))("quarantinePolicy", "Quarantine policy: 0 - None, 1 - Agent only, 2 - Agent and " "household, 3 - + classroom/work, 4 - + school", cxxopts::value<unsigned>()->default_value(std::to_string(unsigned(3))))("quarantineLength", "Length of quarantine in days", cxxopts::value<unsigned>()->default_value(std::to_string(unsigned(10)))) ("dumpLocationAgentList", "Dump per-location list of agents at each iteration", cxxopts::value<std::string>()->default_value("")); } void initializeArgs(const cxxopts::ParseResult& result) { tracked = result["trace"].as<unsigned>(); quarantinePolicy = result["quarantinePolicy"].as<unsigned>(); quarantineLength = result["quarantineLength"].as<unsigned>(); dumpLocationAgentList = result["dumpLocationAgentList"].as<std::string>(); } void init(const parser::LocationTypes& data, unsigned cemeteryID) { publicSpace = data.publicSpace; home = data.home; hospital = data.hospital; cemeteryLoc = cemeteryID; doctor = data.doctor; school = data.school; work = data.work; classroom = data.classroom; } void planLocations(Timehandler simTime, unsigned timeStep) { // PROFILE_FUNCTION(); auto realThis = static_cast<SimulationType*>(this); thrust::device_vector<unsigned>& agentLocations = realThis->agents->location; unsigned numberOfAgents = agentLocations.size(); unsigned numberOfLocations = realThis->locs->locationListOffsets.size() - 1; unsigned timestamp = simTime.getTimestamp(); if (stepsUntilMove.size() == 0) { stepsUntilMove.resize(numberOfAgents); noWorkLoc.resize(numberOfLocations); noWorkAgent.resize(numberOfAgents); } if (curfewTimeConverted == false) { curfewBegin = curfewBegin / timeStep; curfewEnd = curfewEnd / timeStep; curfewTimeConverted = true; } // If curfew, noone moves before curfew ends thrust::fill(stepsUntilMove.begin(), stepsUntilMove.end(), curfewEnd); thrust::fill(realThis->agents->stayedHome.begin(), realThis->agents->stayedHome.end(), true); // For each agent that is under 14 years, check if quarantined or school closed, if so flag home as noWork thrust::fill(noWorkLoc.begin(), noWorkLoc.end(), (uint8_t)0u); thrust::fill(noWorkAgent.begin(), noWorkAgent.end(), (uint8_t)0u); unsigned* noWorkLocPtr = thrust::raw_pointer_cast(noWorkLoc.data()); uint8_t* noWorkAgentPtr = thrust::raw_pointer_cast(noWorkAgent.data()); thrust::device_vector<typename SimulationType::AgentMeta_t>& agentMetaData = realThis->agents->agentMetaData; typename SimulationType::AgentMeta_t* agentMetaDataPtr = thrust::raw_pointer_cast(agentMetaData.data()); thrust::device_vector<bool>& quarantined = realThis->agents->quarantined; bool* quarantinedPtr = thrust::raw_pointer_cast(quarantined.data()); thrust::device_vector<bool>& locationStates = realThis->locs->states; bool* locationStatesPtr = thrust::raw_pointer_cast(locationStates.data()); thrust::device_vector<unsigned>& closedUntil = realThis->locs->closedUntil; unsigned* closedUntilPtr = thrust::raw_pointer_cast(closedUntil.data()); thrust::device_vector<unsigned long>& locationOffset = realThis->agents->locationOffset; unsigned long* locationOffsetPtr = thrust::raw_pointer_cast(locationOffset.data()); thrust::device_vector<unsigned>& possibleLocations = realThis->agents->possibleLocations; unsigned* possibleLocationsPtr = thrust::raw_pointer_cast(possibleLocations.data()); thrust::device_vector<unsigned>& possibleTypes = realThis->agents->possibleTypes; unsigned* possibleTypesPtr = thrust::raw_pointer_cast(possibleTypes.data()); thrust::device_vector<typename SimulationType::PPState_t>& agentStates = realThis->agents->PPValues; typename SimulationType::PPState_t* agentStatesPtr = thrust::raw_pointer_cast(agentStates.data()); thrust::device_vector<AgentStats>& agentStats = realThis->agents->agentStats; AgentStats* agentStatsPtr = thrust::raw_pointer_cast(agentStats.data()); thrust::device_vector<typename SimulationType::TypeOfLocation_t>& locationTypes = realThis->locs->locType; thrust::device_vector<unsigned>& locationQuarantineUntil = realThis->locs->quarantineUntil; unsigned* locationQuarantineUntilPtr = thrust::raw_pointer_cast(locationQuarantineUntil.data()); // if quarantinePolicy >3, check if more than 1 classrrom in a school is quarantined, if so, quarantine the schooland // all classrooms if (quarantinePolicy > 3) { thrust::device_vector<unsigned>& schools = realThis->locs->schools; unsigned* schoolsPtr = thrust::raw_pointer_cast(schools.data()); thrust::device_vector<unsigned>& classrooms = realThis->locs->classrooms; unsigned* classroomsPtr = thrust::raw_pointer_cast(classrooms.data()); thrust::device_vector<unsigned>& classroomOffsets = realThis->locs->classroomOffsets; unsigned* classroomOffsetsPtr = thrust::raw_pointer_cast(classroomOffsets.data()); unsigned numSchools = schools.size(); #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_OMP #pragma omp parallel for for (unsigned i = 0; i < numSchools; i++) { RealMovementOps::checkSchoolQuarantine( i, schoolsPtr, classroomsPtr, classroomOffsetsPtr, locationQuarantineUntilPtr, timestamp); } #elif THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA RealMovementOps::checkSchoolQuarantineDriver<<<(numSchools - 1) / 256 + 1, 256>>>( numSchools, schoolsPtr, classroomsPtr, classroomOffsetsPtr, locationQuarantineUntilPtr, timestamp); cudaDeviceSynchronize(); #endif } // put all workers of quarantined workpalces into quarantine, and clear workplace quarantine // put all attendees of quarantined classroom into quarantine, clear classroom quarantine, close classroom if (quarantinePolicy > 2) { #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_OMP #pragma omp parallel for for (unsigned i = 0; i < numberOfAgents; i++) { RealMovementOps::checkSchoolWorkQuarantine(i, agentStatsPtr, agentStatesPtr, quarantinedPtr, locationQuarantineUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, work, school, classroom, timestamp, timeStep, tracked); } #elif THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA RealMovementOps::checkSchoolWorkQuarantineDriver<<<(numberOfAgents - 1) / 256 + 1, 256>>>(numberOfAgents, agentStatsPtr, agentStatesPtr, quarantinedPtr, locationQuarantineUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, work, school, classroom, timestamp, timeStep, tracked); cudaDeviceSynchronize(); #endif unsigned schoolType = school; unsigned classroomType = classroom; unsigned workType = work; // Clear quarantine flags, set closedUntil instead for schools/classrooms thrust::for_each(thrust::make_zip_iterator(thrust::make_tuple( closedUntil.begin(), locationQuarantineUntil.begin(), locationTypes.begin())), thrust::make_zip_iterator( thrust::make_tuple(closedUntil.end(), locationQuarantineUntil.end(), locationTypes.end())), [schoolType, classroomType, workType, timestamp] HD( thrust::tuple<unsigned&, unsigned&, typename SimulationType::TypeOfLocation_t&> tup) { if (thrust::get<1>(tup) > timestamp && (thrust::get<2>(tup) == schoolType || thrust::get<2>(tup) == classroomType)) { thrust::get<0>(tup) = thrust::get<1>(tup); thrust::get<1>(tup) = 0; } else if (thrust::get<1>(tup) > timestamp && thrust::get<2>(tup) == workType) { thrust::get<1>(tup) = 0; } }); } // Check if minors are alone at home, flag home #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_OMP #pragma omp parallel for for (unsigned i = 0; i < numberOfAgents; i++) { RealMovementOps::checkUnderageAtHome(i, noWorkLocPtr, agentMetaDataPtr, quarantinedPtr, locationStatesPtr, closedUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, timestamp, schoolAgeRestriction); } #elif THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA RealMovementOps::checkUnderageAtHomeDriver<<<(numberOfAgents - 1) / 256 + 1, 256>>>(numberOfAgents, noWorkLocPtr, agentMetaDataPtr, quarantinedPtr, locationStatesPtr, closedUntilPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home, school, classroom, timestamp, schoolAgeRestriction); cudaDeviceSynchronize(); #endif // For each adult working agent (25-65), if home is flagged, at least one adult is flagged as not working that day #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_OMP #pragma omp parallel for for (unsigned i = 0; i < numberOfAgents; i++) { RealMovementOps::setNoWorkToday(i, noWorkLocPtr, noWorkAgentPtr, agentMetaDataPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home); } #elif THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA RealMovementOps::setNoWorkTodayDriver<<<(numberOfAgents - 1) / 256 + 1, 256>>>(numberOfAgents, noWorkLocPtr, noWorkAgentPtr, agentMetaDataPtr, locationOffsetPtr, possibleLocationsPtr, possibleTypesPtr, home); cudaDeviceSynchronize(); #endif } void movement(Timehandler simTime, unsigned timeStep) { // PROFILE_FUNCTION(); auto realThis = static_cast<SimulationType*>(this); RealMovementOps::MovementArguments<typename SimulationType::PPState_t, typename SimulationType::AgentMeta_t, typename SimulationType::TypeOfLocation_t> a; a.quarantinePolicy = quarantinePolicy; a.quarantineLength = quarantineLength; a.tracked = this->tracked; a.hospitalType = hospital; a.homeType = home; a.publicPlaceType = publicSpace; a.doctorType = doctor; a.timeStep = timeStep; a.simTime = TimeDay(simTime); a.cemeteryLoc = cemeteryLoc; a.schoolType = school; a.classroomType = classroom; a.workType = work; a.enableCurfew = enableCurfew; a.curfewBegin = curfewBegin; a.curfewEnd = curfewEnd; a.schoolAgeRestriction = schoolAgeRestriction; a.quarantineImmuneActive = quarantineImmuneActive; a.lockdownNonvaccActive = lockdownNonvaccActive; // Location-based data thrust::device_vector<unsigned>& locationAgentList = realThis->locs->locationAgentList; unsigned* locationAgentListPtr = thrust::raw_pointer_cast(locationAgentList.data()); thrust::device_vector<unsigned>& locationListOffsets = realThis->locs->locationListOffsets; unsigned* locationListOffsetsPtr = thrust::raw_pointer_cast(locationListOffsets.data()); thrust::device_vector<unsigned>& locationIdsOfAgents = realThis->locs->locationIdsOfAgents; unsigned* locationIdsOfAgentsPtr = thrust::raw_pointer_cast(locationIdsOfAgents.data()); thrust::device_vector<bool>& locationStates = realThis->locs->states; a.locationStatesPtr = thrust::raw_pointer_cast(locationStates.data()); thrust::device_vector<unsigned>& closedUntil = realThis->locs->closedUntil; a.closedUntilPtr = thrust::raw_pointer_cast(closedUntil.data()); thrust::device_vector<unsigned>& locationCapacities = realThis->locs->capacity; a.locationCapacitiesPtr = thrust::raw_pointer_cast(locationCapacities.data()); thrust::device_vector<unsigned>& locationQuarantineUntil = realThis->locs->quarantineUntil; a.locationQuarantineUntilPtr = thrust::raw_pointer_cast(locationQuarantineUntil.data()); thrust::device_vector<typename SimulationType::TypeOfLocation_t>& locationTypes = realThis->locs->locType; a.locationTypePtr = thrust::raw_pointer_cast(locationTypes.data()); a.essentialLocPtr = thrust::raw_pointer_cast(realThis->locs->essential.data()); // Agent-based data thrust::device_vector<unsigned>& agentLocations = realThis->agents->location; a.agentLocationsPtr = thrust::raw_pointer_cast(agentLocations.data()); thrust::device_vector<unsigned>& agentTypes = realThis->agents->types; a.agentTypesPtr = thrust::raw_pointer_cast(agentTypes.data()); thrust::device_vector<typename SimulationType::PPState_t>& agentStates = realThis->agents->PPValues; a.agentStatesPtr = thrust::raw_pointer_cast(agentStates.data()); thrust::device_vector<typename SimulationType::AgentMeta_t>& agentMetaData = realThis->agents->agentMetaData; a.agentMetaDataPtr = thrust::raw_pointer_cast(agentMetaData.data()); thrust::device_vector<bool>& diagnosed = realThis->agents->diagnosed; a.diagnosedPtr = thrust::raw_pointer_cast(diagnosed.data()); thrust::device_vector<bool>& stayedHome = realThis->agents->stayedHome; a.stayedHomePtr = thrust::raw_pointer_cast(stayedHome.data()); thrust::device_vector<bool>& quarantined = realThis->agents->quarantined; a.quarantinedPtr = thrust::raw_pointer_cast(quarantined.data()); thrust::device_vector<AgentStats>& agentStats = realThis->agents->agentStats; a.agentStatsPtr = thrust::raw_pointer_cast(agentStats.data()); a.stepsUntilMovePtr = thrust::raw_pointer_cast(this->stepsUntilMove.data()); a.noWorkAgentPtr = thrust::raw_pointer_cast(noWorkAgent.data()); // Arrays storing actual location IDs for each agent, for each location // type thrust::device_vector<unsigned long>& locationOffset = realThis->agents->locationOffset; a.locationOffsetPtr = thrust::raw_pointer_cast(locationOffset.data()); thrust::device_vector<unsigned>& possibleLocations = realThis->agents->possibleLocations; a.possibleLocationsPtr = thrust::raw_pointer_cast(possibleLocations.data()); thrust::device_vector<unsigned>& possibleTypes = realThis->agents->possibleTypes; a.possibleTypesPtr = thrust::raw_pointer_cast(possibleTypes.data()); // Arrays storing movement behaviour with general locationTypes - for // each agent type, WB state, and day thrust::device_vector<unsigned>& eventOffset = realThis->agents->agentTypes.eventOffset; a.eventOffsetPtr = thrust::raw_pointer_cast(eventOffset.data()); thrust::device_vector<AgentTypeList::Event>& events = realThis->agents->agentTypes.events; a.eventsPtr = thrust::raw_pointer_cast(events.data()); unsigned numberOfAgents = agentLocations.size(); unsigned numberOfLocations = locationListOffsets.size() - 1; a.day = simTime.getDay(); if (holidayModeActive) { a.day = Days::SUNDAY; } a.timestamp = simTime.getTimestamp(); #if THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_OMP #pragma omp parallel for for (unsigned i = 0; i < numberOfAgents; i++) { RealMovementOps::doMovement(i, a); } #elif THRUST_DEVICE_SYSTEM == THRUST_DEVICE_SYSTEM_CUDA RealMovementOps::doMovementDriver<<<(numberOfAgents - 1) / 256 + 1, 256>>>(numberOfAgents, a); cudaDeviceSynchronize(); #endif Util::updatePerLocationAgentLists(agentLocations, locationIdsOfAgents, locationAgentList, locationListOffsets); if (dumpLocationAgentList.length()>0) { std::ofstream file; file.open(dumpLocationAgentList + "/locationList"+std::to_string(a.timestamp)+".txt"); file << locationListOffsets.size()-1 << "\n"; thrust::copy(locationListOffsets.begin(), locationListOffsets.end(), std::ostream_iterator<unsigned>(file, " ")); file << "\n"; thrust::copy(locationAgentList.begin(), locationAgentList.end(), std::ostream_iterator<unsigned>(file, " ")); file << "\n"; file.close(); } } };
common.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_UTILS_COMMON_H_ #define LIGHTGBM_UTILS_COMMON_H_ #if ((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__))) #include <LightGBM/utils/common_legacy_solaris.h> #endif #include <LightGBM/utils/json11.h> #include <LightGBM/utils/log.h> #include <LightGBM/utils/openmp_wrapper.h> #include <limits> #include <string> #include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <iomanip> #include <iterator> #include <map> #include <memory> #include <sstream> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #if (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) #define FMT_HEADER_ONLY #include "../../../external_libs/fmt/include/fmt/format.h" #endif #include "../../../external_libs/fast_double_parser/include/fast_double_parser.h" #ifdef _MSC_VER #include <intrin.h> #pragma intrinsic(_BitScanReverse) #endif #if defined(_MSC_VER) #include <malloc.h> #elif MM_MALLOC #include <mm_malloc.h> // https://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html // https://www.oreilly.com/library/view/mac-os-x/0596003560/ch05s01s02.html #elif defined(__GNUC__) && defined(HAVE_MALLOC_H) #include <malloc.h> #define _mm_malloc(a, b) memalign(b, a) #define _mm_free(a) free(a) #else #include <stdlib.h> #define _mm_malloc(a, b) malloc(a) #define _mm_free(a) free(a) #endif namespace LightGBM { namespace Common { using json11::Json; /*! * Imbues the stream with the C locale. */ static void C_stringstream(std::stringstream &ss) { ss.imbue(std::locale::classic()); } inline static char tolower(char in) { if (in <= 'Z' && in >= 'A') return in - ('Z' - 'z'); return in; } inline static std::string Trim(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of(" \f\n\r\t\v") + 1); str.erase(0, str.find_first_not_of(" \f\n\r\t\v")); return str; } inline static std::string RemoveQuotationSymbol(std::string str) { if (str.empty()) { return str; } str.erase(str.find_last_not_of("'\"") + 1); str.erase(0, str.find_first_not_of("'\"")); return str; } inline static bool StartsWith(const std::string& str, const std::string prefix) { if (str.substr(0, prefix.size()) == prefix) { return true; } else { return false; } } inline static std::vector<std::string> Split(const char* c_str, char delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == delimiter) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> SplitBrackets(const char* c_str, char left_delimiter, char right_delimiter) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; bool open = false; while (pos < str.length()) { if (str[pos] == left_delimiter) { open = true; ++pos; i = pos; } else if (str[pos] == right_delimiter && open) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } open = false; ++pos; } else { ++pos; } } return ret; } inline static std::vector<std::string> SplitLines(const char* c_str) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { if (str[pos] == '\n' || str[pos] == '\r') { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } // skip the line endings while (str[pos] == '\n' || str[pos] == '\r') ++pos; // new begin i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::vector<std::string> Split(const char* c_str, const char* delimiters) { std::vector<std::string> ret; std::string str(c_str); size_t i = 0; size_t pos = 0; while (pos < str.length()) { bool met_delimiters = false; for (int j = 0; delimiters[j] != '\0'; ++j) { if (str[pos] == delimiters[j]) { met_delimiters = true; break; } } if (met_delimiters) { if (i < pos) { ret.push_back(str.substr(i, pos - i)); } ++pos; i = pos; } else { ++pos; } } if (i < pos) { ret.push_back(str.substr(i)); } return ret; } inline static std::string GetFromParserConfig(std::string config_str, std::string key) { // parser config should follow json format. std::string err; Json config_json = Json::parse(config_str, &err); if (!err.empty()) { Log::Fatal("Invalid parser config: %s. Please check if follow json format.", err.c_str()); } return config_json[key].string_value(); } inline static std::string SaveToParserConfig(std::string config_str, std::string key, std::string value) { std::string err; Json config_json = Json::parse(config_str, &err); if (!err.empty()) { Log::Fatal("Invalid parser config: %s. Please check if follow json format.", err.c_str()); } CHECK(config_json.is_object()); std::map<std::string, Json> config_map = config_json.object_items(); config_map.insert(std::pair<std::string, Json>(key, Json(value))); return Json(config_map).dump(); } template<typename T> inline static const char* Atoi(const char* p, T* out) { int sign; T value; while (*p == ' ') { ++p; } sign = 1; if (*p == '-') { sign = -1; ++p; } else if (*p == '+') { ++p; } for (value = 0; *p >= '0' && *p <= '9'; ++p) { value = value * 10 + (*p - '0'); } *out = static_cast<T>(sign * value); while (*p == ' ') { ++p; } return p; } template<typename T> inline static double Pow(T base, int power) { if (power < 0) { return 1.0 / Pow(base, -power); } else if (power == 0) { return 1; } else if (power % 2 == 0) { return Pow(base*base, power / 2); } else if (power % 3 == 0) { return Pow(base*base*base, power / 3); } else { return base * Pow(base, power - 1); } } inline static const char* Atof(const char* p, double* out) { int frac; double sign, value, scale; *out = NAN; // Skip leading white space, if any. while (*p == ' ') { ++p; } // Get sign, if any. sign = 1.0; if (*p == '-') { sign = -1.0; ++p; } else if (*p == '+') { ++p; } // is a number if ((*p >= '0' && *p <= '9') || *p == '.' || *p == 'e' || *p == 'E') { // Get digits before decimal point or exponent, if any. for (value = 0.0; *p >= '0' && *p <= '9'; ++p) { value = value * 10.0 + (*p - '0'); } // Get digits after decimal point, if any. if (*p == '.') { double right = 0.0; int nn = 0; ++p; while (*p >= '0' && *p <= '9') { right = (*p - '0') + right * 10.0; ++nn; ++p; } value += right / Pow(10.0, nn); } // Handle exponent, if any. frac = 0; scale = 1.0; if ((*p == 'e') || (*p == 'E')) { uint32_t expon; // Get sign of exponent, if any. ++p; if (*p == '-') { frac = 1; ++p; } else if (*p == '+') { ++p; } // Get digits of exponent, if any. for (expon = 0; *p >= '0' && *p <= '9'; ++p) { expon = expon * 10 + (*p - '0'); } if (expon > 308) expon = 308; // Calculate scaling factor. while (expon >= 50) { scale *= 1E50; expon -= 50; } while (expon >= 8) { scale *= 1E8; expon -= 8; } while (expon > 0) { scale *= 10.0; expon -= 1; } } // Return signed and scaled floating point result. *out = sign * (frac ? (value / scale) : (value * scale)); } else { size_t cnt = 0; while (*(p + cnt) != '\0' && *(p + cnt) != ' ' && *(p + cnt) != '\t' && *(p + cnt) != ',' && *(p + cnt) != '\n' && *(p + cnt) != '\r' && *(p + cnt) != ':') { ++cnt; } if (cnt > 0) { std::string tmp_str(p, cnt); std::transform(tmp_str.begin(), tmp_str.end(), tmp_str.begin(), Common::tolower); if (tmp_str == std::string("na") || tmp_str == std::string("nan") || tmp_str == std::string("null")) { *out = NAN; } else if (tmp_str == std::string("inf") || tmp_str == std::string("infinity")) { *out = sign * 1e308; } else { Log::Fatal("Unknown token %s in data file", tmp_str.c_str()); } p += cnt; } } while (*p == ' ') { ++p; } return p; } // Use fast_double_parse and strtod (if parse failed) to parse double. inline static const char* AtofPrecise(const char* p, double* out) { const char* end = fast_double_parser::parse_number(p, out); if (end != nullptr) { return end; } // Rare path: Not in RFC 7159 format. Possible "inf", "nan", etc. Fallback to standard library: char* end2; errno = 0; // This is Required before calling strtod. *out = std::strtod(p, &end2); // strtod is locale aware. if (end2 == p) { Log::Fatal("no conversion to double for: %s", p); } if (errno == ERANGE) { Log::Warning("convert to double got underflow or overflow: %s", p); } return end2; } inline static bool AtoiAndCheck(const char* p, int* out) { const char* after = Atoi(p, out); if (*after != '\0') { return false; } return true; } inline static bool AtofAndCheck(const char* p, double* out) { const char* after = Atof(p, out); if (*after != '\0') { return false; } return true; } inline static const char* SkipSpaceAndTab(const char* p) { while (*p == ' ' || *p == '\t') { ++p; } return p; } inline static const char* SkipReturn(const char* p) { while (*p == '\n' || *p == '\r' || *p == ' ') { ++p; } return p; } template<typename T, typename T2> inline static std::vector<T2> ArrayCast(const std::vector<T>& arr) { std::vector<T2> ret(arr.size()); for (size_t i = 0; i < arr.size(); ++i) { ret[i] = static_cast<T2>(arr[i]); } return ret; } template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; Atoi(str.c_str(), &ret); return ret; } }; template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { return static_cast<T>(std::stod(str)); } }; template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T> inline static std::vector<std::vector<T>> StringToArrayofArrays( const std::string& str, char left_bracket, char right_bracket, char delimiter) { std::vector<std::string> strs = SplitBrackets(str.c_str(), left_bracket, right_bracket); std::vector<std::vector<T>> ret; for (const auto& s : strs) { ret.push_back(StringToArray<T>(s, delimiter)); } return ret; } template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return Atoi(p, out); } }; template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter, const bool force_C_locale = false) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[0]; for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } template<> inline std::string Join<int8_t>(const std::vector<int8_t>& strs, const char* delimiter, const bool force_C_locale) { if (strs.empty()) { return std::string(""); } std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << static_cast<int16_t>(strs[0]); for (size_t i = 1; i < strs.size(); ++i) { str_buf << delimiter; str_buf << static_cast<int16_t>(strs[i]); } return str_buf.str(); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter, const bool force_C_locale = false) { if (end - start <= 0) { return std::string(""); } start = std::min(start, static_cast<size_t>(strs.size()) - 1); end = std::min(end, static_cast<size_t>(strs.size())); std::stringstream str_buf; if (force_C_locale) { C_stringstream(str_buf); } str_buf << std::setprecision(std::numeric_limits<double>::digits10 + 2); str_buf << strs[start]; for (size_t i = start + 1; i < end; ++i) { str_buf << delimiter; str_buf << strs[i]; } return str_buf.str(); } inline static int64_t Pow2RoundUp(int64_t x) { int64_t t = 1; for (int i = 0; i < 64; ++i) { if (t >= x) { return t; } t <<= 1; } return 0; } /*! * \brief Do inplace softmax transformation on p_rec * \param p_rec The input/output vector of the values. */ inline static void Softmax(std::vector<double>* p_rec) { std::vector<double> &rec = *p_rec; double wmax = rec[0]; for (size_t i = 1; i < rec.size(); ++i) { wmax = std::max(rec[i], wmax); } double wsum = 0.0f; for (size_t i = 0; i < rec.size(); ++i) { rec[i] = std::exp(rec[i] - wmax); wsum += rec[i]; } for (size_t i = 0; i < rec.size(); ++i) { rec[i] /= static_cast<double>(wsum); } } inline static void Softmax(const double* input, double* output, int len) { double wmax = input[0]; for (int i = 1; i < len; ++i) { wmax = std::max(input[i], wmax); } double wsum = 0.0f; for (int i = 0; i < len; ++i) { output[i] = std::exp(input[i] - wmax); wsum += output[i]; } for (int i = 0; i < len; ++i) { output[i] /= static_cast<double>(wsum); } } template<typename T> std::vector<const T*> ConstPtrInVectorWrapper(const std::vector<std::unique_ptr<T>>& input) { std::vector<const T*> ret; for (auto t = input.begin(); t !=input.end(); ++t) { ret.push_back(t->get()); } return ret; } template<typename T1, typename T2> inline static void SortForPair(std::vector<T1>* keys, std::vector<T2>* values, size_t start, bool is_reverse = false) { std::vector<std::pair<T1, T2>> arr; auto& ref_key = *keys; auto& ref_value = *values; for (size_t i = start; i < keys->size(); ++i) { arr.emplace_back(ref_key[i], ref_value[i]); } if (!is_reverse) { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first < b.first; }); } else { std::stable_sort(arr.begin(), arr.end(), [](const std::pair<T1, T2>& a, const std::pair<T1, T2>& b) { return a.first > b.first; }); } for (size_t i = start; i < arr.size(); ++i) { ref_key[i] = arr[i].first; ref_value[i] = arr[i].second; } } template <typename T> inline static std::vector<T*> Vector2Ptr(std::vector<std::vector<T>>* data) { std::vector<T*> ptr(data->size()); auto& ref_data = *data; for (size_t i = 0; i < data->size(); ++i) { ptr[i] = ref_data[i].data(); } return ptr; } template <typename T> inline static std::vector<int> VectorSize(const std::vector<std::vector<T>>& data) { std::vector<int> ret(data.size()); for (size_t i = 0; i < data.size(); ++i) { ret[i] = static_cast<int>(data[i].size()); } return ret; } inline static double AvoidInf(double x) { if (std::isnan(x)) { return 0.0; } else if (x >= 1e300) { return 1e300; } else if (x <= -1e300) { return -1e300; } else { return x; } } inline static float AvoidInf(float x) { if (std::isnan(x)) { return 0.0f; } else if (x >= 1e38) { return 1e38f; } else if (x <= -1e38) { return -1e38f; } else { return x; } } template<typename _Iter> inline static typename std::iterator_traits<_Iter>::value_type* IteratorValType(_Iter) { return (0); } template<typename _RanIt, typename _Pr, typename _VTRanIt> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred, _VTRanIt*) { size_t len = _Last - _First; const size_t kMinInnerLen = 1024; int num_threads = OMP_NUM_THREADS(); if (len <= kMinInnerLen || num_threads <= 1) { std::sort(_First, _Last, _Pred); return; } size_t inner_size = (len + num_threads - 1) / num_threads; inner_size = std::max(inner_size, kMinInnerLen); num_threads = static_cast<int>((len + inner_size - 1) / inner_size); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < num_threads; ++i) { size_t left = inner_size*i; size_t right = left + inner_size; right = std::min(right, len); if (right > left) { std::sort(_First + left, _First + right, _Pred); } } // Buffer for merge. std::vector<_VTRanIt> temp_buf(len); _RanIt buf = temp_buf.begin(); size_t s = inner_size; // Recursive merge while (s < len) { int loop_size = static_cast<int>((len + s * 2 - 1) / (s * 2)); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < loop_size; ++i) { size_t left = i * 2 * s; size_t mid = left + s; size_t right = mid + s; right = std::min(len, right); if (mid >= right) { continue; } std::copy(_First + left, _First + mid, buf + left); std::merge(buf + left, buf + mid, _First + mid, _First + right, _First + left, _Pred); } s *= 2; } } template<typename _RanIt, typename _Pr> inline static void ParallelSort(_RanIt _First, _RanIt _Last, _Pr _Pred) { return ParallelSort(_First, _Last, _Pred, IteratorValType(_First)); } // Check that all y[] are in interval [ymin, ymax] (end points included); throws error if not template <typename T> inline static void CheckElementsIntervalClosed(const T *y, T ymin, T ymax, int ny, const char *callername) { auto fatal_msg = [&y, &ymin, &ymax, &callername](int i) { std::ostringstream os; os << "[%s]: does not tolerate element [#%i = " << y[i] << "] outside [" << ymin << ", " << ymax << "]"; Log::Fatal(os.str().c_str(), callername, i); }; for (int i = 1; i < ny; i += 2) { if (y[i - 1] < y[i]) { if (y[i - 1] < ymin) { fatal_msg(i - 1); } else if (y[i] > ymax) { fatal_msg(i); } } else { if (y[i - 1] > ymax) { fatal_msg(i - 1); } else if (y[i] < ymin) { fatal_msg(i); } } } if (ny & 1) { // odd if (y[ny - 1] < ymin || y[ny - 1] > ymax) { fatal_msg(ny - 1); } } } // One-pass scan over array w with nw elements: find min, max and sum of elements; // this is useful for checking weight requirements. template <typename T1, typename T2> inline static void ObtainMinMaxSum(const T1 *w, int nw, T1 *mi, T1 *ma, T2 *su) { T1 minw; T1 maxw; T1 sumw; int i; if (nw & 1) { // odd minw = w[0]; maxw = w[0]; sumw = w[0]; i = 2; } else { // even if (w[0] < w[1]) { minw = w[0]; maxw = w[1]; } else { minw = w[1]; maxw = w[0]; } sumw = w[0] + w[1]; i = 3; } for (; i < nw; i += 2) { if (w[i - 1] < w[i]) { minw = std::min(minw, w[i - 1]); maxw = std::max(maxw, w[i]); } else { minw = std::min(minw, w[i]); maxw = std::max(maxw, w[i - 1]); } sumw += w[i - 1] + w[i]; } if (mi != nullptr) { *mi = minw; } if (ma != nullptr) { *ma = maxw; } if (su != nullptr) { *su = static_cast<T2>(sumw); } } inline static std::vector<uint32_t> EmptyBitset(int n) { int size = n / 32; if (n % 32 != 0) ++size; return std::vector<uint32_t>(size); } template<typename T> inline static void InsertBitset(std::vector<uint32_t>* vec, const T val) { auto& ref_v = *vec; int i1 = val / 32; int i2 = val % 32; if (static_cast<int>(vec->size()) < i1 + 1) { vec->resize(i1 + 1, 0); } ref_v[i1] |= (1 << i2); } template<typename T> inline static std::vector<uint32_t> ConstructBitset(const T* vals, int n) { std::vector<uint32_t> ret; for (int i = 0; i < n; ++i) { int i1 = vals[i] / 32; int i2 = vals[i] % 32; if (static_cast<int>(ret.size()) < i1 + 1) { ret.resize(i1 + 1, 0); } ret[i1] |= (1 << i2); } return ret; } template<typename T> inline static bool FindInBitset(const uint32_t* bits, int n, T pos) { int i1 = pos / 32; if (i1 >= n) { return false; } int i2 = pos % 32; return (bits[i1] >> i2) & 1; } inline static bool CheckDoubleEqualOrdered(double a, double b) { double upper = std::nextafter(a, INFINITY); return b <= upper; } inline static double GetDoubleUpperBound(double a) { return std::nextafter(a, INFINITY); } inline static size_t GetLine(const char* str) { auto start = str; while (*str != '\0' && *str != '\n' && *str != '\r') { ++str; } return str - start; } inline static const char* SkipNewLine(const char* str) { if (*str == '\r') { ++str; } if (*str == '\n') { ++str; } return str; } template <typename T> static int Sign(T x) { return (x > T(0)) - (x < T(0)); } template <typename T> static T SafeLog(T x) { if (x > 0) { return std::log(x); } else { return -INFINITY; } } inline bool CheckAllowedJSON(const std::string& s) { unsigned char char_code; for (auto c : s) { char_code = static_cast<unsigned char>(c); if (char_code == 34 // " || char_code == 44 // , || char_code == 58 // : || char_code == 91 // [ || char_code == 93 // ] || char_code == 123 // { || char_code == 125 // } ) { return false; } } return true; } inline int RoundInt(double x) { return static_cast<int>(x + 0.5f); } template <typename T, std::size_t N = 32> class AlignmentAllocator { public: typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; inline AlignmentAllocator() throw() {} template <typename T2> inline AlignmentAllocator(const AlignmentAllocator<T2, N>&) throw() {} inline ~AlignmentAllocator() throw() {} inline pointer adress(reference r) { return &r; } inline const_pointer adress(const_reference r) const { return &r; } inline pointer allocate(size_type n) { return (pointer)_mm_malloc(n * sizeof(value_type), N); } inline void deallocate(pointer p, size_type) { _mm_free(p); } inline void construct(pointer p, const value_type& wert) { new (p) value_type(wert); } inline void destroy(pointer p) { p->~value_type(); } inline size_type max_size() const throw() { return size_type(-1) / sizeof(value_type); } template <typename T2> struct rebind { typedef AlignmentAllocator<T2, N> other; }; bool operator!=(const AlignmentAllocator<T, N>& other) const { return !(*this == other); } // Returns true if and only if storage allocated from *this // can be deallocated from other, and vice versa. // Always returns true for stateless allocators. bool operator==(const AlignmentAllocator<T, N>&) const { return true; } }; class Timer { public: Timer() { #ifdef TIMETAG int num_threads = OMP_NUM_THREADS(); start_time_.resize(num_threads); stats_.resize(num_threads); #endif // TIMETAG } ~Timer() { Print(); } #ifdef TIMETAG void Start(const std::string& name) { auto tid = omp_get_thread_num(); start_time_[tid][name] = std::chrono::steady_clock::now(); } void Stop(const std::string& name) { auto cur_time = std::chrono::steady_clock::now(); auto tid = omp_get_thread_num(); if (stats_[tid].find(name) == stats_[tid].end()) { stats_[tid][name] = std::chrono::duration<double, std::milli>(0); } stats_[tid][name] += cur_time - start_time_[tid][name]; } #else void Start(const std::string&) {} void Stop(const std::string&) {} #endif // TIMETAG void Print() const { #ifdef TIMETAG std::unordered_map<std::string, std::chrono::duration<double, std::milli>> stats(stats_[0].begin(), stats_[0].end()); for (size_t i = 1; i < stats_.size(); ++i) { for (auto it = stats_[i].begin(); it != stats_[i].end(); ++it) { if (stats.find(it->first) == stats.end()) { stats[it->first] = it->second; } else { stats[it->first] += it->second; } } } std::map<std::string, std::chrono::duration<double, std::milli>> ordered( stats.begin(), stats.end()); for (auto it = ordered.begin(); it != ordered.end(); ++it) { Log::Info("%s costs:\t %f", it->first.c_str(), it->second * 1e-3); } #endif // TIMETAG } #ifdef TIMETAG std::vector< std::unordered_map<std::string, std::chrono::steady_clock::time_point>> start_time_; std::vector<std::unordered_map<std::string, std::chrono::duration<double, std::milli>>> stats_; #endif // TIMETAG }; // Note: this class is not thread-safe, don't use it inside omp blocks class FunctionTimer { public: #ifdef TIMETAG FunctionTimer(const std::string& name, Timer& timer) : timer_(timer) { timer.Start(name); name_ = name; } ~FunctionTimer() { timer_.Stop(name_); } private: std::string name_; Timer& timer_; #else FunctionTimer(const std::string&, Timer&) {} #endif // TIMETAG }; } // namespace Common extern Common::Timer global_timer; /*! * Provides locale-independent alternatives to Common's methods. * Essential to make models robust to locale settings. */ namespace CommonC { template<typename T> inline static std::string Join(const std::vector<T>& strs, const char* delimiter) { return LightGBM::Common::Join(strs, delimiter, true); } template<typename T> inline static std::string Join(const std::vector<T>& strs, size_t start, size_t end, const char* delimiter) { return LightGBM::Common::Join(strs, start, end, delimiter, true); } inline static const char* Atof(const char* p, double* out) { return LightGBM::Common::Atof(p, out); } template<typename T, bool is_float> struct __StringToTHelperFast { const char* operator()(const char*p, T* out) const { return LightGBM::Common::Atoi(p, out); } }; /*! * \warning Beware that ``Common::Atof`` in ``__StringToTHelperFast``, * has **less** floating point precision than ``__StringToTHelper``. * Both versions are kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. * Check ``StringToArrayFast`` and ``StringToArray`` for more details on this. */ template<typename T> struct __StringToTHelperFast<T, true> { const char* operator()(const char*p, T* out) const { double tmp = 0.0f; auto ret = Atof(p, &tmp); *out = static_cast<T>(tmp); return ret; } }; template<typename T, bool is_float> struct __StringToTHelper { T operator()(const std::string& str) const { T ret = 0; LightGBM::Common::Atoi(str.c_str(), &ret); return ret; } }; /*! * \warning Beware that ``Common::Atof`` in ``__StringToTHelperFast``, * has **less** floating point precision than ``__StringToTHelper``. * Both versions are kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. * Check ``StringToArrayFast`` and ``StringToArray`` for more details on this. * \note It is possible that ``fast_double_parser::parse_number`` is faster than ``Common::Atof``. */ template<typename T> struct __StringToTHelper<T, true> { T operator()(const std::string& str) const { double tmp; const char* end = Common::AtofPrecise(str.c_str(), &tmp); if (end == str.c_str()) { Log::Fatal("Failed to parse double: %s", str.c_str()); } return static_cast<T>(tmp); } }; /*! * \warning Beware that due to internal use of ``Common::Atof`` in ``__StringToTHelperFast``, * this method has less precision for floating point numbers than ``StringToArray``, * which calls ``__StringToTHelper``. * As such, ``StringToArrayFast`` and ``StringToArray`` are not equivalent! * Both versions were kept to maintain bit-for-bit the "legacy" LightGBM behaviour in terms of precision. */ template<typename T> inline static std::vector<T> StringToArrayFast(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } auto p_str = str.c_str(); __StringToTHelperFast<T, std::is_floating_point<T>::value> helper; std::vector<T> ret(n); for (int i = 0; i < n; ++i) { p_str = helper(p_str, &ret[i]); } return ret; } /*! * \warning Do not replace calls to this method by ``StringToArrayFast``. * This method is more precise for floating point numbers. * Check ``StringToArrayFast`` for more details. */ template<typename T> inline static std::vector<T> StringToArray(const std::string& str, int n) { if (n == 0) { return std::vector<T>(); } std::vector<std::string> strs = LightGBM::Common::Split(str.c_str(), ' '); CHECK_EQ(strs.size(), static_cast<size_t>(n)); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } /*! * \warning Do not replace calls to this method by ``StringToArrayFast``. * This method is more precise for floating point numbers. * Check ``StringToArrayFast`` for more details. */ template<typename T> inline static std::vector<T> StringToArray(const std::string& str, char delimiter) { std::vector<std::string> strs = LightGBM::Common::Split(str.c_str(), delimiter); std::vector<T> ret; ret.reserve(strs.size()); __StringToTHelper<T, std::is_floating_point<T>::value> helper; for (const auto& s : strs) { ret.push_back(helper(s)); } return ret; } #if (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) /*! * Safely formats a value onto a buffer according to a format string and null-terminates it. * * \note It checks that the full value was written or forcefully aborts. * This safety check serves to prevent incorrect internal API usage. * Correct usage will never incur in this problem: * - The received buffer size shall be sufficient at all times for the input format string and value. */ template <typename T> inline static void format_to_buf(char* buffer, const size_t buf_len, const char* format, const T value) { auto result = fmt::format_to_n(buffer, buf_len, format, value); if (result.size >= buf_len) { Log::Fatal("Numerical conversion failed. Buffer is too small."); } buffer[result.size] = '\0'; } template<typename T, bool is_float, bool high_precision> struct __TToStringHelper { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{}", value); } }; template<typename T> struct __TToStringHelper<T, true, false> { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{:g}", value); } }; template<typename T> struct __TToStringHelper<T, true, true> { void operator()(T value, char* buffer, size_t buf_len) const { format_to_buf(buffer, buf_len, "{:.17g}", value); } }; /*! * Converts an array to a string with with values separated by the space character. * This method replaces Common's ``ArrayToString`` and ``ArrayToStringFast`` functionality * and is locale-independent. * * \note If ``high_precision_output`` is set to true, * floating point values are output with more digits of precision. */ template<bool high_precision_output = false, typename T> inline static std::string ArrayToString(const std::vector<T>& arr, size_t n) { if (arr.empty() || n == 0) { return std::string(""); } __TToStringHelper<T, std::is_floating_point<T>::value, high_precision_output> helper; const size_t buf_len = high_precision_output ? 32 : 16; std::vector<char> buffer(buf_len); std::stringstream str_buf; Common::C_stringstream(str_buf); helper(arr[0], buffer.data(), buf_len); str_buf << buffer.data(); for (size_t i = 1; i < std::min(n, arr.size()); ++i) { helper(arr[i], buffer.data(), buf_len); str_buf << ' ' << buffer.data(); } return str_buf.str(); } #endif // (!((defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)))) } // namespace CommonC } // namespace LightGBM #endif // LIGHTGBM_UTILS_COMMON_H_
uts_omp_task_shmem.c
/* * ---- The Unbalanced Tree Search (UTS) Benchmark ---- * * Copyright (c) 2010 See AUTHORS file for copyright holders * * This file is part of the unbalanced tree search benchmark. This * project is licensed under the MIT Open Source license. See the LICENSE * file for copyright and licensing information. * * UTS is a collaborative project between researchers at the University of * Maryland, the University of North Carolina at Chapel Hill, and the Ohio * State University. See AUTHORS file for more information. * */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <assert.h> #include <shmem.h> #include "uts.h" /*********************************************************** * * * Compiler Type (these flags are set by at compile time) * * (default) ANSI C compiler - sequential execution * * (_OPENMP) OpenMP enabled C compiler * * (__UPC__) UPC compiler * * (_SHMEM) Cray Shmem * * (__PTHREADS__) Pthreads multithreaded execution * * * ***********************************************************/ #if defined(_OPENMP) /**** OpenMP Definitions ****/ #include <omp.h> #define PARALLEL 1 #define COMPILER_TYPE 1 #define SHARED #define SHARED_INDEF #define VOLATILE volatile #define MAX_OMP_THREADS 32 #define MAX_SHMEM_THREADS 64 #define LOCK_T omp_lock_t #define GET_NUM_THREADS omp_get_num_threads() #define GET_THREAD_NUM omp_get_thread_num() #define SET_LOCK(zlk) omp_set_lock(zlk) #define UNSET_LOCK(zlk) omp_unset_lock(zlk) #define INIT_LOCK(zlk) zlk=omp_global_lock_alloc() #define INIT_SINGLE_LOCK(zlk) zlk=omp_global_lock_alloc() #define SMEMCPY memcpy #define ALLOC malloc #define BARRIER // OpenMP helper function to match UPC lock allocation semantics omp_lock_t * omp_global_lock_alloc() { omp_lock_t *lock = (omp_lock_t *) malloc(sizeof(omp_lock_t) + 128); omp_init_lock(lock); return lock; } #else #error Only supports OMP #endif /* END Par. Model Definitions */ /*********************************************************** * Parallel execution parameters * ***********************************************************/ int doSteal = PARALLEL; // 1 => use work stealing int chunkSize = 20; // number of nodes to move to/from shared area int cbint = 1; // Cancellable barrier polling interval int pollint = 1; // BUPC Polling interval int n_nodes = 0; int n_leaves = 0; #ifdef THREAD_METADATA typedef struct _thread_metadata { size_t ntasks; } thread_metadata; thread_metadata t_metadata[MAX_OMP_THREADS]; #endif #define N_BUFFERED_STEALS 16 Node steal_buffer[N_BUFFERED_STEALS]; volatile int n_buffered_steals = 0; long steal_buffer_locks[MAX_SHMEM_THREADS]; int complete_pes = 0; static int pe, npes; static int steal_from(int target_pe, Node *stolen_out) { int remote_buffered_steals; shmem_set_lock(&steal_buffer_locks[target_pe]); shmem_int_get(&remote_buffered_steals, &n_buffered_steals, 1, target_pe); int stole_something = 0; if (remote_buffered_steals > 0) { remote_buffered_steals--; shmem_getmem(stolen_out, &steal_buffer[remote_buffered_steals], sizeof(Node), target_pe); shmem_int_put(&n_buffered_steals, &remote_buffered_steals, 1, target_pe); stole_something = 1; } shmem_clear_lock(&steal_buffer_locks[target_pe]); return stole_something; } static int remote_steal(Node *stolen_out) { int pe_above = (pe + 1) % npes; int pe_below = pe - 1; if (pe_below < 0) pe_below = npes - 1; shmem_int_add(&complete_pes, 1, 0); int ndone = shmem_int_fadd(&complete_pes, 0, 0); while (ndone != npes) { // Try to remote steal if (steal_from(pe_above, stolen_out) || steal_from(pe_below, stolen_out)) { shmem_int_add(&complete_pes, -1, 0); return 1; } pe_above = (pe_above + 1) % npes; pe_below = pe_below - 1; if (pe_below < 0) pe_below = npes - 1; ndone = shmem_int_fadd(&complete_pes, 0, 0); } assert(ndone == npes); return 0; } #ifdef __BERKELEY_UPC__ /* BUPC nonblocking I/O Handles */ bupc_handle_t cb_handle = BUPC_COMPLETE_HANDLE; const int local_cb_cancel = 1; #endif /*********************************************************** * Tree statistics (if selected via UTS_STAT) * * compute overall size and imbalance metrics * * and histogram size and imbalance per level * ***********************************************************/ #ifdef UTS_STAT /* Check that we are not being asked to compile parallel with stats. * Parallel stats collection is presently not supported. */ #if PARALLEL #error "ERROR: Parallel stats collection is not supported!" #endif #define MAXHISTSIZE 2000 // max tree depth in histogram int stats = 1; int unbType = 1; int maxHeight = 0; // maximum depth of tree double maxImb = 0; // maximum imbalance double minImb = 1; double treeImb =-1; // Overall imbalance, undefined int hist[MAXHISTSIZE+1][2]; // average # nodes per level double unbhist[MAXHISTSIZE+1][3]; // average imbalance per level int *rootSize; // size of the root's children double *rootUnb; // imbalance of root's children /* Tseng statistics */ int totalNodes = 0; double imb_max = 0; // % of work in largest child (ranges from 100/n to 100%) double imb_avg = 0; double imb_devmaxavg = 0; // ( % of work in largest child ) - ( avg work ) double imb_normdevmaxavg = 0; // ( % of work in largest child ) - ( avg work ) / ( 100% - avg work ) #else int stats = 0; int unbType = -1; #endif /*********************************************************** * Execution Tracing * ***********************************************************/ #define SS_WORK 0 #define SS_SEARCH 1 #define SS_IDLE 2 #define SS_OVH 3 #define SS_CBOVH 4 #define SS_NSTATES 5 /* session record for session visualization */ struct sessionRecord_t { double startTime, endTime; }; typedef struct sessionRecord_t SessionRecord; /* steal record for steal visualization */ struct stealRecord_t { long int nodeCount; /* count nodes generated during the session */ int victimThread; /* thread from which we stole the work */ }; typedef struct stealRecord_t StealRecord; /* Store debugging and trace data */ struct metaData_t { SessionRecord sessionRecords[SS_NSTATES][20000]; /* session time records */ StealRecord stealRecords[20000]; /* steal records */ }; typedef struct metaData_t MetaData; /* holds text string for debugging info */ char debug_str[1000]; /*********************************************************** * StealStack types * ***********************************************************/ /*********************************************************** * Global shared state * ***********************************************************/ // termination detection VOLATILE SHARED int cb_cancel; VOLATILE SHARED int cb_count; VOLATILE SHARED int cb_done; LOCK_T * cb_lock; /*********************************************************** * UTS Implementation Hooks * ***********************************************************/ // Return a string describing this implementation char * impl_getName() { char * name[] = {"Sequential C", "C/OpenMP", "UPC", "SHMEM", "PThreads"}; return name[COMPILER_TYPE]; } // construct string with all parameter settings int impl_paramsToStr(char *strBuf, int ind) { int n_omp_threads; #pragma omp parallel #pragma omp single n_omp_threads = omp_get_num_threads(); ind += sprintf(strBuf+ind, "Execution strategy: "); if (PARALLEL) { ind += sprintf(strBuf+ind, "Parallel search using %d threads total (%d " "SHMEM PEs, %d OMP threads per PE)\n", npes * n_omp_threads, npes, n_omp_threads); if (doSteal) { ind += sprintf(strBuf+ind, " Load balance by work stealing, chunk size = %d nodes\n",chunkSize); ind += sprintf(strBuf+ind, " CBarrier Interval: %d\n", cbint); ind += sprintf(strBuf+ind, " Polling Interval: %d\n", pollint); } else ind += sprintf(strBuf+ind, " No load balancing.\n"); } else ind += sprintf(strBuf+ind, "Iterative sequential search\n"); return ind; } int impl_parseParam(char *param, char *value) { int err = 0; // Return 0 on a match, nonzero on an error switch (param[1]) { #if (PARALLEL == 1) case 'c': chunkSize = atoi(value); break; case 's': doSteal = atoi(value); if (doSteal != 1 && doSteal != 0) err = 1; break; case 'i': cbint = atoi(value); break; #ifdef __BERKELEY_UPC__ case 'I': pollint = atoi(value); break; #endif #else /* !PARALLEL */ #ifdef UTS_STAT case 'u': unbType = atoi(value); if (unbType > 2) { err = 1; break; } if (unbType < 0) stats = 0; else stats = 1; break; #endif #endif /* PARALLEL */ default: err = 1; break; } return err; } void impl_helpMessage() { if (PARALLEL) { printf(" -s int zero/nonzero to disable/enable work stealing\n"); printf(" -c int chunksize for work stealing\n"); printf(" -i int set cancellable barrier polling interval\n"); #ifdef __BERKELEY_UPC__ printf(" -I int set working bupc_poll() interval\n"); #endif #ifdef __PTHREADS__ printf(" -T int set number of threads\n"); #endif } else { #ifdef UTS_STAT printf(" -u int unbalance measure (-1: none; 0: min/size; 1: min/n; 2: max/n)\n"); #else printf(" none.\n"); #endif } } void impl_abort(int err) { #if defined(__UPC__) upc_global_exit(err); #elif defined(_OPENMP) exit(err); #elif defined(_SHMEM) exit(err); #else exit(err); #endif } /*********************************************************** * * * FUNCTIONS * * * ***********************************************************/ /* * StealStack * Stack of nodes with sharing at the bottom of the stack * and exclusive access at the top for the "owning" thread * which has affinity to the stack's address space. * * * All operations on the shared portion of the stack * must be guarded using the stack-specific lock. * * Elements move between the shared and exclusive * portion of the stack solely under control of the * owning thread. (ss_release and ss_acquire) * * workAvail is the count of elements in the shared * portion of the stack. It may be read without * acquiring the stack lock, but of course its value * may not be acurate. Idle threads read workAvail in * this speculative fashion to minimize overhead to * working threads. * * Elements can be stolen from the bottom of the shared * portion by non-owning threads. The values are * reserved under lock by the stealing thread, and then * copied without use of the lock (currently space for * reserved values is never reclaimed). * */ /* fatal error */ void ss_error(char *str) { printf("*** [Thread %i] %s\n",GET_THREAD_NUM, str); exit(4); } #ifdef UTS_STAT /* * Statistics, * : number of nodes per level * : imbalanceness of nodes per level * */ void initHist() { int i; for (i=0; i<MAXHISTSIZE; i++){ hist[i][0]=0; hist[i][1]=0; unbhist[i][1]=1; unbhist[i][2]=0; } } void updateHist(Node* c, double unb) { if (c->height<MAXHISTSIZE){ hist[c->height][1]++; hist[c->height][0]+=c->numChildren; unbhist[c->height][0]+=unb; if (unbhist[c->height][1]>unb) unbhist[c->height][1]=unb; if (unbhist[c->height][2]<unb) unbhist[c->height][2]=unb; } else { hist[MAXHISTSIZE][1]++; hist[MAXHISTSIZE][0]+=c->numChildren; } } void showHist(FILE *fp) { int i; fprintf(fp, "depth\tavgNumChildren\t\tnumChildren\t imb\t maxImb\t minImb\t\n"); for (i=0; i<MAXHISTSIZE; i++){ if ((hist[i][0]!=0)&&(hist[i][1]!=0)) fprintf(fp, "%d\t%f\t%d\t %lf\t%lf\t%lf\n", i, (double)hist[i][0]/hist[i][1], hist[i][0], unbhist[i][0]/hist[i][1], unbhist[i][1], unbhist[i][2]); } } double getImb(Node *c) { int i=0; double avg=.0, tmp=.0; double unb=0.0; avg=(double)c->sizeChildren/c->numChildren; for (i=0; i<c->numChildren; i++){ if ((type==BIN)&&(c->pp==NULL)) { if (unbType<2) tmp=min((double)rootSize[i]/avg, avg/(double)rootSize[i]); else tmp=max((double)rootSize[i]/avg, avg/(double)rootSize[i]); if (unbType>0) unb+=tmp*rootUnb[i]; else unb+=tmp*rootUnb[i]*rootSize[i]; } else{ if (unbType<2) tmp=min((double)c->size[i]/avg, avg/(double)c->size[i]); else tmp=max((double)c->size[i]/avg, avg/(double)c->size[i]); if (unbType>0) unb+=tmp*c->unb[i]; else unb+=tmp*c->unb[i]*c->size[i]; } } if (unbType>0){ if (c->numChildren>0) unb=unb/c->numChildren; else unb=1.0; } else { if (c->sizeChildren>1) unb=unb/c->sizeChildren; else unb=1.0; } if ((debug & 1) && unb>1) printf("unb>1%lf\t%d\n", unb, c->numChildren); return unb; } void getImb_Tseng(Node *c) { double t_max, t_avg, t_devmaxavg, t_normdevmaxavg; if (c->numChildren==0) { t_avg =0; t_max =0; } else { t_max = (double)c->maxSizeChildren/(c->sizeChildren-1); t_avg = (double)1/c->numChildren; } t_devmaxavg = t_max-t_avg; if (debug & 1) printf("max\t%lf, %lf, %d, %d, %d\n", t_max, t_avg, c->maxSizeChildren, c->sizeChildren, c->numChildren); if (1-t_avg==0) t_normdevmaxavg = 1; else t_normdevmaxavg = (t_max-t_avg)/(1-t_avg); imb_max += t_max; imb_avg += t_avg; imb_devmaxavg += t_devmaxavg; imb_normdevmaxavg +=t_normdevmaxavg; } void updateParStat(Node *c) { double unb; totalNodes++; if (maxHeight<c->height) maxHeight=c->height; unb=getImb(c); maxImb=max(unb, maxImb); minImb=min(unb, minImb); updateHist(c, unb); getImb_Tseng(c); if (c->pp!=NULL){ if ((c->type==BIN)&&(c->pp->pp==NULL)){ rootSize[c->pp->ind]=c->sizeChildren; rootUnb[c->pp->ind]=unb; } else{ c->pp->size[c->pp->ind]=c->sizeChildren; c->pp->unb[c->pp->ind]=unb; } /* update statistics per node*/ c->pp->ind++; c->pp->sizeChildren+=c->sizeChildren; if (c->pp->maxSizeChildren<c->sizeChildren) c->pp->maxSizeChildren=c->sizeChildren; } else treeImb = unb; } #endif /* * Tree Implementation * */ void initNode(Node * child) { child->type = -1; child->height = -1; child->numChildren = -1; // not yet determined #ifdef UTS_STAT if (stats){ int i; child->ind = 0; child->sizeChildren = 1; child->maxSizeChildren = 0; child->pp = NULL; for (i = 0; i < MAXNUMCHILDREN; i++){ child->size[i] = 0; child->unb[i] = 0.0; } } #endif } void initRootNode(Node * root, int type) { uts_initRoot(root, type); #ifdef TRACE stealStack[0]->md->stealRecords[0].victimThread = 0; // first session is own "parent session" #endif #ifdef UTS_STAT if (stats){ int i; root->ind = 0; root->sizeChildren = 1; root->maxSizeChildren = 1; root->pp = NULL; if (type != BIN){ for (i=0; i<MAXNUMCHILDREN; i++){ root->size[i] = 0; root->unb[i] =.0; } } else { int rbf = (int) ceil(b_0); rootSize = malloc(rbf*sizeof(int)); rootUnb = malloc(rbf*sizeof(double)); for (i = 0; i < rbf; i++) { rootSize[i] = 0; rootUnb[i] = 0.0; } } } #endif } /* * Generate all children of the parent * * details depend on tree type, node type and shape function * */ void genChildren(Node * parent, Node * child) { int parentHeight = parent->height; int numChildren, childType; #ifdef THREAD_METADATA t_metadata[omp_get_thread_num()].ntasks += 1; #endif #pragma omp atomic n_nodes += 1; numChildren = uts_numChildren(parent); childType = uts_childType(parent); // record number of children in parent parent->numChildren = numChildren; // construct children and push onto stack if (numChildren > 0) { int i, j; child->type = childType; child->height = parentHeight + 1; #ifdef UTS_STAT if (stats) { child->pp = parent; // pointer to parent } #endif unsigned char * parent_state = parent->state.state; unsigned char * child_state = child->state.state; for (i = 0; i < numChildren; i++) { for (j = 0; j < computeGranularity; j++) { // TBD: add parent height to spawn // computeGranularity controls number of rng_spawn calls per node rng_spawn(parent_state, child_state, i); } Node parent = *child; int made_available_for_stealing = 0; if (omp_get_thread_num() == 0 && n_buffered_steals < N_BUFFERED_STEALS) { shmem_set_lock(&steal_buffer_locks[pe]); if (n_buffered_steals < N_BUFFERED_STEALS) { steal_buffer[n_buffered_steals++] = parent; made_available_for_stealing = 1; } shmem_clear_lock(&steal_buffer_locks[pe]); } if (!made_available_for_stealing) { #pragma omp task untied firstprivate(parent) if(parent.height < 9) { Node child; initNode(&child); if (parent.numChildren < 0) { genChildren(&parent, &child); } } } } } else { #pragma omp atomic n_leaves += 1; } } // causes one or more threads waiting at barrier, if any, // to be released #ifdef TRACE // print session records for each thread (used when trace is enabled) void printSessionRecords() { int i, j, k; double offset; for (i = 0; i < GET_NUM_THREADS; i++) { offset = startTime[i] - startTime[0]; for (j = 0; j < SS_NSTATES; j++) for (k = 0; k < stealStack[i]->entries[j]; k++) { printf ("%d %d %f %f", i, j, stealStack[i]->md->sessionRecords[j][k].startTime - offset, stealStack[i]->md->sessionRecords[j][k].endTime - offset); if (j == SS_WORK) printf (" %d %ld", stealStack[i]->md->stealRecords[k].victimThread, stealStack[i]->md->stealRecords[k].nodeCount); printf ("\n"); } } } #endif // display search statistics void showStats(double elapsedSecs) { int i; int tnodes = 0, tleaves = 0, trel = 0, tacq = 0, tsteal = 0, tfail= 0; int mdepth = 0, mheight = 0; double twork = 0.0, tsearch = 0.0, tidle = 0.0, tovh = 0.0, tcbovh = 0.0; // // combine measurements from all threads // for (i = 0; i < GET_NUM_THREADS; i++) { // tnodes += stealStack[i]->nNodes; // tleaves += stealStack[i]->nLeaves; // trel += stealStack[i]->nRelease; // tacq += stealStack[i]->nAcquire; // tsteal += stealStack[i]->nSteal; // tfail += stealStack[i]->nFail; // twork += stealStack[i]->time[SS_WORK]; // tsearch += stealStack[i]->time[SS_SEARCH]; // tidle += stealStack[i]->time[SS_IDLE]; // tovh += stealStack[i]->time[SS_OVH]; // tcbovh += stealStack[i]->time[SS_CBOVH]; // mdepth = max(mdepth, stealStack[i]->maxStackDepth); // mheight = max(mheight, stealStack[i]->maxTreeDepth); // } // if (trel != tacq + tsteal) { // printf("*** error! total released != total acquired + total stolen\n"); // } // uts_showStats(GET_NUM_THREADS, chunkSize, elapsedSecs, n_nodes, n_leaves, mheight); // // if (verbose > 1) { // if (doSteal) { // printf("Total chunks released = %d, of which %d reacquired and %d stolen\n", // trel, tacq, tsteal); // printf("Failed steal operations = %d, ", tfail); // } // // printf("Max stealStack size = %d\n", mdepth); // printf("Avg time per thread: Work = %.6f, Search = %.6f, Idle = %.6f\n", (twork / GET_NUM_THREADS), // (tsearch / GET_NUM_THREADS), (tidle / GET_NUM_THREADS)); // printf(" Overhead = %6f, CB_Overhead = %6f\n\n", (tovh / GET_NUM_THREADS), // (tcbovh/GET_NUM_THREADS)); // } // // // per thread execution info // if (verbose > 2) { // for (i = 0; i < GET_NUM_THREADS; i++) { // printf("** Thread %d\n", i); // printf(" # nodes explored = %d\n", stealStack[i]->nNodes); // printf(" # chunks released = %d\n", stealStack[i]->nRelease); // printf(" # chunks reacquired = %d\n", stealStack[i]->nAcquire); // printf(" # chunks stolen = %d\n", stealStack[i]->nSteal); // printf(" # failed steals = %d\n", stealStack[i]->nFail); // printf(" maximum stack depth = %d\n", stealStack[i]->maxStackDepth); // printf(" work time = %.6f secs (%d sessions)\n", // stealStack[i]->time[SS_WORK], stealStack[i]->entries[SS_WORK]); // printf(" overhead time = %.6f secs (%d sessions)\n", // stealStack[i]->time[SS_OVH], stealStack[i]->entries[SS_OVH]); // printf(" search time = %.6f secs (%d sessions)\n", // stealStack[i]->time[SS_SEARCH], stealStack[i]->entries[SS_SEARCH]); // printf(" idle time = %.6f secs (%d sessions)\n", // stealStack[i]->time[SS_IDLE], stealStack[i]->entries[SS_IDLE]); // printf(" wakeups = %d, false wakeups = %d (%.2f%%)", // stealStack[i]->wakeups, stealStack[i]->falseWakeups, // (stealStack[i]->wakeups == 0) ? 0.00 : ((((double)stealStack[i]->falseWakeups)/stealStack[i]->wakeups)*100.0)); // printf("\n"); // } // } // // #ifdef TRACE // printSessionRecords(); // #endif // // // tree statistics output to stat.txt, if requested // #ifdef UTS_STAT // if (stats) { // FILE *fp; // char * tmpstr; // char strBuf[5000]; // int ind = 0; // // fp = fopen("stat.txt", "a+w"); // fprintf(fp, "\n------------------------------------------------------------------------------------------------------\n"); // ind = uts_paramsToStr(strBuf, ind); // ind = impl_paramsToStr(strBuf, ind); // //showParametersStr(strBuf); // fprintf(fp, "%s\n", strBuf); // // fprintf(fp, "\nTotal nodes = %d\n", totalNodes); // fprintf(fp, "Max depth = %d\n\n", maxHeight); // fprintf(fp, "Tseng ImbMeasure(overall)\n max:\t\t%lf \n avg:\t\t%lf \n devMaxAvg:\t %lf\n normDevMaxAvg: %lf\t\t\n\n", // imb_max/totalNodes, imb_avg/totalNodes, imb_devmaxavg/totalNodes, // imb_normdevmaxavg/totalNodes); // // switch (unbType){ // case 0: tmpstr = "(min imb weighted by size)"; break; // case 1: tmpstr = "(min imb not weighted by size)"; break; // case 2: tmpstr = "(max imb not weighted by size)"; break; // default: tmpstr = "(?unknown measure)"; break; // } // fprintf(fp, "ImbMeasure:\t%s\n Overall:\t %lf\n Max:\t\t%lf\n Min:\t\t%lf\n\n", // tmpstr, treeImb, minImb, maxImb); // showHist(fp); // fprintf(fp, "\n------------------------------------------------------------------------------------------------------\n\n\n"); // fclose(fp); // } // #endif } /* Main() function for: Sequential, OpenMP, UPC, and Shmem * * Notes on execution model: * - under openMP, global vars are all shared * - under UPC, global vars are private unless explicitly shared * - UPC is SPMD starting with main, OpenMP goes SPMD after * parsing parameters */ int main(int argc, char *argv[]) { Node root; #ifdef THREAD_METADATA memset(t_metadata, 0x00, MAX_OMP_THREADS * sizeof(thread_metadata)); #endif memset(steal_buffer_locks, 0x00, MAX_SHMEM_THREADS * sizeof(long)); shmem_init(); pe = shmem_my_pe(); npes = shmem_n_pes(); /* determine benchmark parameters (all PEs) */ uts_parseParams(argc, argv); #ifdef UTS_STAT if (stats) { initHist(); } #endif double t1, t2, et; /* show parameter settings */ if (pe == 0) { uts_printParams(); } initRootNode(&root, type); shmem_barrier_all(); /* time parallel search */ t1 = uts_wctime(); int n_omp_threads; /********** SPMD Parallel Region **********/ #pragma omp parallel { #pragma omp master { int first = 1; n_omp_threads = omp_get_num_threads(); assert(n_omp_threads <= MAX_OMP_THREADS); Node child; retry: initNode(&child); if (first) { if (pe == 0) { genChildren(&root, &child); } } else { genChildren(&root, &child); } first = 0; #pragma omp taskwait if (n_buffered_steals > 0) { shmem_set_lock(&steal_buffer_locks[pe]); if (n_buffered_steals > 0) { n_buffered_steals--; memcpy(&root, &steal_buffer[n_buffered_steals], sizeof(root)); shmem_clear_lock(&steal_buffer_locks[pe]); goto retry; } else { shmem_clear_lock(&steal_buffer_locks[pe]); } } const int got_more_work = remote_steal(&root); if (got_more_work == 1) { goto retry; } } } if (pe != 0) { shmem_int_add(&n_nodes, n_nodes, 0); shmem_int_add(&n_leaves, n_leaves, 0); } shmem_barrier_all(); t2 = uts_wctime(); et = t2 - t1; if (pe == 0) { showStats(et); } /********** End Parallel Region **********/ #ifdef THREAD_METADATA int p; for (p = 0; p < npes; p++) { if (p == pe) { printf("\n"); int i; for (i = 0; i < n_omp_threads; i++) { printf("PE %d, thread %d: %lu tasks\n", p, i, t_metadata[i].ntasks); } } shmem_barrier_all(); } #endif shmem_finalize(); return 0; }
9223.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop #pragma omp parallel for private(i, j) collapse(#P12) schedule(#P9, #P11) num_threads(#P11) #pragma omp parallel for for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp parallel for for (j = 1; j < _PB_NJ - 1; ++j) { B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1] + -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1] + 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1]; } } #pragma endscop // printf("Kernal computation complete !!\n"); } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj); /* Initialize array(s). */ init_array (ni, nj, POLYBENCH_ARRAY(A)); /* Start timer. */ //polybench_start_instruments; polybench_timer_start(); /* Run kernel. */ kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Stop and print timer. */ polybench_timer_stop(); polybench_timer_print(); //polybench_stop_instruments; //polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
host_function.c
#include <stdio.h> #include <omp.h> #pragma omp declare target void hostrpc_fptr0(void* fun_ptr); #pragma omp end declare target // A host function will synchronously call from a device as a function pointer void myfun() { fprintf(stderr, " This is myfun writing to stderr \n"); } int main() { int N = 10; int a[N]; int b[N]; int i; for (i=0; i<N; i++){ a[i]=0; b[i]=i; } //void (*fun_ptr)(int) = &myfun; void (*fun_ptr)() = &myfun; printf("Testing myfun execution as a function pointer \n"); (*fun_ptr)(); printf("Testing myfun execution from device using hostrpc_fptr0\n"); #pragma omp target parallel for map(from: a[0:N]) map(to: b[0:N]) is_device_ptr(fun_ptr) for (int j = 0; j< N; j++) { a[j]=b[j]; hostrpc_fptr0(fun_ptr); } printf("Testing the host fallback of hostrpc_fptr0 \n"); hostrpc_fptr0(fun_ptr); int rc = 0; for (i=0; i<N; i++) if (a[i] != b[i] ) { rc++; printf ("Wrong value: a[%d]=%d\n", i, a[i]); } if (!rc){ printf("Success\n"); return EXIT_SUCCESS; } else{ printf("Failure\n"); return EXIT_FAILURE; } }
lhac.h
// // lhac.h // LHAC_v1 // // Created by Xiaocheng Tang on 1/31/13. // Copyright (c) 2013 Xiaocheng Tang. All rights reserved. // #ifndef __LHAC_v1__lhac__ #define __LHAC_v1__lhac__ #include "Lbfgs.h" #include "Objective.h" #include <math.h> #include "linalg.h" #include "timing.h" #include "Parameter.h" #ifdef _OPENMP #include <omp.h> #endif #define MAX_LENS 1024 #define __MATLAB_API__ enum { LHAC_MSG_NO=0, LHAC_MSG_NEWTON, LHAC_MSG_SD, LHAC_MSG_CD, LHAC_MSG_MAX }; enum{ GREEDY= 1, STD, GREEDY_CUTZERO, GREEDY_CUTGRAD, GREEDY_ADDZERO, STD_CUTGRAD, STD_CUTGRAD_AGGRESSIVE }; struct Func { double f; double g; double val; // f + g inline void add(const double _f, const double _g) { f = _f; g = _g; val = f + g; }; }; template <typename T1> struct Solution { T1* t; T1* fval; T1* normgs; int* niter; unsigned long* numActive; T1* w; unsigned long p; //dimension of w T1 cdTime; T1 lsTime; T1 lbfgsTime1; T1 lbfgsTime2; unsigned long size; // max_newton_iter unsigned long ngval; unsigned long nfval; unsigned long nls; // # of line searches T1 gvalTime; T1 fvalTime; inline void addEntry(T1 objval, T1 normsg, T1 elapsedTime, int iter, unsigned long _numActive) { fval[size] = objval; normgs[size] = normsg; t[size] = elapsedTime; niter[size] = iter; numActive[size] = _numActive; (size)++; }; inline void finalReport(const int error, T1* wfinal) { memcpy(w, wfinal, p*sizeof(T1)); unsigned long last = size - 1; printf( "=========================== final report ========================\n" ); if (error) printf("Terminated!\n"); else printf("Optimal!\n"); printf( "Best objective value found %+.6e\n" "In %3d iterations (%.4e seconds)\n" "With a precision of: %+.4e\n" "=================================================================\n", fval[last], niter[last], t[last], normgs[last] / normgs[0] ); }; Solution(unsigned long max_iter, unsigned long _p) { fval = new T1[max_iter]; normgs = new T1[max_iter]; t = new T1[max_iter]; niter = new int[max_iter]; numActive = new unsigned long[max_iter]; cdTime = 0; lbfgsTime1 = 0; lbfgsTime2 = 0; lsTime = 0; ngval = 0; nfval = 0; gvalTime = 0.0; fvalTime = 0.0; nls = 0; size = 0; p = _p; w = new T1[p]; }; ~Solution() { delete [] w; delete [] fval; delete [] normgs; delete [] t; delete [] niter; return; }; }; template <typename InnerSolver, typename T1> class Subproblem { public: inline void build(LBFGS<T1>* lR, T1* grad, work_set_struct* work_set) { return static_cast<InnerSolver*>(this)->build(lR, grad, work_set); }; inline T1 objective_value(const T1 gama) { return static_cast<InnerSolver*>(this)->objective_value(gama); }; inline const T1* solve(const T1* w_prev, const unsigned short k, T1 gama) { return static_cast<InnerSolver*>(this)->solve(w_prev, k, gama); }; virtual ~Subproblem() {}; }; template <typename T1> class CoordinateDescent: public Subproblem<CoordinateDescent<T1>, T1> { public: CoordinateDescent(const Parameter* const _param, unsigned long _p): p(_p) { lmd = _param->lmd; l = _param->l; cd_rate = _param->cd_rate; msgFlag = _param->verbose; D = new T1[p]; H_diag = new T1[p]; // p d_bar = new T1[2*l]; // 2*l }; ~CoordinateDescent() { delete [] D; delete [] H_diag; delete [] d_bar; }; void build(LBFGS<T1>* lR, T1* grad, work_set_struct* work_set) { Q = lR->Q; Q_bar = lR->Q_bar; m = lR->m; L_grad = grad; permut = work_set->permut; idxs = work_set->idxs; numActive = work_set->numActive; gama0 = lR->gama; buffer = lR->buff; memset(D, 0, p*sizeof(T1)); memset(d_bar, 0, 2*l*sizeof(T1)); for (unsigned long k = 0, i = 0; i < work_set->numActive; i++, k += m) { H_diag[i] = gama0; for (unsigned long j = 0; j < m; j++) H_diag[i] -= Q_bar[k+j]*Q[k+j]; } }; T1 objective_value(const T1 gama) { T1 order1 = lcddot((int)p, D, 1, L_grad, 1); T1 order2 = 0; int cblas_M = (int) numActive; int cblas_N = (int) m; lcdgemv(CblasColMajor, CblasTrans, Q, d_bar, buffer, cblas_N, cblas_M, cblas_N); T1 vp = 0; for (unsigned long ii = 0; ii < numActive; ii++) { unsigned long idx = idxs[ii].j; unsigned long idx_Q = permut[ii]; vp += D[idx]*buffer[idx_Q]; } order2 = gama*lcddot((int)p, D, 1, D, 1)-vp; order2 = order2*0.5; return order1 + order2; } const T1* solve(const T1* w_prev, const unsigned short k, T1 gama) { T1 dH_diag = gama-gama0; unsigned long max_cd_pass = 1 + k / cd_rate; for (unsigned long cd_pass = 1; cd_pass <= max_cd_pass; cd_pass++) { T1 diffd = 0; T1 normd = 0; for (unsigned long ii = 0; ii < numActive; ii++) { unsigned long rii = ii; unsigned long idx = idxs[rii].j; unsigned long idx_Q = permut[rii]; unsigned long Q_idx_m = idx_Q*m; T1 Qd_bar = lcddot(m, &Q[Q_idx_m], 1, d_bar, 1); T1 Hd_j = gama*D[idx] - Qd_bar; T1 Hii = H_diag[idx_Q] + dH_diag; T1 G = Hd_j + L_grad[idx]; T1 Gp = G + lmd; T1 Gn = G - lmd; T1 wpd = w_prev[idx] + D[idx]; T1 Hwd = Hii * wpd; T1 z = -wpd; if (Gp <= Hwd) z = -Gp/Hii; if (Gn >= Hwd) z = -Gn/Hii; D[idx] = D[idx] + z; for (unsigned long k = Q_idx_m, j = 0; j < m; j++) d_bar[j] += z*Q_bar[k+j]; diffd += fabs(z); normd += fabs(D[idx]); } if (msgFlag >= LHAC_MSG_CD) { printf("\t\t Coordinate descent pass %ld: Change in d = %+.4e norm(d) = %+.4e\n", cd_pass, diffd, normd); } } return D; }; private: /* own */ T1* D; T1* d_bar; T1* H_diag; T1* Q; T1* Q_bar; T1* L_grad; T1* buffer; unsigned long* permut; ushort_pair_t* idxs; T1 lmd; T1 gama0; unsigned long cd_rate; unsigned long l; unsigned long numActive; int msgFlag; unsigned long p; unsigned short m; }; template <typename Derived, typename T1> class LHAC { public: LHAC(Objective<Derived, T1>* _mdl, const Parameter* const _param) : mdl(_mdl), param(_param) { p = mdl->getDims(); obj = new Func; l = param->l; opt_outer_tol = param->opt_outer_tol; max_iter = param->max_iter; lmd = param->lmd; msgFlag = param->verbose; w_prev = new T1[p]; w = new T1[p]; L_grad_prev = new T1[p]; L_grad = new T1[p]; D = new T1[p]; H_diag = new T1[p]; // p d_bar = new T1[2*param->l]; // 2*l /* initiate */ if (_param->w_initial == NULL) { memset(w, 0, p*sizeof(T1)); memset(w_prev, 0, p*sizeof(T1)); } else { for (size_t i = 0; i < p; ++i) w[i] = (T1) _param->w_initial[i]; // w_prev is set in initialStep() } memset(D, 0, p*sizeof(T1)); sols = new Solution<T1>(max_iter, p); work_set = new work_set_struct(p); lR = new LBFGS<T1>(p, l, (T1) param->shrink); ista_size = (T1) _param->stepsize_initial; }; ~LHAC() { delete [] w_prev; delete [] w; delete [] L_grad; delete [] L_grad_prev; delete [] D; delete [] H_diag; delete [] d_bar; delete lR; delete work_set; } int ista() { T1 elapsedTimeBegin = CFAbsoluteTimeGetCurrent(); int error = 0; normsg = normsg0; for (ista_iter = 1; ista_iter <= max_iter; ista_iter++) { error = istaStep(); if (error) { break; } T1 elapsedTime = CFAbsoluteTimeGetCurrent()-elapsedTimeBegin; if (ista_iter == 1 || ista_iter % 30 == 0 ) sols->addEntry(obj->val, normsg, elapsedTime, ista_iter, work_set->numActive); if (msgFlag >= LHAC_MSG_NEWTON) printf("%.4e iter %3d: obj.f = %+.4e obj.normsg = %+.4e\n", elapsedTime, ista_iter, obj->f, normsg); normsg = computeSubgradient(); mdl->computeGradient(w, L_grad); if (normsg <= opt_outer_tol*normsg0) { break; } } return error; } // proximal inexact quasi-newton int piqn() { T1 elapsedTimeBegin = CFAbsoluteTimeGetCurrent(); initialStep(); int error = 0; for (newton_iter = 1; newton_iter < max_iter; newton_iter++) { computeWorkSet(); lR->computeLowRankApprox_v2(work_set); T1 elapsedTime = CFAbsoluteTimeGetCurrent()-elapsedTimeBegin; normsg = computeSubgradient(); if (msgFlag >= LHAC_MSG_NEWTON) printf("%.4e iter %3d: obj.f = %+.4e obj.normsg = %+.4e |work_set| = %ld\n", elapsedTime, newton_iter, obj->f, normsg, work_set->numActive); sols->addEntry(obj->val, normsg, elapsedTime, newton_iter, work_set->numActive); if (normsg <= opt_outer_tol*normsg0) { break; } error = suffcientDecrease(); if (error) { break; } memcpy(L_grad_prev, L_grad, p*sizeof(T1)); mdl->computeGradient(w, L_grad); /* update LBFGS */ lR->updateLBFGS(w, w_prev, L_grad, L_grad_prev); } return error; } template <typename InnerSolver> int piqnGeneral(Subproblem<InnerSolver, T1>* subprob) { double elapsedTimeBegin = CFAbsoluteTimeGetCurrent(); initialStep(); int error = 0; unsigned short max_inner_iter = 200; for (newton_iter = 1; newton_iter < max_iter; newton_iter++) { computeWorkSet(); lR->computeLowRankApprox_v2(work_set); double elapsedTime = CFAbsoluteTimeGetCurrent()-elapsedTimeBegin; normsg = computeSubgradient(); if (msgFlag >= LHAC_MSG_NEWTON) printf("%.4e iter %3d: obj.f = %+.4e obj.normsg = %+.4e |work_set| = %ld\n", elapsedTime, newton_iter, obj->f, normsg, work_set->numActive); sols->addEntry(obj->val, normsg, elapsedTime, newton_iter, work_set->numActive); if (normsg <= opt_outer_tol*normsg0) { break; } /* inner solver starts*/ subprob->build(lR, L_grad, work_set); T1 gama = lR->gama; T1 rho_trial = 0.0; memcpy(w_prev, w, p*sizeof(T1)); unsigned short inner_iter; for (inner_iter = 0; inner_iter < max_inner_iter; inner_iter++) { const T1* d = subprob->solve(w_prev, newton_iter, gama); bool good_d = sufficientDecreaseCheck(d, subprob, gama, &rho_trial); if (good_d) { if (msgFlag >= LHAC_MSG_SD) printf("\t \t \t # of line searches = %3d; model quality: %+.3f\n", inner_iter, rho_trial); break; } else gama *= 2.0; } /* inner solver ends */ if (inner_iter >= max_inner_iter) { error = 1; break; } memcpy(L_grad_prev, L_grad, p*sizeof(T1)); mdl->computeGradient(w, L_grad); /* update LBFGS */ lR->updateLBFGS(w, w_prev, L_grad, L_grad_prev); } return error; } /* fast proximal inexact quasi-newton */ int fpiqn() { T1 elapsedTimeBegin = CFAbsoluteTimeGetCurrent(); initialStep(); T1 t = 1.0; int error = 0; T1* x = new T1[p]; memcpy(x, w, p*sizeof(T1)); // w_1 (y_1) == x_0 for (newton_iter = 1; newton_iter < max_iter; newton_iter++) { computeWorkSet(); lR->computeLowRankApprox_v2(work_set); T1 elapsedTime = CFAbsoluteTimeGetCurrent()-elapsedTimeBegin; normsg = computeSubgradient(); if (msgFlag >= LHAC_MSG_NEWTON) printf("%.4e iter %3d: obj.f = %+.4e obj.normsg = %+.4e |work_set| = %ld\n", elapsedTime, newton_iter, obj->f, normsg, work_set->numActive); sols->addEntry(obj->val, normsg, elapsedTime, newton_iter, work_set->numActive); if (normsg <= opt_outer_tol*normsg0) { break; } error = suffcientDecrease(); if (error) { break; } fistaUpdate(&t, x); obj->add(mdl->computeObject(w), computeReg(w)); memcpy(L_grad_prev, L_grad, p*sizeof(T1)); mdl->computeGradient(w, L_grad); /* update LBFGS */ lR->updateLBFGS(w, w_prev, L_grad, L_grad_prev); } return error; } Solution<T1>* solve() { obj->add(mdl->computeObject(w), computeReg(w)); mdl->computeGradient(w, L_grad); normsg0 = computeSubgradient(); int error = 0; switch (param->method_flag) { case 1: error = ista(); break; case 2: error = piqn(); break; case 3: error = fpiqn(); break; case 4: error = piqnGeneral(new CoordinateDescent<T1>(param, p)); break; default: error = 1; fprintf(stderr, "ValueError: flag q only accept value 1 (ISTA), 2 (lhac) or 3 (f-lhac).\n"); break; } sols->finalReport(error, w); return sols; }; private: Objective<Derived, T1>* mdl; const Parameter* param; Solution<T1>* sols; work_set_struct* work_set; Func* obj; LBFGS<T1>* lR; unsigned long l; T1 opt_outer_tol; unsigned short max_iter; T1 lmd; int msgFlag; unsigned long p; unsigned short newton_iter; unsigned short ista_iter; T1 ista_size; T1* D; T1 normsg0; T1 normsg; T1* w_prev; T1* w; T1* L_grad_prev; T1* L_grad; T1* H_diag; // p T1* d_bar; // 2*l void initialStep() { // initial step (only for l1) // for (unsigned long idx = 0; idx < p; idx++) { // T1 G = L_grad[idx]; // T1 Gp = G + lmd; // T1 Gn = G - lmd; // T1 Hwd = 0.0; // if (Gp <= Hwd) // D[idx] = -Gp; // else if (Gn >= Hwd) // D[idx] = -Gn; // else // D[idx] = 0.0; // } // T1 a = 1.0; // T1 l1_next = 0.0; // T1 delta = 0.0; // for (unsigned long i = 0; i < p; i++) { // w[i] += D[i]; // l1_next += lmd*fabs(w[i]); // delta += L_grad[i]*D[i]; // } // delta += l1_next - obj->g; // // line search // for (unsigned long lineiter = 0; lineiter < 1000; lineiter++) { // T1 f_trial = mdl->computeObject(w); // T1 obj_trial = f_trial + l1_next; // if (obj_trial < obj->val + a*0.001*delta) { // obj->add(f_trial, l1_next); // break; // } // a = 0.5*a; // l1_next = 0; // for (unsigned long i = 0; i < p; i++) { // w[i] = w_prev[i] + a*D[i]; // l1_next += lmd*fabs(w[i]); // } // } istaStep(); memcpy(L_grad_prev, L_grad, p*sizeof(T1)); mdl->computeGradient(w, L_grad); lR->initData(w, w_prev, L_grad, L_grad_prev); } int istaStep() { printf("Finding the proper initial step size...\n"); memcpy(w_prev, w, p*sizeof(T1)); for (int backtrack=0; backtrack<200; backtrack++) { T1 t = ista_size*lmd; unsigned long i; #pragma omp parallel for private(i) for (i = 0; i < p; i++) { T1 ui = w_prev[i] - ista_size*L_grad[i]; if (ui > t) w[i] = ui - t; else if (ui < -t) w[i] = ui + t; else w[i] = 0.0; D[i] = w[i] - w_prev[i]; } T1 order1 = lcddot((int)p, D, 1, L_grad, 1); T1 order2 = lcddot((int)p, D, 1, D, 1); T1 f_trial = mdl->computeObject(w); if (f_trial > obj->f + order1 + (0.5/ista_size)*order2) { ista_size = ista_size * 0.5; continue; } printf("SET initial step size to %f\n", ista_size); obj->add(f_trial, 0); return 0; } return 1; } void fistaUpdate(T1* const t, T1* const x) { T1 t_ = *t; *t = (1 + sqrt(1+4*t_*t_))*0.5; T1 c = (t_ - 1) / *t; for (unsigned long i = 0; i < p; i++) { T1 yi = w[i] + c*(w[i] - x[i]); // x is x_{k-1} x[i] = w[i]; w[i] = yi; } } /* may generalize to other regularizations beyond l1 */ T1 computeReg(const T1* const wnew) { T1 gval = 0.0; for (unsigned long i = 0; i < p; i++) gval += lmd*fabs(wnew[i]); return gval; } T1 computeSubgradient() { T1 subgrad = 0.0; for (unsigned long i = 0; i < p; i++) { T1 g = L_grad[i]; if (w[i] != 0.0 || (fabs(g) > lmd)) { if (w[i] > 0) g += lmd; else if (w[i] < 0) g -= lmd; else g = fabs(g) - lmd; subgrad += fabs(g); } } return subgrad; } static int _cmp_by_vlt(const void *a, const void *b) { const ushort_pair_t *ia = (ushort_pair_t *)a; const ushort_pair_t *ib = (ushort_pair_t *)b; if (ib->vlt - ia->vlt > 0) { return 1; } else if (ib->vlt - ia->vlt < 0){ return -1; } else return 0; } static int _cmp_by_vlt_reverse(const void *a, const void *b) { const ushort_pair_t *ia = (ushort_pair_t *)a; const ushort_pair_t *ib = (ushort_pair_t *)b; if (ib->vlt - ia->vlt > 0) { return -1; } else if (ib->vlt - ia->vlt < 0){ return 1; } else return 0; } void computeWorkSet() { switch (param->active_set) { case GREEDY: greedySelector(); break; case STD: stdSelector(); break; case STD_CUTGRAD: stdSelector_cutgrad(); break; case STD_CUTGRAD_AGGRESSIVE: stdSelector_cutgrad_aggressive(); break; case GREEDY_CUTGRAD: greedySelector(); break; case GREEDY_CUTZERO: greedySelector_cutzero(); break; case GREEDY_ADDZERO: greedySelector_addzero(); break; default: stdSelector(); break; } /* reset permutation */ for (unsigned long j = 0; j < work_set->numActive; j++) { work_set->permut[j] = j; } return; } void stdSelector() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; /*** select rule 2 ***/ for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd)) { idxs[numActive].i = (unsigned short) j; idxs[numActive].j = (unsigned short) j; numActive++; } } work_set->numActive = numActive; return; } void stdSelector_cutgrad() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; /*** select rule 2 ***/ for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd + 0.01)) { idxs[numActive].i = (unsigned short) j; idxs[numActive].j = (unsigned short) j; numActive++; } } work_set->numActive = numActive; return; } void stdSelector_cutgrad_aggressive() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; /*** select rule 2 ***/ for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd + 0.5)) { idxs[numActive].i = (unsigned short) j; idxs[numActive].j = (unsigned short) j; numActive++; } } work_set->numActive = numActive; return; } void greedySelector() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; unsigned long zeroActive = 0; for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd)) { idxs[numActive].i = (unsigned short) j; idxs[numActive].j = (unsigned short) j; g = fabs(g) - lmd; idxs[numActive].vlt = fabs(g); numActive++; if (w[j] == 0.0) zeroActive++; } } qsort((void *)idxs, (size_t) numActive, sizeof(ushort_pair_t), _cmp_by_vlt); work_set->numActive = numActive; } void greedySelector_cutgrad() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; unsigned long zeroActive = 0; for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd + 0.01)) { idxs[numActive].i = (unsigned short) j; idxs[numActive].j = (unsigned short) j; g = fabs(g) - lmd; idxs[numActive].vlt = fabs(g); numActive++; if (w[j] == 0.0) zeroActive++; } } qsort((void *)idxs, (size_t) numActive, sizeof(ushort_pair_t), _cmp_by_vlt); work_set->numActive = numActive; } void greedySelector_cutzero() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; unsigned long zeroActive = 0; for (unsigned long j = 0; j < p; j++) { T1 g = L_grad[j]; if (w[j] != 0.0 || (fabs(g) > lmd)) { idxs[numActive].i = j; idxs[numActive].j = j; g = fabs(g) - lmd; idxs[numActive].vlt = fabs(g); numActive++; if (w[j] == 0.0) zeroActive++; } } qsort((void *)idxs, (size_t) numActive, sizeof(ushort_pair_t), _cmp_by_vlt); // zerosActive small means found the nonzeros subspace numActive = (zeroActive<100)?numActive:(numActive-zeroActive); work_set->numActive = numActive; } void _insert(unsigned long idx, T1 vlt, unsigned long n) { ushort_pair_t* &idxs = work_set->idxs; unsigned long end = p-1-n; unsigned long j; for (j = p-1; j > end; j--) { if (idxs[j].vlt >= vlt) continue; else { for (unsigned long i = j+1, k = j; i > end; i--, k--) { // swap unsigned long tmpj = idxs[k].j; T1 tmpv = idxs[k].vlt; idxs[k].j = idx; idxs[k].vlt = vlt; vlt = tmpv; idx = tmpj; } break; } } if (j == end) { idxs[end].j = idx; idxs[end].vlt = vlt; } } T1 _vlt(unsigned long j) { T1 g = L_grad[j]; if (w[j] > 0) g += lmd; else if (w[j] < 0) g -= lmd; else g = fabs(g) - lmd; return g; } /* not converging on a9a */ void greedySelector_addzero_no() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; unsigned long work_size = param->work_size; unsigned long zeroActive = 0; unsigned long nzeroActive = 0; for (unsigned long j = 0; j < p; j++) { T1 g = fabs(L_grad[j]) - lmd; if (g > 0) { unsigned long end = p-1-zeroActive; idxs[end].j = j; idxs[end].vlt = g; zeroActive++; } else if (w[j] != 0.0) { idxs[nzeroActive].j = j; nzeroActive++; } } if (zeroActive>2*nzeroActive) { unsigned long pos = p - zeroActive; qsort((void *)(idxs+pos), (size_t) zeroActive, sizeof(ushort_pair_t), _cmp_by_vlt_reverse); work_size = (nzeroActive<10)?zeroActive/3:nzeroActive; } else work_size = zeroActive; numActive = nzeroActive; unsigned long end = p-work_size; for (unsigned long j = p-1; j >= end; j--) { idxs[numActive].j = idxs[j].j; numActive++; } work_set->numActive = numActive; } void greedySelector_addzero() { ushort_pair_t* &idxs = work_set->idxs; unsigned long numActive = 0; unsigned long work_size = param->work_size; unsigned long zeroActive = 0; unsigned long nzeroActive = 0; for (unsigned long j = 0; j < p; j++) { T1 g = fabs(L_grad[j]) - lmd; if (g > 0) { _insert(j, g, zeroActive); zeroActive++; } else if (w[j] != 0.0) { idxs[nzeroActive].j = j; nzeroActive++; } } work_size = (nzeroActive<10)?zeroActive:nzeroActive; work_size = (zeroActive>2*nzeroActive)?work_size:zeroActive; numActive = nzeroActive; unsigned long end = p-work_size; for (unsigned long k = p, j = p-1; k > end; k--, j--) { idxs[numActive].j = idxs[j].j; numActive++; } work_set->numActive = numActive; } static inline void shuffle( work_set_struct* work_set ) { unsigned long lens = work_set->numActive; ushort_pair_t* idxs = work_set->idxs; unsigned long* permut = work_set->permut; for (unsigned long i = 0; i < lens; i++) { unsigned long j = i + rand()%(lens - i); unsigned short k1 = idxs[i].i; unsigned short k2 = idxs[i].j; T1 vlt = idxs[i].vlt; idxs[i].i = idxs[j].i; idxs[i].j = idxs[j].j; idxs[i].vlt = idxs[j].vlt; idxs[j].i = k1; idxs[j].j = k2; idxs[j].vlt = vlt; /* update permutation */ unsigned long tmp = permut[i]; permut[i] = permut[j]; permut[j] = tmp; } return; } int suffcientDecrease() { int max_sd_iters = 200; T1 mu = 1.0; T1 rho = param->rho; int msgFlag = param->verbose; memcpy(w_prev, w, p*sizeof(T1)); const T1 lmd = param->lmd; const unsigned long l = param->l; T1* Q = lR->Q; const T1* Q_bar = lR->Q_bar; const unsigned short m = lR->m; const T1 gama = lR->gama; memset(D, 0, p*sizeof(T1)); memset(d_bar, 0, 2*l*sizeof(T1)); for (unsigned long k = 0, i = 0; i < work_set->numActive; i++, k += m) { H_diag[i] = gama; for (unsigned long j = 0; j < m; j++) H_diag[i] -= Q_bar[k+j]*Q[k+j]; } unsigned long max_cd_pass = 1 + newton_iter / param->cd_rate; unsigned long* permut = work_set->permut; ushort_pair_t* idxs = work_set->idxs; unsigned long cd_pass; int sd_iters; for (sd_iters = 0; sd_iters < max_sd_iters; sd_iters++) { T1 gama_scale = mu*gama; T1 dH_diag = gama_scale-gama; for (cd_pass = 1; cd_pass <= max_cd_pass; cd_pass++) { T1 diffd = 0; T1 normd = 0; for (unsigned long ii = 0; ii < work_set->numActive; ii++) { unsigned long rii = ii; unsigned long idx = idxs[rii].j; unsigned long idx_Q = permut[rii]; unsigned long Q_idx_m = idx_Q*m; T1 Qd_bar = lcddot(m, &Q[Q_idx_m], 1, d_bar, 1); T1 Hd_j = gama_scale*D[idx] - Qd_bar; T1 Hii = H_diag[idx_Q] + dH_diag; T1 G = Hd_j + L_grad[idx]; T1 Gp = G + lmd; T1 Gn = G - lmd; T1 wpd = w_prev[idx] + D[idx]; T1 Hwd = Hii * wpd; T1 z = -wpd; if (Gp <= Hwd) z = -Gp/Hii; if (Gn >= Hwd) z = -Gn/Hii; D[idx] = D[idx] + z; for (unsigned long k = Q_idx_m, j = 0; j < m; j++) d_bar[j] += z*Q_bar[k+j]; diffd += fabs(z); normd += fabs(D[idx]); } if (msgFlag >= LHAC_MSG_CD) { printf("\t\t Coordinate descent pass %ld: Change in d = %+.4e norm(d) = %+.4e\n", cd_pass, diffd, normd); } } for (unsigned long i = 0; i < p; i++) { w[i] = w_prev[i] + D[i]; } T1 f_trial = mdl->computeObject(w); T1 g_trial = computeReg(w); T1 obj_trial = f_trial + g_trial; T1 order1 = lcddot((int)p, D, 1, L_grad, 1); T1 order2 = 0; T1* buffer = lR->buff; int cblas_M = (int) work_set->numActive; int cblas_N = (int) m; lcdgemv(CblasColMajor, CblasTrans, Q, d_bar, buffer, cblas_N, cblas_M, cblas_N); T1 vp = 0; for (unsigned long ii = 0; ii < work_set->numActive; ii++) { unsigned long idx = idxs[ii].j; unsigned long idx_Q = permut[ii]; vp += D[idx]*buffer[idx_Q]; } order2 = mu*gama*lcddot((int)p, D, 1, D, 1)-vp; order2 = order2*0.5; T1 f_mdl = obj->f + order1 + order2 + g_trial; T1 rho_trial = (obj_trial-obj->val)/(f_mdl-obj->val); if (msgFlag >= LHAC_MSG_SD) { printf("\t \t \t # of line searches = %3d; model quality: %+.3f\n", sd_iters, rho_trial); } if (rho_trial > rho) { obj->add(f_trial, g_trial); break; } mu = 2*mu; } if (sd_iters == max_sd_iters) { fprintf(stderr, "failed to satisfy sufficient decrease condition.\n"); return -1; } return 0; } template <typename InnerSolver> bool sufficientDecreaseCheck(const T1* D, Subproblem<InnerSolver, T1>* const subprob, const T1 gama, T1* rho_trial) { for (unsigned long i = 0; i < p; i++) { w[i] = w_prev[i] + D[i]; } T1 f_trial = mdl->computeObject(w); T1 g_trial = computeReg(w); T1 obj_trial = f_trial + g_trial; T1 f_mdl = obj->f + subprob->objective_value(gama) + g_trial; *rho_trial = (obj_trial-obj->val)/(f_mdl-obj->val); if (*rho_trial > param->rho) { obj->add(f_trial, g_trial); return true; } return false; } }; #endif /* defined(__LHAC_v1__lhac__) */
deconvolution_pack1ton.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 deconvolution_pack1ton_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_pack1ton, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; const int maxk = kernel_w * kernel_h; const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat32m1_t _sum = vfmv_v_f_f32m1(0.f, vl); if (bias_data_ptr) { _sum = vle32_v_f32m1(bias_data_ptr + p * packn, vl); } const float* kptr = (const float*)weight_data_pack1ton + maxk * channels * p * packn; // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); for (int y = 0; y < kernel_h; y++) { int sys = (i + y * dilation_h - (kernel_extent_h - 1)); if (sys < 0 || sys % stride_h != 0) continue; int sy = sys / stride_h; if (sy >= h) continue; const float* sptr = m.row(sy); for (int x = 0; x < kernel_w; x++) { int sxs = (j + x * dilation_w - (kernel_extent_w - 1)); if (sxs < 0 || sxs % stride_w != 0) continue; int sx = sxs / stride_w; if (sx >= w) continue; float val = sptr[sx]; int k = y * kernel_w + x; vfloat32m1_t _w = vle32_v_f32m1(kptr + k * packn, vl); _sum = vfmacc_vf_f32m1(_sum, val, _w, vl); } } kptr += maxk * packn; } _sum = activation_ps(_sum, activation_type, activation_params, vl); vse32_v_f32m1(outptr + j * packn, _sum, vl); } outptr += outw * packn; } } }
#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 <iostream> #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);//params.sorted indices_to_ids(indices[i], indices[i], n); count += n; } } } else { //#pragma omp parallel num_threads(params.cores) { //this way 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
omp_sum_strnum_tls.c
/* vim: set ts=4 sw=4: */ /* Filename : omp_sum_strnum_tls.c * Description : OpenMP TLS * Author : SunYoung Kim <sunyzero@gmail.com> * Notes : */ #define _XOPEN_SOURCE 600 #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <omp.h> #include "stdalsp.h" #define LEN_SUM_STR 16 char *sum_strnum(const char *, const char *); int main() { omp_set_num_threads(4); #pragma omp parallel sections { #pragma omp section { char *x = "1", *y = "3"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); } #pragma omp section { char *x = "4", *y = "4"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); } #pragma omp section { char *x = "1", *y = "5"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); } } /* omp parallel, sections */ return EXIT_SUCCESS; } char *sum_strnum(const char *s1, const char *s2) { static char tls_str[LEN_SUM_STR]; #pragma omp threadprivate(tls_str) snprintf(tls_str, LEN_SUM_STR, "%d", atoi(s1) + atoi(s2)); return tls_str; }
morph_library.h
#include "../include/CImgFloatWrapper.h" #include "../loewner_morphology.h" #include "omp.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <thread> #define THREADS_X 16 #define THREADS_Y 16 #define TILE_X 16 #define TILE_Y 16 #define BLOCK_SIZE 256 #define CONSTANT_SIZE 1024 #define OMP_THREAD_NUM 8 #define NUM_STREAMS 4 #define first(idx, n, dim) (((idx) * (dim)) / (n)) #define last(idx, n, dim) ((first(idx + 1, n, dim)) - 1) #define size(idx, n, dim) ((last(idx, n, dim)) - (first(idx, n, dim)) + 1) int __constant__ maskMemory[CONSTANT_SIZE]; // constant memroy array cudaStream_t streams[NUM_STREAMS]; // cuda streams typedef LoewnerMorphology::MorphCircle Circle; /* *============================================================================================================== * Class that contains morphological operations which are introduced in the paper of B. Burgeth and A. Kleefeld *============================================================================================================== */ class LoewnerMorphology::Morph { public: /* * Constructor of the class Morph. It takes name of the file where image is stored, name of the file where mask (structural element) is stored * and dimension of the mask as arguments. */ Morph(const char *imageFile, const char *maskFile, int maskDim); /* * Destructor of the class Morph. */ ~Morph(); // MORPHOLOGICAL OPERATION /* * Performs morphological opration dilation on the input image. */ void dilation(int iter = 1); /* * Performs morphological operation erosion on the input image. */ void erosion(int iter = 1); /* * Performs morphological operation closing on the input image. */ void closing(int iter = 1); /* * Performs morphological operation opening on the input image. */ void opening(int iter = 1); /* * Performs morphological operation black top hat on the input image. */ void blackTopHat(int iter = 1); /* * Performs morphological operation white top hat on the input image. */ void whiteTopHat(int iter = 1); /* * Performs morphological operation self-dual top hat on the input image. */ void selfDualTopHat(int iter = 1); /* * Performs morphological operation beucher gradient on the input image. */ void beucherGradient(int iter = 1); /* * Performs morphological operation internal gradient on the input image. */ void externalGradient(int iter = 1); /* * Performs morphological operation internal gradient on the input image. */ void internalGradient(int iter = 1); /* * Performs morphological operation morphological laplacian on the input image. */ void laplacian(int iter = 1); /* * Performs morphological operation shock filter on the input image. */ void shockFilter(int iter = 1); /* * Displays original image. */ void displayOriginalImage(); /* * Displays result of the morphological operation if the operation is called. */ void displayResultImage(); /* * Returns result image as an array of floats. It allocates memory equal to the size of the image times spectrum. */ float *returnResult(); /* * Saves result to the file which name is provided. */ void saveResult(const char *fileName); private: CImgFloatWrapper *inputImage; // input image CImgFloatWrapper *outputImage; // output image - after morphological operation int *mask; // mask array int padding; // mask padding LoewnerMorphology::MorphColorMatrix *matrices; // input image converted to array of MorphColorMatrix objects LoewnerMorphology::MorphColorMatrix *result; // result image converted to array of MorphColorMatrix objects int width; // width of the image int height; // height of the image int spectrum; // spectrum of the image int size; // size of the image // HANDLERS /* * Invokes GPU kernel for performing modified Einstein subtraction of two given image vectors in device memory. * Kernel is launched without further synchronization. Width and height are the dimensions of the original image. * Since image1 and image2 are image matrices stored in row-major vectorized format, one should provide lda for each of them. */ template<typename T> static void morph_einstein_async(T *image1, T *image2, int width, int height, int lda1, int lda2, cudaStream_t stream = 0); /* * Method that copies original image stored on memory location in to device pointer dev_out2, performs modified Einstein substraction * between images stored on device on locations dev_out1 and dev_out2 and then copies the result to host on memory location out. * Type of the subtraction is determined by template parameter type. If the type parameter is false, dev_out2 will be subtracted from * dev_out1, if the type parameter is true, dev_out1 will be subtracted from dev_out2 in terms of Einstein subtraction. The operation * is performed asynchronusely with N streams. Method does not do explicit synchronizations. */ template<typename T, bool type, int N> static void morph_einstein_copy_original_launcher(T *dev_out1, T *dev_out2, T *in, T *out, int width, int height, cudaStream_t *streams); /* * Method modified Einstein substraction between images stored on device on locations dev_out1 and dev_out2 and then copies the result * to host on memory location out. More precisely, dev_out2 will be subtracted from dev_out2 will be subtracted from dev_out1 in terms of Einstein subtraction. The operation * is performed asynchronusely with N streams. Method does not do explicit synchronizations. */ template<typename T, int N> static void morph_einstein_copy_launcher(T *dev_out1, T *dev_out2, T *out, int width, int height, cudaStream_t *streams); /* * Method that invokes the kernels for basic morphological operations. Morphological operation is determined with template parameter type. If it is false, dilation * is performed, in the other case, erosion is performed. Arguments dev_in and dev_out are device pointers. On the location dev_in there is * an array of size (pWidth + 2 * padding) * (pHeight + 2 * padding) containing image information with appropriate padding converthed to type T. Pointer dev_out contains preallocated * memory for the result image. Size of the allocated memory is width * height where width and height are initial image dimensions. Also, pWidth and pHeight are expected to be calculated like this: * pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X and pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y. Padding is appropriate mask padding. * It is calculated as mask dimension / 2 where / is integer division. The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * Also, sheared memory size in bytes should be provided. On host memory location in, original image converted to type T must be stored. */ template<typename T, bool type> static void morph_basic_launcher(T *dev_in, T *dev_out, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream = 0); /* * Method that invokes the kernels for morphological operation shockfilter. Arguments dev_in and dev_out are device pointers. On the location dev_in there is * an array of size (pWidth + 2 * padding) * (pHeight + 2 * padding) containing image information with appropriate padding converthed to type T. Pointer dev_out contains preallocated * memory for the result image. Size of the allocated memory is width * height where width and height are initial image dimensions. Also, pWidth and pHeight are expected to be calculated like this: * pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X and pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y. Padding is appropriate mask padding. * It is calculated as mask dimension / 2 where / is integer division. The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * Also, sheared memory size in bytes should be provided. On host memory location in, original image converted to type T must be stored. However, on device memory location laplacian, morphological * laplacian of the original image has to be stored. */ template<typename T> static void morph_shock_launcher(T *dev_in1, T* dev_in2, T *dev_out, T *laplacian, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream = 0); /* * Invokes GPU kernel responsible for perfoming wanted basic morphological operation on given image vector. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask. For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * * Template parameter type determines morphological operation: * 1) false -> DILATION * 2) true -> EROSION */ template<typename T, bool type> static void morph_basic(T *in, T *out, int width, int height, int padding); /* * Invokes GPU kernel responsible for perfoming wanted basic morphological operation on given image vector. Input vector dev_in is expected to be an image matrix on GPU memory containing objects * of type T as elements. The vector containing the image matrix must have size size (pWidth + 2 * padding) * (pHeight + 2 * padding). Argument padding is a padding of the given mask. For example, * if mask has dimensions 5x5, padding is 2. Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, * solving Smallest enclosing circle of circles problem. The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * Also, shared memory size in bytes needs to be provided, as well as original image vector in host memory which elements are converted to type T on memory location in. * * Template parameter type determines morphological operation: * 1) false -> CLOSING * 2) true -> OPENING */ template<typename T, bool type> static void morph_second_order_launcher(T *dev_in, T *dev_out, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream = 0); /* * Invokes GPU kernel responsible for perfoming wanted higher order morphological operation on given image vector. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * * Template parameter type determines morphological operation: * 1) false -> CLOSING * 2) true -> OPENING */ template<typename T, bool type> static void morph_second_order(T *in, T *out, int width, int height, int padding); /* * Invokes GPU kernel responsible for perfoming morphological operations white top hat and black top hat on given image vector. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * * Template parameter type determines morphological operation: * 1) false -> BLACK TOP HAT * 2) true -> WHITE TOP HAT */ template<typename T, bool type> static void morph_hats(T *in, T *out, int width, int height, int padding); /* * Invokes GPU kernel responsible for perfoming morphological operation Beucher gradient on given image vector. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. */ template<typename T> static void morph_beucher(T *in, T *out, int width, int height, int padding, int *mask); /* * Invokes GPU kernel responsible for perfoming morphological operations self dual top hat on given image vector. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. */ template<typename T> static void morph_sdth(T *in, T *out, int width, int height, int padding, int *mask); /* * Invokes GPU kernel responsible for perfoming morphological operations internal gradient and external gradient on given image vector. Input vector in is expected to be an image matrix containing * objects of type T as elements. The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has * dimensions 5x5, padding is 2. Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving * smallest circle problem. The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. * * Template parameter type determines morphological operation: * 1) false -> EXTERNAL GRADIENT * 2) true -> INTERNAL GRADIENT */ template<typename T, bool type> static void morph_gradients(T *in, T *out, int width, int height, int padding); /* * Invokes GPU kernel responsible for perfoming morphological operation morphological Laplacian. Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. */ template<typename T> static void morph_laplacian(T *in, T *out, int width, int height, int padding, int *mask); /* * Invokes GPU kernel responsible for perfoming morphological operation shock-filter Input vector in is expected to be an image matrix containing objects of type T as elements. * The vector containing the image matrix must have size width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Output vector's size has to be width * height. Morphological operations are performed as explained in the paper, elements are compared using Loewner order, solving smallest circle problem. * The type T should support the conversion to the type MorphCircle. In the other words, constructor MorphCircle(&T) must exist. */ template<typename T> static void morph_shock(T *in, T *out, int width, int height, int padding, int *mask); /* * Basic handle for invoking launcher methods which are invoking GPU kernels for performing all morphological operations introduced in the paper from B. Burgeth and A. Kleefeld. Pointers in and out * must be host pointer. Memory location in must contain original image matrix which elements are converted to the type T. Result of the selected morphological operation will be stored on memory location * out. This memory location should be preallocated to the size of width * height. Argument padding is a padding of the given mask (structural element). For example, if mask has dimensions 5x5, padding is 2. * Argument iters defines number of iterations. * * Morphological operation is determined by morphType argument: * 0) DILATION * 1) EROSION * 2) CLOSING * 3) OPENING * 4) BLACK TOP HAT * 5) WHITE TOP HAT * 6) SELF-DUAL TOP HAT * 7) BEUCHER GRADIENT * 8) EXTERNAL GRADIENT * 9) INTERNAL GRADIENT * 10) MORPHOLOGICAL LAPLACIAN * 11) SHOCK FILTER */ template<typename T> static void morph_handle(T *in, T *out, int width, int height, int padding, int *mask, int morphType, int iters = 0); // HELPER METHODS /* * Helper method that creates output image (CImgFloatWrapper object) from an array of MorphColorMatrix objects result stored as a class variable. */ void createOutputImage(); /* * Helper method for copying one array to another. */ template<typename T> static void copy(T *in, T *out, int size); /* * Helper method that prepares grid for fill kernel. */ static inline void prepareGrid1(dim3 &gridDim, dim3 &blockDim, int height); /* * Helper method that prepares grid for the morph kernel. Arguments pWidth and pHeight must be multiples of THREADS_X and THREADS_Y constants, respectively. * Morpe precisely, pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X and pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y. */ static inline void prepareGrid2(dim3 &gridDim, dim3 &blockDim, int pWidth, int pHeight); /* * Helper method that prepares grid for einstein kernel. */ static inline void prepareGrid3(dim3 &gridDim, dim3 &blockDim, int width, int height); /* * Reading mask from a file specified by given string. Also, mask dimension needs to be provided. Mask * is expected to be a maskDim * maskDim matrix containing only 0 and 1. */ static void readMaskFromFile(int *maskPointer, int maskDim, const char *fileName); // DEBUGGING /* * Helper method for printing matrix of MorphCircle objects to the standard output. * Used for debbugging. */ static void __host__ __device__ print_shared_vector(Circle *in, int width, int height, int lda); /* * Helper method for printing matrix of MorphColorMatrix objects to the standard output. * Used for debbugging. */ static void __host__ __device__ print_shared_vector(LoewnerMorphology::MorphColorMatrix *in, int width, int height, int lda); /* * Helper method for printing matrix of floats to the standard output. * Used for debbugging. */ static void __host__ __device__ print_shared_vector(float *in, int width, int height, int lda); }; void LoewnerMorphology::Morph::readMaskFromFile(int *maskPointer, int maskDim, const char *fileName) { FILE *file = NULL; open_file(file, fileName, "r"); for (int i = 0, n = maskDim * maskDim; i < n; i++) { if (fscanf(file, "%d", maskPointer + i) != 1) { printf("Error while reading file %s.\n", fileName); exit(EXIT_FAILURE); } } close_file(file, fileName); } void __host__ __device__ LoewnerMorphology::Morph::print_shared_vector(Circle *in, int width, int height, int lda) { Circle *current = in; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { current[j].print(); printf(" "); } printf("\n"); current += lda; } } void __host__ __device__ LoewnerMorphology::Morph::print_shared_vector(float *in, int width, int height, int lda) { float *current = in; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { printf("%5.2f ", current[j]); } printf("\n"); current += lda; } } void __host__ __device__ LoewnerMorphology::Morph::print_shared_vector(LoewnerMorphology::MorphColorMatrix *in, int width, int height, int lda) { MorphColorMatrix *current = in; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { current[j].printMorphColorMatrix(); printf(" "); } printf("\n"); current += lda; } } inline void LoewnerMorphology::Morph::prepareGrid1(dim3 &gridDim, dim3 &blockDim, int height) { blockDim.x = BLOCK_SIZE; blockDim.y = 1; gridDim.x = 1; gridDim.y = height; } inline void LoewnerMorphology::Morph::prepareGrid2(dim3 &gridDim, dim3 &blockDim, int pWidth, int pHeight) { blockDim.x = THREADS_X; blockDim.y = THREADS_Y; gridDim.x = pWidth / THREADS_X; gridDim.y = pHeight / THREADS_Y; } inline void LoewnerMorphology::Morph::prepareGrid3(dim3 &gridDim, dim3 &blockDim, int width, int height) { blockDim.x = TILE_X; blockDim.y = TILE_Y; int pWidth = ((width + TILE_X - 1) / TILE_X) * TILE_X; int pHeight = ((height + TILE_Y - 1) / TILE_Y) * TILE_Y; gridDim.x = pWidth / TILE_X; gridDim.y = pHeight / TILE_Y; } template<typename T> void LoewnerMorphology::Morph::morph_einstein_async(T *image1, T *image2, int width, int height, int lda1, int lda2, cudaStream_t stream) { dim3 blockDim; dim3 gridDim; prepareGrid3(gridDim, blockDim, width, height); LoewnerMorphology::einstein_kernel<T><<<gridDim, blockDim, 0, stream>>>(image1, image2, width, height, lda1, lda2); } template<typename T, bool type, int N> void LoewnerMorphology::Morph::morph_einstein_copy_original_launcher(T *dev_out1, T *dev_out2, T *in, T *out, int width, int height, cudaStream_t *streams) { // calling einstein cernel asynchronusly with memory transfers #pragma unroll for (int i = 0; i < N; i++) { int first = first(i, N, height) * width; int chunkHeight = size(i, N, height); size_t size = chunkHeight * width * sizeof(T); cuda_exec(cudaMemcpyAsync(dev_out2 + first, in + first, size, cudaMemcpyHostToDevice, streams[i])); morph_einstein_async(((type) ? dev_out2 : dev_out1) + first, ((type) ? dev_out1 : dev_out2) + first, width, chunkHeight, width, width, streams[i]); cuda_exec(cudaMemcpyAsync(out + first, ((type) ? dev_out2 : dev_out1) + first, size, cudaMemcpyDeviceToHost, streams[i])); } } template<typename T, int N> void LoewnerMorphology::Morph::morph_einstein_copy_launcher(T *dev_out1, T *dev_out2, T *out, int width, int height, cudaStream_t *streams) { // calling einstein cernel asynchronusly with memory transfers #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { int first = first(i, NUM_STREAMS, height) * width; int chunkHeight = size(i, NUM_STREAMS, height); size_t size = chunkHeight * width * sizeof(T); morph_einstein_async(dev_out1 + first, dev_out2 + first, width, chunkHeight, width, width, streams[i]); cuda_exec(cudaMemcpyAsync(out + first, dev_out1 + first, size, cudaMemcpyDeviceToHost, streams[i])); } } template<typename T, bool type> void LoewnerMorphology::Morph::morph_basic_launcher(T *dev_in, T *dev_out, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream) { dim3 blockDim; dim3 gridDim; // filling device memory with appropriate value prepareGrid1(gridDim, blockDim, pHeight + 2 * padding); LoewnerMorphology::fill<T><<<gridDim, blockDim, 0, stream>>>(dev_in, pWidth + 2 * padding, (type) ? T::max() : T::min()); // copying image to device memory cuda_exec(cudaMemcpy2D(dev_in + padding * (pWidth + 2 * padding) + padding, (pWidth + 2 * padding) * sizeof(T), in, width * sizeof(T), width * sizeof(T), height, cudaMemcpyHostToDevice)); // invoking morph kernel prepareGrid2(gridDim, blockDim, pWidth, pHeight); LoewnerMorphology::morph_kernel<T, type><<<gridDim, blockDim, sharedSize, stream>>>(dev_in, dev_out, width, height, pWidth, pHeight, padding); } template<typename T> void LoewnerMorphology::Morph::morph_shock_launcher(T *dev_in1, T* dev_in2, T *dev_out, T *laplacian, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream) { dim3 blockDim; dim3 gridDim; // filling device memory with appropriate value prepareGrid1(gridDim, blockDim, pHeight + 2 * padding); LoewnerMorphology::fill<T><<<gridDim, blockDim, 0, stream>>>(dev_in1, pWidth + 2 * padding, T::min()); LoewnerMorphology::fill<T><<<gridDim, blockDim, 0, stream>>>(dev_in2, pWidth + 2 * padding, T::max()); cuda_exec(cudaStreamSynchronize(stream)); // copying image to device memory cuda_exec(cudaMemcpy2D(dev_in1 + padding * (pWidth + 2 * padding) + padding, (pWidth + 2 * padding) * sizeof(T), in, width * sizeof(T), width * sizeof(T), height, cudaMemcpyHostToDevice)); cuda_exec(cudaMemcpy2D(dev_in2 + padding * (pWidth + 2 * padding) + padding, (pWidth + 2 * padding) * sizeof(T), in, width * sizeof(T), width * sizeof(T), height, cudaMemcpyHostToDevice)); // invoking morph kernela prepareGrid2(gridDim, blockDim, pWidth, pHeight); LoewnerMorphology::shock_kernel<T><<<gridDim, blockDim, 2 * sharedSize, stream>>>(dev_in1, dev_in2, dev_out, laplacian, width, height, pWidth, pHeight, padding); cuda_exec(cudaStreamSynchronize(stream)); } template<typename T, bool type> void LoewnerMorphology::Morph::morph_basic(T *in, T *out, int width, int height, int padding) { T *dev_in = NULL; // device vector holding image matrix T *dev_out = NULL; // device vector holding first output image int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes cuda_exec(cudaMalloc(&dev_in, inSize)); cuda_exec(cudaMalloc(&dev_out, outSize)); morph_basic_launcher<T, type>(dev_in, dev_out, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaDeviceSynchronize()); cuda_exec(cudaMemcpy(out, dev_out, outSize, cudaMemcpyDeviceToHost)); cuda_exec(cudaFree(dev_in)); cuda_exec(cudaFree(dev_out)); } template<typename T, bool type> void LoewnerMorphology::Morph::morph_second_order_launcher(T *dev_in, T *dev_out, T *in, int width, int height, int pWidth, int pHeight, int padding, size_t sharedSize, cudaStream_t stream) { dim3 blockDim1, blockDim2; dim3 gridDim1, gridDim2; prepareGrid1(gridDim1, blockDim1, pHeight + 2 * padding); prepareGrid2(gridDim2, blockDim2, pWidth, pHeight); // filling device memory with appropriate value LoewnerMorphology::fill<T><<<gridDim1, blockDim1, 0, stream>>>(dev_in, pWidth + 2 * padding, (type) ? T::max() : T::min()); // copying image to device memory cuda_exec(cudaMemcpy2DAsync(dev_in + padding * (pWidth + 2 * padding) + padding, (pWidth + 2 * padding) * sizeof(T), in, width * sizeof(T), width * sizeof(T), height, cudaMemcpyHostToDevice, stream)); // invoking morph kernela LoewnerMorphology::morph_kernel<T, type><<<gridDim2, blockDim2, sharedSize, stream>>>(dev_in, dev_out, width, height, pWidth, pHeight, padding); // filling device memory with appropriate value LoewnerMorphology::fill<T><<<gridDim1, blockDim1, 0, stream>>>(dev_in, pWidth + 2 * padding, (!type) ? T::max() : T::min()); // copying image to device memory cuda_exec(cudaMemcpy2DAsync(dev_in + padding * (pWidth + 2 * padding) + padding, (pWidth + 2 * padding) * sizeof(T), dev_out, width * sizeof(T), width * sizeof(T), height, cudaMemcpyDeviceToDevice, stream)); // invoking morph kernela LoewnerMorphology::morph_kernel<T, !type><<<gridDim2, blockDim2, sharedSize, stream>>>(dev_in, dev_out, width, height, pWidth, pHeight, padding); } template<typename T, bool type> void LoewnerMorphology::Morph::morph_second_order(T *in, T *out, int width, int height, int padding) { T *dev_in = NULL; // device vector holding image matrix T *dev_out = NULL; // device vector holding first output image int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes cuda_exec(cudaMalloc(&dev_in, inSize)); cuda_exec(cudaMalloc(&dev_out, outSize)); morph_second_order_launcher<T, type>(dev_in, dev_out, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaDeviceSynchronize()); cuda_exec(cudaMemcpy(out, dev_out, outSize, cudaMemcpyDeviceToHost)); cuda_exec(cudaFree(dev_in)); cuda_exec(cudaFree(dev_out)); } template<typename T, bool type> void LoewnerMorphology::Morph::morph_hats(T *in, T *out, int width, int height, int padding) { T *dev_in = NULL; // device vector holding image matrix (padding) T *dev_out1 = NULL; // device vector holding first output image T *dev_out2 = NULL; // device vector holding original image int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes cuda_exec(cudaMalloc(&dev_in, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); morph_second_order_launcher<T, type>(dev_in, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaDeviceSynchronize()); morph_einstein_copy_original_launcher<T, type, NUM_STREAMS>(dev_out1, dev_out2, in, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cuda_exec(cudaFree(dev_in)); cuda_exec(cudaFree(dev_out1)); cuda_exec(cudaFree(dev_out2)); } template<typename T> void LoewnerMorphology::Morph::morph_sdth(T *in, T *out, int width, int height, int padding, int *mask) { T *dev_in1 = NULL; // device vector holding image matrix (padding) T *dev_in2 = NULL; // device vector holding image matrix (padding) T *dev_out1 = NULL; // device vector holding first output image T *dev_out2 = NULL; // device vector holding second output image T *dev_out_temp = NULL; // device vector holding output image on second device (optional, if it is available) int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes int count = 0; cuda_exec(cudaGetDeviceCount(&count)); if (count < 2) { // code executed on one GPU cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); morph_second_order_launcher<T, false>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize, streams[0]); morph_second_order_launcher<T, true>(dev_in2, dev_out2, in, width, height, pWidth, pHeight, padding, sharedSize, streams[1]); cuda_exec(cudaStreamSynchronize(streams[0])); cuda_exec(cudaStreamSynchronize(streams[1])); cuda_exec(cudaFree(dev_in2)); } else { // code executed on two GPUs cuda_exec(cudaSetDevice(0)); cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); cuda_exec(cudaSetDevice(1)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out_temp, outSize)); cuda_exec(cudaMemcpyToSymbol(maskMemory, mask, (2 * padding + 1) * (2 * padding + 1) * sizeof(int), cudaMemcpyHostToDevice)); cuda_exec(cudaSetDevice(0)); morph_second_order_launcher<T, false>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaSetDevice(1)); morph_second_order_launcher<T, true>(dev_in2, dev_out_temp, in, width, height, pWidth, pHeight, padding, sharedSize); cudaSetDevice(0); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(1); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(0); cudaDeviceEnablePeerAccess(1, 0); cuda_exec(cudaMemcpyPeer(dev_out2, 0, dev_out_temp, 1, outSize)); cudaSetDevice(1); cuda_exec(cudaFree(dev_in2)); cuda_exec(cudaFree(dev_out_temp)); cudaSetDevice(0); } morph_einstein_copy_launcher<T, NUM_STREAMS>(dev_out1, dev_out2, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cuda_exec(cudaFree(dev_in1)); cuda_exec(cudaFree(dev_out1)); cuda_exec(cudaFree(dev_out2)); } template<typename T> void LoewnerMorphology::Morph::morph_beucher(T *in, T *out, int width, int height, int padding, int *mask) { T *dev_in1 = NULL; // device vector holding image matrix (padding) T *dev_in2 = NULL; // device vector holding image matrix (padding) T *dev_out1 = NULL; // device vector holding first output image T *dev_out2 = NULL; // device vector holding second output image T *dev_out_temp = NULL; // device vector holding output image on second device (optional, if it is available) int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes int count = 0; cuda_exec(cudaGetDeviceCount(&count)); if (count < 2) { // code executed on one GPU cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); morph_basic_launcher<T, false>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize, streams[0]); morph_basic_launcher<T, true>(dev_in2, dev_out2, in, width, height, pWidth, pHeight, padding, sharedSize, streams[1]); cuda_exec(cudaStreamSynchronize(streams[0])); cuda_exec(cudaStreamSynchronize(streams[1])); cuda_exec(cudaFree(dev_in2)); } else { // code executed on two GPUs cuda_exec(cudaSetDevice(0)); cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); cuda_exec(cudaSetDevice(1)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out_temp, outSize)); cuda_exec(cudaMemcpyToSymbol(maskMemory, mask, (2 * padding + 1) * (2 * padding + 1) * sizeof(int), cudaMemcpyHostToDevice)); cuda_exec(cudaSetDevice(0)); morph_basic_launcher<T, false>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaSetDevice(1)); morph_basic_launcher<T, true>(dev_in2, dev_out_temp, in, width, height, pWidth, pHeight, padding, sharedSize); cudaSetDevice(0); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(1); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(0); cudaDeviceEnablePeerAccess(1, 0); cuda_exec(cudaMemcpyPeer(dev_out2, 0, dev_out_temp, 1, outSize)); cudaSetDevice(1); cuda_exec(cudaFree(dev_in2)); cuda_exec(cudaFree(dev_out_temp)); cudaSetDevice(0); } morph_einstein_copy_launcher<T, NUM_STREAMS>(dev_out1, dev_out2, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cuda_exec(cudaFree(dev_in1)); cuda_exec(cudaFree(dev_out1)); cuda_exec(cudaFree(dev_out2)); } template<typename T, bool type> void LoewnerMorphology::Morph::morph_gradients(T *in, T *out, int width, int height, int padding) { T *dev_in = NULL; // device vector holding image matrix (padding) T *dev_out = NULL; // device vector holding first output image int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes cuda_exec(cudaMalloc(&dev_in, inSize)); cuda_exec(cudaMalloc(&dev_out, outSize)); morph_basic_launcher<T, type>(dev_in, dev_out, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaDeviceSynchronize()); morph_einstein_copy_original_launcher<T, type, NUM_STREAMS>(dev_out, dev_in, in, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cuda_exec(cudaFree(dev_in)); cuda_exec(cudaFree(dev_out)); } template<typename T> void LoewnerMorphology::Morph::morph_laplacian(T *in, T *out, int width, int height, int padding, int *mask) { T *dev_in1 = NULL; // device vector holding image matrix (padding) T *dev_in2 = NULL; // device vector holding image matrix (padding) T *dev_out1 = NULL; // device vector holding first output image T *dev_out2 = NULL; // device vector holding second output image T *dev_out_temp = NULL; // device vector holding output image on second device (optional, if it is available) int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes int count = 0; cuda_exec(cudaGetDeviceCount(&count)); if (count < 2) { cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); morph_basic_launcher<T, true>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize, streams[0]); morph_basic_launcher<T, false>(dev_in2, dev_out2, in, width, height, pWidth, pHeight, padding, sharedSize, streams[1]); cuda_exec(cudaMemcpyAsync(dev_in1, in, outSize, cudaMemcpyHostToDevice, streams[0])); morph_einstein_async(dev_out1, dev_in1, width, height, width, width, streams[0]); cuda_exec(cudaMemcpyAsync(dev_in2, in, outSize, cudaMemcpyHostToDevice, streams[1])); morph_einstein_async(dev_in2, dev_out2, width, height, width, width, streams[1]); cuda_exec(cudaStreamSynchronize(streams[0])); cuda_exec(cudaStreamSynchronize(streams[1])); morph_einstein_copy_launcher<T, NUM_STREAMS>(dev_out1, dev_in2, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cuda_exec(cudaFree(dev_in2)); } else { // code executed on two GPUs cuda_exec(cudaSetDevice(0)); cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); cuda_exec(cudaSetDevice(1)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out_temp, outSize)); cuda_exec(cudaMemcpyToSymbol(maskMemory, mask, (2 * padding + 1) * (2 * padding + 1) * sizeof(int), cudaMemcpyHostToDevice)); cuda_exec(cudaSetDevice(0)); morph_basic_launcher<T, true>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaMemcpyAsync(dev_in1, in, outSize, cudaMemcpyHostToDevice)); morph_einstein_async(dev_out1, dev_in1, width, height, width, width); cuda_exec(cudaSetDevice(1)); morph_basic_launcher<T, false>(dev_in2, dev_out_temp, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaMemcpyAsync(dev_in2, in, outSize, cudaMemcpyHostToDevice)); morph_einstein_async(dev_in2, dev_out_temp, width, height, width, width); cudaSetDevice(0); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(1); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(0); cudaDeviceEnablePeerAccess(1, 0); cuda_exec(cudaMemcpyPeer(dev_out2, 0, dev_in2, 1, outSize)); morph_einstein_copy_launcher<T, NUM_STREAMS>(dev_out1, dev_in2, out, width, height, streams); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamSynchronize(streams[i])); } cudaSetDevice(1); cuda_exec(cudaFree(dev_in2)); cuda_exec(cudaFree(dev_out_temp)); cudaSetDevice(0); } cuda_exec(cudaFree(dev_in1)); cuda_exec(cudaFree(dev_out1)); cuda_exec(cudaFree(dev_out2)); } template<typename T> void LoewnerMorphology::Morph::morph_shock(T *in, T *out, int width, int height, int padding, int *mask) { T *dev_in1 = NULL; // device vector holding image matrix (padding) T *dev_in2 = NULL; // device vector holding image matrix (padding) T *dev_out1 = NULL; // device vector holding first output image T *dev_out2 = NULL; // device vector holding second output image T *dev_out_temp = NULL; // device vector holding output image on second device (optional, if it is available) int pWidth = ((width + THREADS_X - 1) / THREADS_X) * THREADS_X; // width of the image (rounded to the multiple of THREAD_X) int pHeight = ((height + THREADS_Y - 1) / THREADS_Y) * THREADS_Y; // hight of the image (rounded to the multiple of THREAD_Y) size_t inSize = (pWidth + 2 * padding) * (pHeight + 2 * padding) * sizeof(T); // size of the input device vector (Circle is used for max and min calculations as described in the paper) size_t outSize = width * height * sizeof(T); // size of the (each) output device vector int sharedWidth = THREADS_X + 2 * padding + 1; // shared memory width (avoiding bank conflicts) int sharedHeight = THREADS_Y + 2 * padding; // shared memory height size_t sharedSize = sharedWidth * sharedHeight * sizeof(Circle); // size of the shared memory in bypes int count = 0; cuda_exec(cudaGetDeviceCount(&count)); if (count < 2) { cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); morph_basic_launcher<T, true>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize, streams[0]); morph_basic_launcher<T, false>(dev_in2, dev_out2, in, width, height, pWidth, pHeight, padding, sharedSize, streams[1]); cuda_exec(cudaMemcpyAsync(dev_in1, in, outSize, cudaMemcpyHostToDevice, streams[0])); morph_einstein_async(dev_out1, dev_in1, width, height, width, width, streams[0]); cuda_exec(cudaMemcpyAsync(dev_in2, in, outSize, cudaMemcpyHostToDevice, streams[1])); morph_einstein_async(dev_in2, dev_out2, width, height, width, width, streams[1]); cuda_exec(cudaStreamSynchronize(streams[0])); cuda_exec(cudaStreamSynchronize(streams[1])); morph_einstein_async(dev_out1, dev_in2, width, height, width, width); cuda_exec(cudaDeviceSynchronize()); cuda_exec(cudaFree(dev_in2)); } else { // code executed on two GPUs cuda_exec(cudaSetDevice(0)); cuda_exec(cudaMalloc(&dev_in1, inSize)); cuda_exec(cudaMalloc(&dev_out1, outSize)); cuda_exec(cudaMalloc(&dev_out2, outSize)); cuda_exec(cudaSetDevice(1)); cuda_exec(cudaMalloc(&dev_in2, inSize)); cuda_exec(cudaMalloc(&dev_out_temp, outSize)); cuda_exec(cudaMemcpyToSymbol(maskMemory, mask, (2 * padding + 1) * (2 * padding + 1) * sizeof(int), cudaMemcpyHostToDevice)); cuda_exec(cudaSetDevice(0)); morph_basic_launcher<T, false>(dev_in1, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaMemcpyAsync(dev_in1, in, outSize, cudaMemcpyHostToDevice)); morph_einstein_async(dev_out1, dev_in1, width, height, width, width); cuda_exec(cudaSetDevice(1)); morph_basic_launcher<T, true>(dev_in2, dev_out_temp, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaMemcpyAsync(dev_in2, in, outSize, cudaMemcpyHostToDevice)); morph_einstein_async(dev_in2, dev_out_temp, width, height, width, width); cudaSetDevice(0); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(1); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(0); cudaDeviceEnablePeerAccess(1, 0); cuda_exec(cudaMemcpyPeer(dev_out2, 0, dev_in2, 1, outSize)); morph_einstein_async(dev_out1, dev_in2, width, height, width, width); cuda_exec(cudaDeviceSynchronize()); cudaSetDevice(1); cuda_exec(cudaFree(dev_in2)); cuda_exec(cudaFree(dev_out_temp)); cudaSetDevice(0); } // there is laplacian on location dev_out1 cuda_exec(cudaMalloc(&dev_in2, inSize)); morph_shock_launcher(dev_in1, dev_in2, dev_out2, dev_out1, in, width, height, pWidth, pHeight, padding, sharedSize); cuda_exec(cudaDeviceSynchronize()); cuda_exec(cudaMemcpy(out, dev_out2, outSize, cudaMemcpyDeviceToHost)); cuda_exec(cudaFree(dev_in1)); cuda_exec(cudaFree(dev_in2)); cuda_exec(cudaFree(dev_out1)); cuda_exec(cudaFree(dev_out2)); } template<typename T> void LoewnerMorphology::Morph::morph_handle(T *in, T *out, int width, int height, int padding, int *mask, int morphType, int iters) { if (iters < 1) { printf("Operation cannot be executed. Number of iterations must be greater than 0. You provided %d.\n", iters); exit(EXIT_FAILURE); } cuda_exec(cudaSetDevice(0)); // copying mask to constant memory int maskSize = (2 * padding + 1) * (2 * padding + 1) * sizeof(int); cuda_exec(cudaMemcpyToSymbol(maskMemory, mask, maskSize, cudaMemcpyHostToDevice)); #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamCreate(&streams[i])); } switch (morphType) { case 0: for (int i = 0; i < iters; i++) { if (i == 0) { morph_basic<T, false>(in, out, width, height, padding); } else { morph_basic<T, false>(out, out, width, height, padding); } } break; case 1: for (int i = 0; i < iters; i++) { if (i == 0) { morph_basic<T, true>(in, out, width, height, padding); } else { morph_basic<T, true>(out, out, width, height, padding); } } break; case 2: for (int i = 0; i < iters; i++) { if (i == 0) { morph_second_order<T, false>(in, out, width, height, padding); } else { morph_second_order<T, false>(out, out, width, height, padding); } } break; case 3: for (int i = 0; i < iters; i++) { if (i == 0) { morph_second_order<T, true>(in, out, width, height, padding); } else { morph_second_order<T, true>(out, out, width, height, padding); } } break; case 4: for (int i = 0; i < iters; i++) { if (i == 0) { morph_hats<T, false>(in, out, width, height, padding); } else { morph_hats<T, false>(out, out, width, height, padding); } } break; case 5: for (int i = 0; i < iters; i++) { if (i == 0) { morph_hats<T, true>(in, out, width, height, padding); } else { morph_hats<T, true>(out, out, width, height, padding); } } break; case 6: for (int i = 0; i < iters; i++) { if (i == 0) { morph_sdth<T>(in, out, width, height, padding, mask); } else { morph_sdth<T>(out, out, width, height, padding, mask); } } break; case 7: for (int i = 0; i < iters; i++) { if (i == 0) { morph_beucher<T>(in, out, width, height, padding, mask); } else { morph_beucher<T>(out, out, width, height, padding, mask); } } break; case 8: for (int i = 0; i < iters; i++) { if (i == 0) { morph_gradients<T, false>(in, out, width, height, padding); } else { morph_gradients<T, false>(out, out, width, height, padding); } } break; case 9: for (int i = 0; i < iters; i++) { if (i == 0) { morph_gradients<T, true>(in, out, width, height, padding); } else { morph_gradients<T, true>(out, out, width, height, padding); } } break; case 10: for (int i = 0; i < iters; i++) { if (i == 0) { morph_laplacian<T>(in, out, width, height, padding, mask); } else { morph_laplacian<T>(out, out, width, height, padding, mask); } } break; case 11: for (int i = 0; i < iters; i++) { if (i == 0) { morph_shock<T>(in, out, width, height, padding, mask); } else { morph_shock<T>(out, out, width, height, padding, mask); } } break; } #pragma unroll for (int i = 0; i < NUM_STREAMS; i++) { cuda_exec(cudaStreamDestroy(streams[i])); } } LoewnerMorphology::Morph::Morph(const char *imageFile, const char *maskFile, int maskDim) { double *image = NULL; double *data = NULL; if (maskDim % 2 == 0 || maskDim * maskDim > 1024) { printf("Mask dimension should be odd and its squere should be less than 1024.\n"); exit(EXIT_FAILURE); } mask = (int *)malloc(maskDim * maskDim * sizeof(int)); readMaskFromFile(mask, maskDim, maskFile); padding = maskDim / 2; omp_set_num_threads(OMP_THREAD_NUM); inputImage = new CImgFloatWrapper(imageFile); outputImage = nullptr; width = inputImage->width(); height = inputImage->height(); spectrum = inputImage->spectrum(); size = width * height; image = (double *)malloc(size * spectrum * sizeof(double)); data = (double *)malloc(size * spectrum * sizeof(double)); cuda_exec(cudaMallocHost(&matrices, size * sizeof(LoewnerMorphology::MorphColorMatrix))); cuda_exec(cudaMallocHost(&result, size * sizeof(LoewnerMorphology::MorphColorMatrix))); Conversions::type2double(inputImage->data(), image, size * spectrum); Conversions::rgb2mhcl(image, image + size, image + 2 * size, data, data + size, data + 2 * size, size); Conversions::mhcl2matrix(data, data + size, data + 2 * size, matrices, size); free(image); free(data); } LoewnerMorphology::Morph::~Morph() { free(mask); cuda_exec(cudaFreeHost(matrices)); cuda_exec(cudaFreeHost(result)); delete inputImage; delete outputImage; } void LoewnerMorphology::Morph::createOutputImage() { double *image = (double *)malloc(size * spectrum * sizeof(double)); double *data = (double *)malloc(size * spectrum * sizeof(double)); float *out = (float *)malloc(size * spectrum * sizeof(float)); Conversions::matrix2mhcl(result, data, data + size, data + 2 * size, size); Conversions::mhcl2rgb(data, data + size, data + 2 * size, image, image + size, image + 2 * size, size); Conversions::double2type(image, out, size * spectrum); if (outputImage != nullptr) { delete outputImage; } outputImage = new CImgFloatWrapper(out, width, height, spectrum); free(image); free(data); free(out); } void LoewnerMorphology::Morph::dilation(int iter) { morph_handle(matrices, result, width, height, padding, mask, 0, iter); createOutputImage(); } void LoewnerMorphology::Morph::erosion(int iter) { morph_handle(matrices, result, width, height, padding, mask, 1, iter); createOutputImage(); } void LoewnerMorphology::Morph::closing(int iter) { morph_handle(matrices, result, width, height, padding, mask, 2, iter); createOutputImage(); } void LoewnerMorphology::Morph::opening(int iter) { morph_handle(matrices, result, width, height, padding, mask, 3, iter ); createOutputImage(); } void LoewnerMorphology::Morph::blackTopHat(int iter) { morph_handle(matrices, result, width, height, padding, mask, 4, iter); createOutputImage(); } void LoewnerMorphology::Morph::whiteTopHat(int iter) { morph_handle(matrices, result, width, height, padding, mask, 5, iter); createOutputImage(); } void LoewnerMorphology::Morph::selfDualTopHat(int iter) { morph_handle(matrices, result, width, height, padding, mask, 6, iter); createOutputImage(); } void LoewnerMorphology::Morph::beucherGradient(int iter) { morph_handle(matrices, result, width, height, padding, mask, 7, iter); createOutputImage(); } void LoewnerMorphology::Morph::externalGradient(int iter) { morph_handle(matrices, result, width, height, padding, mask, 8, iter); createOutputImage(); } void LoewnerMorphology::Morph::internalGradient(int iter) { morph_handle(matrices, result, width, height, padding, mask, 9, iter); createOutputImage(); } void LoewnerMorphology::Morph::laplacian(int iter) { morph_handle(matrices, result, width, height, padding, mask, 10, iter); createOutputImage(); } void LoewnerMorphology::Morph::shockFilter(int iter) { morph_handle(matrices, result, width, height, padding, mask, 11, iter); createOutputImage(); } void LoewnerMorphology::Morph::displayOriginalImage() { inputImage->display(); } void LoewnerMorphology::Morph::displayResultImage() { if (outputImage == nullptr) { printf("There is no result to display.\n"); return; } outputImage->display(); } template<typename T> void LoewnerMorphology::Morph::copy(T *in, T *out, int size) { #pragma omp parallel for for (int i = 0; i < size; i++) { out[i] = in[i]; } } float *LoewnerMorphology::Morph::returnResult() { if (outputImage == nullptr) { printf("There is no result to return.\n"); return nullptr; } float *out = (float *)malloc(size * spectrum * sizeof(float)); copy(outputImage->data(), out, size * spectrum); return out; } void LoewnerMorphology::Morph::saveResult(const char *fileName) { if (outputImage == nullptr) { printf("There is no result to save.\n"); return; } outputImage->save(fileName); }
simd-clones-7.c
/* { dg-do compile { target i?86-*-* x86_64-*-* } } */ /* { dg-options "-fopenmp -w" } */ int array[1000]; #pragma omp declare simd notinbranch simdlen(4) void foo (int *a, int b) { a[b] = 555; } #pragma omp declare simd notinbranch simdlen(4) void bar (int *a) { *a = 555; }
bitonic_sort.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <string.h> #include <omp.h> struct timeval st, et; void swap(int*, int, int); void rng(int*, int, int*); void buildDummy(int*, int, int, int); void impBitonicSortPar(int*, int, int); void impBitonicSortSer(int*, int); int getPowTwo(int); void writeToFile(int*, int, char*); int thr; int main(int argc, char **argv) { int n, dummy_n, threads, test, max_x; int* arr; int* arr2; thr = omp_get_max_threads(); // get maximum effective threads threads = omp_get_max_threads(); if (argc < 2) { printf("Usage: %s <n> <p>\nwhere <n> is problem size, <p> is number of thread (optional)\n\n", argv[0]); exit(1); } if (argc == 3){ // use for custom threads number threads = atoi(argv[2]); } // true for test with 1,2,4,8,...,256 threads number test = threads<=0; if(test){ printf("test\n"); } // get problem size; n = atoi(argv[1]); // get dummy_n from nearest power of two dummy_n = getPowTwo(n); // prepare random numbers arr = (int*) malloc(dummy_n*sizeof(int)); if(!arr){ printf("Unable to allocate memory\n"); exit(1); } rng(arr,n,&max_x); buildDummy(arr,n,dummy_n,max_x); // copy arr2 = (int*) malloc(dummy_n*sizeof(int)); memcpy(arr2,arr,dummy_n*sizeof(int)); // write random numbers to input file writeToFile(arr,n,"./data/input"); // execute serial gettimeofday(&st,NULL); impBitonicSortSer(arr,dummy_n); gettimeofday(&et,NULL); int elapsed_serial = ((et.tv_sec - st.tv_sec) * 1000000) + (et.tv_usec - st.tv_usec); printf("Execution serial time: %d micro sec\n",elapsed_serial); // execute paralel gettimeofday(&st,NULL); impBitonicSortPar(arr2,dummy_n,threads); gettimeofday(&et,NULL); int elapsed_paralel = ((et.tv_sec - st.tv_sec) * 1000000) + (et.tv_usec - st.tv_usec); printf("Execution paralel time: %d micro sec\n",elapsed_paralel); // calculate speedup printf("Speedup : %.3f\n",(float)elapsed_serial/elapsed_paralel); writeToFile(arr,n,"./data/output"); free(arr); free(arr2); return 0; } void writeToFile(int* arr, int n, char* path){ FILE* f = fopen(path,"w"); for(int i=0; i<n; i++) { fprintf(f, "%d\n", arr[i]); } fclose(f); } void rng(int* arr, int n, int* max_x) { int seed = 13515097; srand(seed); for(long i = 0; i < n; i++) { arr[i] = (int)rand(); *max_x = ((i==0 || *max_x<arr[i])?arr[i]:*max_x); } } void buildDummy(int* arr,int N,int dummy_n, int max_x){ for(long i = N; i < dummy_n; i++) { arr[i]=max_x; } } void swap(int* a, int i, int j) { int t; t = a[i]; a[i] = a[j]; a[j] = t; } /* Imperative paralel bitonic sort */ void impBitonicSortPar(int* a, int n, int threads) { int i,j,k; int dummy_n = getPowTwo(n); for (k=2; k<=dummy_n; k=2*k) { for (j=k>>1; j>0; j=j>>1) { // bitonic increasing #pragma omp parallel for num_threads(threads) private(i) shared(n,j,k) for (i=0; i<n; i++) { int ij=i^j; if ((ij)>i) { // monotonic increasing if ((i&k)==0 && a[i] > a[ij]) swap(a,i,ij); // monotonic decreasing if ((i&k)!=0 && a[i] < a[ij]) swap(a,i,ij); } } } } } /* Imperative serial bitonic sort */ void impBitonicSortSer(int* a, int n) { int i,j,k; int dummy_n = getPowTwo(n); for (k=2; k<=dummy_n; k=2*k) { for (j=k>>1; j>0; j=j>>1) { // bitonic increasing for (i=0; i<n; i++) { int ij=i^j; if ((ij)>i) { // monotonic increasing if ((i&k)==0 && a[i] > a[ij]) swap(a,i,ij); // monotonic decreasing if ((i&k)!=0 && a[i] < a[ij]) swap(a,i,ij); } } } } } int getPowTwo(int n){ int d=1; while (d>0 && d<n) d<<=1; return d; }
omp_reduction.c
/****************************************************************************** * FILE: omp_reduction.c * DESCRIPTION: * OpenMP Example - Combined Parallel Loop Reduction - C/C++ Version * This example demonstrates a sum reduction within a combined parallel loop * construct. Notice that default data element scoping is assumed - there * are no clauses specifying shared or private variables. OpenMP will * automatically make loop index variables private within team threads, and * global variables shared. * AUTHOR: Blaise Barney 5/99 * LAST REVISED: 04/06/05 ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int i, n; float a[100], b[100], sum; /* Some initializations */ n = 100; for (i=0; i < n; i++) a[i] = b[i] = i * 1.0; sum = 0.0; #pragma omp parallel for reduction(+:sum) for (i=0; i < n; i++) sum = sum + (a[i] * b[i]); printf(" Sum = %f\n",sum); return 0; }
data.c
#include "data.h" #include "utils.h" #include "image.h" #include "dark_cuda.h" #include "box.h" #include "http_stream.h" #include <stdio.h> #include <stdlib.h> #include <string.h> extern int check_mistakes; #define NUMCHARS 37 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; list *get_paths(char *filename) { char *path; FILE *file = fopen(filename, "r"); if(!file) file_error(filename); list *lines = make_list(); while((path=fgetl(file))){ list_insert(lines, path); } fclose(file); return lines; } /* char **get_random_paths_indexes(char **paths, int n, int m, int *indexes) { char **random_paths = calloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); for(i = 0; i < n; ++i){ int index = random_gen()%m; indexes[i] = index; random_paths[i] = paths[index]; if(i == 0) printf("%s\n", paths[index]); } pthread_mutex_unlock(&mutex); return random_paths; } */ char **get_sequential_paths(char **paths, int n, int m, int mini_batch, int augment_speed) { int speed = rand_int(1, augment_speed); if (speed < 1) speed = 1; char** sequentia_paths = (char**)xcalloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); //printf("n = %d, mini_batch = %d \n", n, mini_batch); unsigned int *start_time_indexes = (unsigned int *)xcalloc(mini_batch, sizeof(unsigned int)); for (i = 0; i < mini_batch; ++i) { start_time_indexes[i] = random_gen() % m; //printf(" start_time_indexes[i] = %u, ", start_time_indexes[i]); } for (i = 0; i < n; ++i) { do { int time_line_index = i % mini_batch; unsigned int index = start_time_indexes[time_line_index] % m; start_time_indexes[time_line_index] += speed; //int index = random_gen() % m; sequentia_paths[i] = paths[index]; //if(i == 0) printf("%s\n", paths[index]); //printf(" index = %u - grp: %s \n", index, paths[index]); if (strlen(sequentia_paths[i]) <= 4) printf(" Very small path to the image: %s \n", sequentia_paths[i]); } while (strlen(sequentia_paths[i]) == 0); } free(start_time_indexes); pthread_mutex_unlock(&mutex); return sequentia_paths; } char **get_random_paths(char **paths, int n, int m) { char** random_paths = (char**)xcalloc(n, sizeof(char*)); int i; pthread_mutex_lock(&mutex); //printf("n = %d \n", n); for(i = 0; i < n; ++i){ do { int index = random_gen() % m; random_paths[i] = paths[index]; //if(i == 0) printf("%s\n", paths[index]); //printf("grp: %s\n", paths[index]); if (strlen(random_paths[i]) <= 4) printf(" Very small path to the image: %s \n", random_paths[i]); } while (strlen(random_paths[i]) == 0); } pthread_mutex_unlock(&mutex); return random_paths; } char **find_replace_paths(char **paths, int n, char *find, char *replace) { char** replace_paths = (char**)xcalloc(n, sizeof(char*)); int i; for(i = 0; i < n; ++i){ char replaced[4096]; find_replace(paths[i], find, replace, replaced); replace_paths[i] = copy_string(replaced); } return replace_paths; } matrix load_image_paths_gray(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image(paths[i], w, h, 3); image gray = grayscale_image(im); free_image(im); im = gray; X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_paths(char **paths, int n, int w, int h) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], w, h); X.vals[i] = im.data; X.cols = im.h*im.w*im.c; } return X; } matrix load_image_augment_paths(char **paths, int n, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure, int dontuse_opencv) { int i; matrix X; X.rows = n; X.vals = (float**)xcalloc(X.rows, sizeof(float*)); X.cols = 0; for(i = 0; i < n; ++i){ int size = w > h ? w : h; image im; if(dontuse_opencv) im = load_image_stb_resize(paths[i], 0, 0, 3); else im = load_image_color(paths[i], 0, 0); image crop = random_augment_image(im, angle, aspect, min, max, size); int flip = use_flip ? random_gen() % 2 : 0; if (flip) flip_image(crop); random_distort_image(crop, hue, saturation, exposure); image sized = resize_image(crop, w, h); //show_image(im, "orig"); //show_image(sized, "sized"); //show_image(sized, paths[i]); //wait_until_press_key_cv(); //printf("w = %d, h = %d \n", sized.w, sized.h); free_image(im); free_image(crop); X.vals[i] = sized.data; X.cols = sized.h*sized.w*sized.c; } return X; } box_label *read_boxes(char *filename, int *n) { box_label* boxes = (box_label*)xcalloc(1, sizeof(box_label)); FILE *file = fopen(filename, "r"); if (!file) { printf("Can't open label file. (This can be normal only if you use MSCOCO): %s \n", filename); //file_error(filename); FILE* fw = fopen("bad.list", "a"); fwrite(filename, sizeof(char), strlen(filename), fw); char *new_line = "\n"; fwrite(new_line, sizeof(char), strlen(new_line), fw); fclose(fw); if (check_mistakes) { printf("\n Error in read_boxes() \n"); getchar(); } *n = 0; return boxes; } float x, y, h, w; int id; int count = 0; while(fscanf(file, "%d %f %f %f %f", &id, &x, &y, &w, &h) == 5){ boxes = (box_label*)xrealloc(boxes, (count + 1) * sizeof(box_label)); boxes[count].id = id; boxes[count].x = x; boxes[count].y = y; boxes[count].h = h; boxes[count].w = w; boxes[count].left = x - w/2; boxes[count].right = x + w/2; boxes[count].top = y - h/2; boxes[count].bottom = y + h/2; ++count; } fclose(file); *n = count; return boxes; } void randomize_boxes(box_label *b, int n) { int i; for(i = 0; i < n; ++i){ box_label swap = b[i]; int index = random_gen()%n; b[i] = b[index]; b[index] = swap; } } void correct_boxes(box_label *boxes, int n, float dx, float dy, float sx, float sy, int flip) { int i; for(i = 0; i < n; ++i){ if(boxes[i].x == 0 && boxes[i].y == 0) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } if ((boxes[i].x + boxes[i].w / 2) < 0 || (boxes[i].y + boxes[i].h / 2) < 0 || (boxes[i].x - boxes[i].w / 2) > 1 || (boxes[i].y - boxes[i].h / 2) > 1) { boxes[i].x = 999999; boxes[i].y = 999999; boxes[i].w = 999999; boxes[i].h = 999999; continue; } boxes[i].left = boxes[i].left * sx - dx; boxes[i].right = boxes[i].right * sx - dx; boxes[i].top = boxes[i].top * sy - dy; boxes[i].bottom = boxes[i].bottom* sy - dy; if(flip){ float swap = boxes[i].left; boxes[i].left = 1. - boxes[i].right; boxes[i].right = 1. - swap; } boxes[i].left = constrain(0, 1, boxes[i].left); boxes[i].right = constrain(0, 1, boxes[i].right); boxes[i].top = constrain(0, 1, boxes[i].top); boxes[i].bottom = constrain(0, 1, boxes[i].bottom); boxes[i].x = (boxes[i].left+boxes[i].right)/2; boxes[i].y = (boxes[i].top+boxes[i].bottom)/2; boxes[i].w = (boxes[i].right - boxes[i].left); boxes[i].h = (boxes[i].bottom - boxes[i].top); boxes[i].w = constrain(0, 1, boxes[i].w); boxes[i].h = constrain(0, 1, boxes[i].h); } } void fill_truth_swag(char *path, float *truth, int classes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count && i < 30; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .0 || h < .0) continue; int index = (4+classes) * i; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; if (id < classes) truth[index+id] = 1; } free(boxes); } void fill_truth_region(char *path, float *truth, int classes, int num_boxes, int flip, float dx, float dy, float sx, float sy) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; box_label *boxes = read_boxes(labelpath, &count); randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); float x,y,w,h; int id; int i; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; if (w < .001 || h < .001) continue; int col = (int)(x*num_boxes); int row = (int)(y*num_boxes); x = x*num_boxes - col; y = y*num_boxes - row; int index = (col+row*num_boxes)*(5+classes); if (truth[index]) continue; truth[index++] = 1; if (id < classes) truth[index+id] = 1; index += classes; truth[index++] = x; truth[index++] = y; truth[index++] = w; truth[index++] = h; } free(boxes); } int fill_truth_detection(const char *path, int num_boxes, float *truth, int classes, int flip, float dx, float dy, float sx, float sy, int net_w, int net_h) { char labelpath[4096]; replace_image_to_label(path, labelpath); int count = 0; int i; box_label *boxes = read_boxes(labelpath, &count); int min_w_h = 0; float lowest_w = 1.F / net_w; float lowest_h = 1.F / net_h; randomize_boxes(boxes, count); correct_boxes(boxes, count, dx, dy, sx, sy, flip); if (count > num_boxes) count = num_boxes; float x, y, w, h; int id; int sub = 0; for (i = 0; i < count; ++i) { x = boxes[i].x; y = boxes[i].y; w = boxes[i].w; h = boxes[i].h; id = boxes[i].id; // not detect small objects //if ((w < 0.001F || h < 0.001F)) continue; // if truth (box for object) is smaller than 1x1 pix char buff[256]; if (id >= classes) { printf("\n Wrong annotation: class_id = %d. But class_id should be [from 0 to %d], file: %s \n", id, (classes-1), labelpath); sprintf(buff, "echo %s \"Wrong annotation: class_id = %d. But class_id should be [from 0 to %d]\" >> bad_label.list", labelpath, id, (classes-1)); system(buff); if (check_mistakes) getchar(); ++sub; continue; } if ((w < lowest_w || h < lowest_h)) { //sprintf(buff, "echo %s \"Very small object: w < lowest_w OR h < lowest_h\" >> bad_label.list", labelpath); //system(buff); ++sub; continue; } if (x == 999999 || y == 999999) { printf("\n Wrong annotation: x = 0, y = 0, < 0 or > 1, file: %s \n", labelpath); sprintf(buff, "echo %s \"Wrong annotation: x = 0 or y = 0\" >> bad_label.list", labelpath); system(buff); ++sub; if (check_mistakes) getchar(); continue; } if (x <= 0 || x > 1 || y <= 0 || y > 1) { printf("\n Wrong annotation: x = %f, y = %f, file: %s \n", x, y, labelpath); sprintf(buff, "echo %s \"Wrong annotation: x = %f, y = %f\" >> bad_label.list", labelpath, x, y); system(buff); ++sub; if (check_mistakes) getchar(); continue; } if (w > 1) { printf("\n Wrong annotation: w = %f, file: %s \n", w, labelpath); sprintf(buff, "echo %s \"Wrong annotation: w = %f\" >> bad_label.list", labelpath, w); system(buff); w = 1; if (check_mistakes) getchar(); } if (h > 1) { printf("\n Wrong annotation: h = %f, file: %s \n", h, labelpath); sprintf(buff, "echo %s \"Wrong annotation: h = %f\" >> bad_label.list", labelpath, h); system(buff); h = 1; if (check_mistakes) getchar(); } if (x == 0) x += lowest_w; if (y == 0) y += lowest_h; truth[(i-sub)*5+0] = x; truth[(i-sub)*5+1] = y; truth[(i-sub)*5+2] = w; truth[(i-sub)*5+3] = h; truth[(i-sub)*5+4] = id; if (min_w_h == 0) min_w_h = w*net_w; if (min_w_h > w*net_w) min_w_h = w*net_w; if (min_w_h > h*net_h) min_w_h = h*net_h; } free(boxes); return min_w_h; } void print_letters(float *pred, int n) { int i; for(i = 0; i < n; ++i){ int index = max_index(pred+i*NUMCHARS, NUMCHARS); printf("%c", int_to_alphanum(index)); } printf("\n"); } void fill_truth_captcha(char *path, int n, float *truth) { char *begin = strrchr(path, '/'); ++begin; int i; for(i = 0; i < strlen(begin) && i < n && begin[i] != '.'; ++i){ int index = alphanum_to_int(begin[i]); if(index > 35) printf("Bad %c\n", begin[i]); truth[i*NUMCHARS+index] = 1; } for(;i < n; ++i){ truth[i*NUMCHARS + NUMCHARS-1] = 1; } } data load_data_captcha(char **paths, int n, int m, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = make_matrix(n, k*NUMCHARS); int i; for(i = 0; i < n; ++i){ fill_truth_captcha(paths[i], k, d.y.vals[i]); } if(m) free(paths); return d; } data load_data_captcha_encode(char **paths, int n, int m, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.X.cols = 17100; d.y = d.X; if(m) free(paths); return d; } void fill_truth(char *path, char **labels, int k, float *truth) { int i; memset(truth, 0, k*sizeof(float)); int count = 0; for(i = 0; i < k; ++i){ if(strstr(path, labels[i])){ truth[i] = 1; ++count; } } if (count != 1) { printf("Too many or too few labels: %d, %s\n", count, path); count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { printf("\t label %d: %s \n", count, labels[i]); count++; } } } } void fill_truth_smooth(char *path, char **labels, int k, float *truth, float label_smooth_eps) { int i; memset(truth, 0, k * sizeof(float)); int count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { truth[i] = (1 - label_smooth_eps); ++count; } else { truth[i] = label_smooth_eps / (k - 1); } } if (count != 1) { printf("Too many or too few labels: %d, %s\n", count, path); count = 0; for (i = 0; i < k; ++i) { if (strstr(path, labels[i])) { printf("\t label %d: %s \n", count, labels[i]); count++; } } } } void fill_hierarchy(float *truth, int k, tree *hierarchy) { int j; for(j = 0; j < k; ++j){ if(truth[j]){ int parent = hierarchy->parent[j]; while(parent >= 0){ truth[parent] = 1; parent = hierarchy->parent[parent]; } } } int i; int count = 0; for(j = 0; j < hierarchy->groups; ++j){ //printf("%d\n", count); int mask = 1; for(i = 0; i < hierarchy->group_size[j]; ++i){ if(truth[count + i]){ mask = 0; break; } } if (mask) { for(i = 0; i < hierarchy->group_size[j]; ++i){ truth[count + i] = SECRET_NUM; } } count += hierarchy->group_size[j]; } } matrix load_labels_paths(char **paths, int n, char **labels, int k, tree *hierarchy, float label_smooth_eps) { matrix y = make_matrix(n, k); int i; for(i = 0; i < n && labels; ++i){ fill_truth_smooth(paths[i], labels, k, y.vals[i], label_smooth_eps); if(hierarchy){ fill_hierarchy(y.vals[i], k, hierarchy); } } return y; } matrix load_tags_paths(char **paths, int n, int k) { matrix y = make_matrix(n, k); int i; int count = 0; for(i = 0; i < n; ++i){ char label[4096]; find_replace(paths[i], "imgs", "labels", label); find_replace(label, "_iconl.jpeg", ".txt", label); FILE *file = fopen(label, "r"); if(!file){ find_replace(label, "labels", "labels2", label); file = fopen(label, "r"); if(!file) continue; } ++count; int tag; while(fscanf(file, "%d", &tag) == 1){ if(tag < k){ y.vals[i][tag] = 1; } } fclose(file); } printf("%d/%d\n", count, n); return y; } char **get_labels_custom(char *filename, int *size) { list *plist = get_paths(filename); if(size) *size = plist->size; char **labels = (char **)list_to_array(plist); free_list(plist); return labels; } char **get_labels(char *filename) { return get_labels_custom(filename, NULL); } void free_data(data d) { if(!d.shallow){ free_matrix(d.X); free_matrix(d.y); }else{ free(d.X.vals); free(d.y.vals); } } data load_data_region(int n, char **paths, int m, int w, int h, int size, int classes, float jitter, float hue, float saturation, float exposure) { char **random_paths = get_random_paths(paths, n, m); int i; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = size*size*(5+classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image orig = load_image_color(random_paths[i], 0, 0); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; int flip = random_gen()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/ow)/sx; float dy = ((float)ptop /oh)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); random_distort_image(sized, hue, saturation, exposure); d.X.vals[i] = sized.data; fill_truth_region(random_paths[i], d.y.vals[i], classes, size, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); } free(random_paths); return d; } data load_data_compare(int n, char **paths, int m, int classes, int w, int h) { if(m) paths = get_random_paths(paths, 2*n, m); int i,j; data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*6; int k = 2*(classes); d.y = make_matrix(n, k); for(i = 0; i < n; ++i){ image im1 = load_image_color(paths[i*2], w, h); image im2 = load_image_color(paths[i*2+1], w, h); d.X.vals[i] = (float*)xcalloc(d.X.cols, sizeof(float)); memcpy(d.X.vals[i], im1.data, h*w*3*sizeof(float)); memcpy(d.X.vals[i] + h*w*3, im2.data, h*w*3*sizeof(float)); int id; float iou; char imlabel1[4096]; char imlabel2[4096]; find_replace(paths[i*2], "imgs", "labels", imlabel1); find_replace(imlabel1, "jpg", "txt", imlabel1); FILE *fp1 = fopen(imlabel1, "r"); while(fscanf(fp1, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id] < iou) d.y.vals[i][2*id] = iou; } find_replace(paths[i*2+1], "imgs", "labels", imlabel2); find_replace(imlabel2, "jpg", "txt", imlabel2); FILE *fp2 = fopen(imlabel2, "r"); while(fscanf(fp2, "%d %f", &id, &iou) == 2){ if (d.y.vals[i][2*id + 1] < iou) d.y.vals[i][2*id + 1] = iou; } for (j = 0; j < classes; ++j){ if (d.y.vals[i][2*j] > .5 && d.y.vals[i][2*j+1] < .5){ d.y.vals[i][2*j] = 1; d.y.vals[i][2*j+1] = 0; } else if (d.y.vals[i][2*j] < .5 && d.y.vals[i][2*j+1] > .5){ d.y.vals[i][2*j] = 0; d.y.vals[i][2*j+1] = 1; } else { d.y.vals[i][2*j] = SECRET_NUM; d.y.vals[i][2*j+1] = SECRET_NUM; } } fclose(fp1); fclose(fp2); free_image(im1); free_image(im2); } if(m) free(paths); return d; } data load_data_swag(char **paths, int n, int classes, float jitter) { int index = random_gen()%n; char *random_path = paths[index]; image orig = load_image_color(random_path, 0, 0); int h = orig.h; int w = orig.w; data d = {0}; d.shallow = 0; d.w = w; d.h = h; d.X.rows = 1; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*3; int k = (4+classes)*30; d.y = make_matrix(1, k); int dw = w*jitter; int dh = h*jitter; int pleft = rand_uniform(-dw, dw); int pright = rand_uniform(-dw, dw); int ptop = rand_uniform(-dh, dh); int pbot = rand_uniform(-dh, dh); int swidth = w - pleft - pright; int sheight = h - ptop - pbot; float sx = (float)swidth / w; float sy = (float)sheight / h; int flip = random_gen()%2; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft/w)/sx; float dy = ((float)ptop /h)/sy; image sized = resize_image(cropped, w, h); if(flip) flip_image(sized); d.X.vals[0] = sized.data; fill_truth_swag(random_path, d.y.vals[0], classes, flip, dx, dy, 1./sx, 1./sy); free_image(orig); free_image(cropped); return d; } void blend_truth(float *new_truth, int boxes, float *old_truth) { const int t_size = 4 + 1; int count_new_truth = 0; int t; for (t = 0; t < boxes; ++t) { float x = new_truth[t*(4 + 1)]; if (!x) break; count_new_truth++; } for (t = count_new_truth; t < boxes; ++t) { float *new_truth_ptr = new_truth + t*t_size; float *old_truth_ptr = old_truth + (t - count_new_truth)*t_size; float x = old_truth_ptr[0]; if (!x) break; new_truth_ptr[0] = old_truth_ptr[0]; new_truth_ptr[1] = old_truth_ptr[1]; new_truth_ptr[2] = old_truth_ptr[2]; new_truth_ptr[3] = old_truth_ptr[3]; new_truth_ptr[4] = old_truth_ptr[4]; } //printf("\n was %d bboxes, now %d bboxes \n", count_new_truth, t); } void blend_truth_mosaic(float *new_truth, int boxes, float *old_truth, int w, int h, float cut_x, float cut_y, int i_mixup, int left_shift, int right_shift, int top_shift, int bot_shift) { const int t_size = 4 + 1; int count_new_truth = 0; int t; for (t = 0; t < boxes; ++t) { float x = new_truth[t*(4 + 1)]; if (!x) break; count_new_truth++; } int new_t = count_new_truth; for (t = count_new_truth; t < boxes; ++t) { float *new_truth_ptr = new_truth + new_t*t_size; new_truth_ptr[0] = 0; float *old_truth_ptr = old_truth + (t - count_new_truth)*t_size; float x = old_truth_ptr[0]; if (!x) break; float xb = old_truth_ptr[0]; float yb = old_truth_ptr[1]; float wb = old_truth_ptr[2]; float hb = old_truth_ptr[3]; // shift 4 images if (i_mixup == 0) { xb = xb - (float)(w - cut_x - right_shift) / w; yb = yb - (float)(h - cut_y - bot_shift) / h; } if (i_mixup == 1) { xb = xb + (float)(cut_x - left_shift) / w; yb = yb - (float)(h - cut_y - bot_shift) / h; } if (i_mixup == 2) { xb = xb - (float)(w - cut_x - right_shift) / w; yb = yb + (float)(cut_y - top_shift) / h; } if (i_mixup == 3) { xb = xb + (float)(cut_x - left_shift) / w; yb = yb + (float)(cut_y - top_shift) / h; } int left = (xb - wb / 2)*w; int right = (xb + wb / 2)*w; int top = (yb - hb / 2)*h; int bot = (yb + hb / 2)*h; // fix out of bound if (left < 0) { float diff = (float)left / w; xb = xb - diff / 2; wb = wb + diff; } if (right > w) { float diff = (float)(right - w) / w; xb = xb - diff / 2; wb = wb - diff; } if (top < 0) { float diff = (float)top / h; yb = yb - diff / 2; hb = hb + diff; } if (bot > h) { float diff = (float)(bot - h) / h; yb = yb - diff / 2; hb = hb - diff; } left = (xb - wb / 2)*w; right = (xb + wb / 2)*w; top = (yb - hb / 2)*h; bot = (yb + hb / 2)*h; // leave only within the image if(left >= 0 && right <= w && top >= 0 && bot <= h && wb > 0 && wb < 1 && hb > 0 && hb < 1 && xb > 0 && xb < 1 && yb > 0 && yb < 1) { new_truth_ptr[0] = xb; new_truth_ptr[1] = yb; new_truth_ptr[2] = wb; new_truth_ptr[3] = hb; new_truth_ptr[4] = old_truth_ptr[4]; new_t++; } } //printf("\n was %d bboxes, now %d bboxes \n", count_new_truth, t); } #ifdef OPENCV #include "http_stream.h" data load_data_detection(int n, char **paths, int m, int w, int h, int c, int boxes, int classes, int use_flip, int use_gaussian_noise, int use_blur, int use_mixup, float jitter, float hue, float saturation, float exposure, int mini_batch, int track, int augment_speed, int letter_box, int show_imgs) { const int random_index = random_gen(); c = c ? c : 3; if (use_mixup == 2) { printf("\n cutmix=1 - isn't supported for Detector \n"); exit(0); } if (use_mixup == 3 && letter_box) { printf("\n Combination: letter_box=1 & mosaic=1 - isn't supported, use only 1 of these parameters \n"); exit(0); } if (random_gen() % 2 == 0) use_mixup = 0; int i; int *cut_x = NULL, *cut_y = NULL; if (use_mixup == 3) { cut_x = (int*)calloc(n, sizeof(int)); cut_y = (int*)calloc(n, sizeof(int)); const float min_offset = 0.2; // 20% for (i = 0; i < n; ++i) { cut_x[i] = rand_int(w*min_offset, w*(1 - min_offset)); cut_y[i] = rand_int(h*min_offset, h*(1 - min_offset)); } } data d = {0}; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*c; float r1 = 0, r2 = 0, r3 = 0, r4 = 0, r_scale = 0; float dhue = 0, dsat = 0, dexp = 0, flip = 0, blur = 0; int augmentation_calculated = 0, gaussian_noise = 0; d.y = make_matrix(n, 5*boxes); int i_mixup = 0; for (i_mixup = 0; i_mixup <= use_mixup; i_mixup++) { if (i_mixup) augmentation_calculated = 0; // recalculate augmentation for the 2nd sequence if(track==1) char **random_paths; if (track) random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed); else random_paths = get_random_paths(paths, n, m); for (i = 0; i < n; ++i) { float *truth = (float*)xcalloc(5 * boxes, sizeof(float)); const char *filename = random_paths[i]; int flag = (c >= 3); mat_cv *src; src = load_image_mat_cv(filename, flag); if (src == NULL) { if (check_mistakes) { printf("\n Error in load_data_detection() - OpenCV \n"); getchar(); } continue; } int oh = get_height_mat(src); int ow = get_width_mat(src); int dw = (ow*jitter); int dh = (oh*jitter); if (!augmentation_calculated || !track) { augmentation_calculated = 1; r1 = random_float(); r2 = random_float(); r3 = random_float(); r4 = random_float(); r_scale = random_float(); dhue = rand_uniform_strong(-hue, hue); dsat = rand_scale(saturation); dexp = rand_scale(exposure); flip = use_flip ? random_gen() % 2 : 0; if (use_blur) { int tmp_blur = rand_int(0, 2); // 0 - disable, 1 - blur background, 2 - blur the whole image if (tmp_blur == 0) blur = 0; else if (tmp_blur == 1) blur = 1; else blur = use_blur; } if (use_gaussian_noise && rand_int(0, 1) == 1) gaussian_noise = use_gaussian_noise; else gaussian_noise = 0; } int pleft = rand_precalc_random(-dw, dw, r1); int pright = rand_precalc_random(-dw, dw, r2); int ptop = rand_precalc_random(-dh, dh, r3); int pbot = rand_precalc_random(-dh, dh, r4); //printf("\n pleft = %d, pright = %d, ptop = %d, pbot = %d, ow = %d, oh = %d \n", pleft, pright, ptop, pbot, ow, oh); //float scale = rand_precalc_random(.25, 2, r_scale); // unused currently if (letter_box) { float img_ar = (float)ow / (float)oh; float net_ar = (float)w / (float)h; float result_ar = img_ar / net_ar; //printf(" ow = %d, oh = %d, w = %d, h = %d, img_ar = %f, net_ar = %f, result_ar = %f \n", ow, oh, w, h, img_ar, net_ar, result_ar); if (result_ar > 1) // sheight - should be increased { float oh_tmp = ow / net_ar; float delta_h = (oh_tmp - oh)/2; ptop = ptop - delta_h; pbot = pbot - delta_h; //printf(" result_ar = %f, oh_tmp = %f, delta_h = %d, ptop = %f, pbot = %f \n", result_ar, oh_tmp, delta_h, ptop, pbot); } else // swidth - should be increased { float ow_tmp = oh * net_ar; float delta_w = (ow_tmp - ow)/2; pleft = pleft - delta_w; pright = pright - delta_w; //printf(" result_ar = %f, ow_tmp = %f, delta_w = %d, pleft = %f, pright = %f \n", result_ar, ow_tmp, delta_w, pleft, pright); } } int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; float dx = ((float)pleft / ow) / sx; float dy = ((float)ptop / oh) / sy; int min_w_h = fill_truth_detection(filename, boxes, truth, classes, flip, dx, dy, 1. / sx, 1. / sy, w, h); if ((min_w_h / 8) < blur && blur > 1) blur = min_w_h / 8; // disable blur if one of the objects is too small image ai = image_data_augmentation(src, w, h, pleft, ptop, swidth, sheight, flip, dhue, dsat, dexp, gaussian_noise, blur, boxes, truth); if (use_mixup == 0) { d.X.vals[i] = ai.data; memcpy(d.y.vals[i], truth, 5 * boxes * sizeof(float)); } else if (use_mixup == 1) { if (i_mixup == 0) { d.X.vals[i] = ai.data; memcpy(d.y.vals[i], truth, 5 * boxes * sizeof(float)); } else if (i_mixup == 1) { image old_img = make_empty_image(w, h, c); old_img.data = d.X.vals[i]; //show_image(ai, "new"); //show_image(old_img, "old"); //wait_until_press_key_cv(); blend_images_cv(ai, 0.5, old_img, 0.5); blend_truth(d.y.vals[i], boxes, truth); free_image(old_img); d.X.vals[i] = ai.data; } } else if (use_mixup == 3) { if (i_mixup == 0) { image tmp_img = make_image(w, h, c); d.X.vals[i] = tmp_img.data; } if (flip) { int tmp = pleft; pleft = pright; pright = tmp; } const int left_shift = min_val_cmp(cut_x[i], max_val_cmp(0, (-pleft*w / ow))); const int top_shift = min_val_cmp(cut_y[i], max_val_cmp(0, (-ptop*h / oh))); const int right_shift = min_val_cmp((w - cut_x[i]), max_val_cmp(0, (-pright*w / ow))); const int bot_shift = min_val_cmp(h - cut_y[i], max_val_cmp(0, (-pbot*h / oh))); int k, x, y; for (k = 0; k < c; ++k) { for (y = 0; y < h; ++y) { int j = y*w + k*w*h; if (i_mixup == 0 && y < cut_y[i]) { int j_src = (w - cut_x[i] - right_shift) + (y + h - cut_y[i] - bot_shift)*w + k*w*h; memcpy(&d.X.vals[i][j + 0], &ai.data[j_src], cut_x[i] * sizeof(float)); } if (i_mixup == 1 && y < cut_y[i]) { int j_src = left_shift + (y + h - cut_y[i] - bot_shift)*w + k*w*h; memcpy(&d.X.vals[i][j + cut_x[i]], &ai.data[j_src], (w-cut_x[i]) * sizeof(float)); } if (i_mixup == 2 && y >= cut_y[i]) { int j_src = (w - cut_x[i] - right_shift) + (top_shift + y - cut_y[i])*w + k*w*h; memcpy(&d.X.vals[i][j + 0], &ai.data[j_src], cut_x[i] * sizeof(float)); } if (i_mixup == 3 && y >= cut_y[i]) { int j_src = left_shift + (top_shift + y - cut_y[i])*w + k*w*h; memcpy(&d.X.vals[i][j + cut_x[i]], &ai.data[j_src], (w - cut_x[i]) * sizeof(float)); } } } blend_truth_mosaic(d.y.vals[i], boxes, truth, w, h, cut_x[i], cut_y[i], i_mixup, left_shift, right_shift, top_shift, bot_shift); free_image(ai); ai.data = d.X.vals[i]; } if (show_imgs && i_mixup == use_mixup) // delete i_mixup { image tmp_ai = copy_image(ai); char buff[1000]; //sprintf(buff, "aug_%d_%d_%s_%d", random_index, i, basecfg((char*)filename), random_gen()); sprintf(buff, "aug_%d_%d_%d", random_index, i, random_gen()); int t; for (t = 0; t < boxes; ++t) { box b = float_to_box_stride(d.y.vals[i] + t*(4 + 1), 1); if (!b.x) break; int left = (b.x - b.w / 2.)*ai.w; int right = (b.x + b.w / 2.)*ai.w; int top = (b.y - b.h / 2.)*ai.h; int bot = (b.y + b.h / 2.)*ai.h; draw_box_width(tmp_ai, left, top, right, bot, 1, 150, 100, 50); // 3 channels RGB } save_image(tmp_ai, buff); if (show_imgs == 1) { //char buff_src[1000]; //sprintf(buff_src, "src_%d_%d_%s_%d", random_index, i, basecfg((char*)filename), random_gen()); //show_image_mat(src, buff_src); show_image(tmp_ai, buff); wait_until_press_key_cv(); } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Click on window and press ESC button \n"); free_image(tmp_ai); } release_mat(&src); free(truth); } if (random_paths) free(random_paths); } return d; } #else // OPENCV void blend_images(image new_img, float alpha, image old_img, float beta) { int data_size = new_img.w * new_img.h * new_img.c; int i; #pragma omp parallel for for (i = 0; i < data_size; ++i) new_img.data[i] = new_img.data[i] * alpha + old_img.data[i] * beta; } data load_data_detection(int n, char **paths, int m, int w, int h, int c, int boxes, int classes, int use_flip, int gaussian_noise, int use_blur, int use_mixup, float jitter, float hue, float saturation, float exposure, int mini_batch, int track, int augment_speed, int letter_box, int show_imgs) { const int random_index = random_gen(); c = c ? c : 3; char **random_paths; char **mixup_random_paths = NULL; if(track) random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed); else random_paths = get_random_paths(paths, n, m); //assert(use_mixup < 2); if (use_mixup == 2) { printf("\n cutmix=1 - isn't supported for Detector \n"); exit(0); } if (use_mixup == 3) { printf("\n mosaic=1 - compile Darknet with OpenCV for using mosaic=1 \n"); exit(0); } int mixup = use_mixup ? random_gen() % 2 : 0; //printf("\n mixup = %d \n", mixup); if (mixup) { if (track) mixup_random_paths = get_sequential_paths(paths, n, m, mini_batch, augment_speed); else mixup_random_paths = get_random_paths(paths, n, m); } int i; data d = { 0 }; d.shallow = 0; d.X.rows = n; d.X.vals = (float**)xcalloc(d.X.rows, sizeof(float*)); d.X.cols = h*w*c; float r1 = 0, r2 = 0, r3 = 0, r4 = 0, r_scale; float dhue = 0, dsat = 0, dexp = 0, flip = 0; int augmentation_calculated = 0; d.y = make_matrix(n, 5 * boxes); int i_mixup = 0; for (i_mixup = 0; i_mixup <= mixup; i_mixup++) { if (i_mixup) augmentation_calculated = 0; for (i = 0; i < n; ++i) { float *truth = (float*)xcalloc(5 * boxes, sizeof(float)); char *filename = (i_mixup) ? mixup_random_paths[i] : random_paths[i]; image orig = load_image(filename, 0, 0, c); int oh = orig.h; int ow = orig.w; int dw = (ow*jitter); int dh = (oh*jitter); if (!augmentation_calculated || !track) { augmentation_calculated = 1; r1 = random_float(); r2 = random_float(); r3 = random_float(); r4 = random_float(); r_scale = random_float(); dhue = rand_uniform_strong(-hue, hue); dsat = rand_scale(saturation); dexp = rand_scale(exposure); flip = use_flip ? random_gen() % 2 : 0; } int pleft = rand_precalc_random(-dw, dw, r1); int pright = rand_precalc_random(-dw, dw, r2); int ptop = rand_precalc_random(-dh, dh, r3); int pbot = rand_precalc_random(-dh, dh, r4); float scale = rand_precalc_random(.25, 2, r_scale); // unused currently if (letter_box) { float img_ar = (float)ow / (float)oh; float net_ar = (float)w / (float)h; float result_ar = img_ar / net_ar; //printf(" ow = %d, oh = %d, w = %d, h = %d, img_ar = %f, net_ar = %f, result_ar = %f \n", ow, oh, w, h, img_ar, net_ar, result_ar); if (result_ar > 1) // sheight - should be increased { float oh_tmp = ow / net_ar; float delta_h = (oh_tmp - oh) / 2; ptop = ptop - delta_h; pbot = pbot - delta_h; //printf(" result_ar = %f, oh_tmp = %f, delta_h = %d, ptop = %f, pbot = %f \n", result_ar, oh_tmp, delta_h, ptop, pbot); } else // swidth - should be increased { float ow_tmp = oh * net_ar; float delta_w = (ow_tmp - ow) / 2; pleft = pleft - delta_w; pright = pright - delta_w; //printf(" result_ar = %f, ow_tmp = %f, delta_w = %d, pleft = %f, pright = %f \n", result_ar, ow_tmp, delta_w, pleft, pright); } } int swidth = ow - pleft - pright; int sheight = oh - ptop - pbot; float sx = (float)swidth / ow; float sy = (float)sheight / oh; image cropped = crop_image(orig, pleft, ptop, swidth, sheight); float dx = ((float)pleft / ow) / sx; float dy = ((float)ptop / oh) / sy; image sized = resize_image(cropped, w, h); if (flip) flip_image(sized); distort_image(sized, dhue, dsat, dexp); //random_distort_image(sized, hue, saturation, exposure); fill_truth_detection(filename, boxes, truth, classes, flip, dx, dy, 1. / sx, 1. / sy, w, h); if (i_mixup) { image old_img = sized; old_img.data = d.X.vals[i]; //show_image(sized, "new"); //show_image(old_img, "old"); //wait_until_press_key_cv(); blend_images(sized, 0.5, old_img, 0.5); blend_truth(truth, boxes, d.y.vals[i]); free_image(old_img); } d.X.vals[i] = sized.data; memcpy(d.y.vals[i], truth, 5 * boxes * sizeof(float)); if (show_imgs)// && i_mixup) { char buff[1000]; sprintf(buff, "aug_%d_%d_%s_%d", random_index, i, basecfg(filename), random_gen()); int t; for (t = 0; t < boxes; ++t) { box b = float_to_box_stride(d.y.vals[i] + t*(4 + 1), 1); if (!b.x) break; int left = (b.x - b.w / 2.)*sized.w; int right = (b.x + b.w / 2.)*sized.w; int top = (b.y - b.h / 2.)*sized.h; int bot = (b.y + b.h / 2.)*sized.h; draw_box_width(sized, left, top, right, bot, 1, 150, 100, 50); // 3 channels RGB } save_image(sized, buff); if (show_imgs == 1) { show_image(sized, buff); wait_until_press_key_cv(); } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Press Enter: \n"); //getchar(); } free_image(orig); free_image(cropped); free(truth); } } free(random_paths); if (mixup_random_paths) free(mixup_random_paths); return d; } #endif // OPENCV void *load_thread(void *ptr) { //srand(time(0)); //printf("Loading data: %d\n", random_gen()); load_args a = *(struct load_args*)ptr; if(a.exposure == 0) a.exposure = 1; if(a.saturation == 0) a.saturation = 1; if(a.aspect == 0) a.aspect = 1; if (a.type == OLD_CLASSIFICATION_DATA){ *a.d = load_data_old(a.paths, a.n, a.m, a.labels, a.classes, a.w, a.h); } else if (a.type == CLASSIFICATION_DATA){ *a.d = load_data_augment(a.paths, a.n, a.m, a.labels, a.classes, a.hierarchy, a.flip, a.min, a.max, a.w, a.h, a.angle, a.aspect, a.hue, a.saturation, a.exposure, a.mixup, a.blur, a.show_imgs, a.label_smooth_eps, a.dontuse_opencv); } else if (a.type == SUPER_DATA){ *a.d = load_data_super(a.paths, a.n, a.m, a.w, a.h, a.scale); } else if (a.type == WRITING_DATA){ *a.d = load_data_writing(a.paths, a.n, a.m, a.w, a.h, a.out_w, a.out_h); } else if (a.type == REGION_DATA){ *a.d = load_data_region(a.n, a.paths, a.m, a.w, a.h, a.num_boxes, a.classes, a.jitter, a.hue, a.saturation, a.exposure); } else if (a.type == DETECTION_DATA){ *a.d = load_data_detection(a.n, a.paths, a.m, a.w, a.h, a.c, a.num_boxes, a.classes, a.flip, a.gaussian_noise, a.blur, a.mixup, a.jitter, a.hue, a.saturation, a.exposure, a.mini_batch, a.track, a.augment_speed, a.letter_box, a.show_imgs); } else if (a.type == SWAG_DATA){ *a.d = load_data_swag(a.paths, a.n, a.classes, a.jitter); } else if (a.type == COMPARE_DATA){ *a.d = load_data_compare(a.n, a.paths, a.m, a.classes, a.w, a.h); } else if (a.type == IMAGE_DATA){ *(a.im) = load_image(a.path, 0, 0, a.c); *(a.resized) = resize_image(*(a.im), a.w, a.h); }else if (a.type == LETTERBOX_DATA) { *(a.im) = load_image(a.path, 0, 0, a.c); *(a.resized) = letterbox_image(*(a.im), a.w, a.h); } else if (a.type == TAG_DATA){ *a.d = load_data_tag(a.paths, a.n, a.m, a.classes, a.flip, a.min, a.max, a.w, a.h, a.angle, a.aspect, a.hue, a.saturation, a.exposure); } free(ptr); return 0; } pthread_t load_data_in_thread(load_args args) { pthread_t thread; struct load_args* ptr = (load_args*)xcalloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_thread, ptr)) error("Thread creation failed"); return thread; } static const int thread_wait_ms = 5; static volatile int flag_exit; static volatile int * run_load_data = NULL; static load_args * args_swap = NULL; static pthread_t* threads = NULL; pthread_mutex_t mtx_load_data = PTHREAD_MUTEX_INITIALIZER; void *run_thread_loop(void *ptr) { const int i = *(int *)ptr; while (!custom_atomic_load_int(&flag_exit)) { while (!custom_atomic_load_int(&run_load_data[i])) { if (custom_atomic_load_int(&flag_exit)) { free(ptr); return 0; } this_thread_sleep_for(thread_wait_ms); } pthread_mutex_lock(&mtx_load_data); load_args *args_local = (load_args *)xcalloc(1, sizeof(load_args)); *args_local = args_swap[i]; pthread_mutex_unlock(&mtx_load_data); load_thread(args_local); custom_atomic_store_int(&run_load_data[i], 0); } free(ptr); return 0; } void *load_threads(void *ptr) { //srand(time(0)); int i; load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; data *out = args.d; int total = args.n; free(ptr); data* buffers = (data*)xcalloc(args.threads, sizeof(data)); if (!threads) { threads = (pthread_t*)xcalloc(args.threads, sizeof(pthread_t)); run_load_data = (volatile int *)xcalloc(args.threads, sizeof(int)); args_swap = (load_args *)xcalloc(args.threads, sizeof(load_args)); fprintf(stderr, " Create %d permanent cpu-threads \n", args.threads); for (i = 0; i < args.threads; ++i) { int* ptr = (int*)xcalloc(1, sizeof(int)); *ptr = i; if (pthread_create(&threads[i], 0, run_thread_loop, ptr)) error("Thread creation failed"); } } for (i = 0; i < args.threads; ++i) { args.d = buffers + i; args.n = (i + 1) * total / args.threads - i * total / args.threads; pthread_mutex_lock(&mtx_load_data); args_swap[i] = args; pthread_mutex_unlock(&mtx_load_data); custom_atomic_store_int(&run_load_data[i], 1); // run thread } for (i = 0; i < args.threads; ++i) { while (custom_atomic_load_int(&run_load_data[i])) this_thread_sleep_for(thread_wait_ms); // join } /* pthread_t* threads = (pthread_t*)xcalloc(args.threads, sizeof(pthread_t)); for(i = 0; i < args.threads; ++i){ args.d = buffers + i; args.n = (i+1) * total/args.threads - i * total/args.threads; threads[i] = load_data_in_thread(args); } for(i = 0; i < args.threads; ++i){ pthread_join(threads[i], 0); } */ *out = concat_datas(buffers, args.threads); out->shallow = 0; for(i = 0; i < args.threads; ++i){ buffers[i].shallow = 1; free_data(buffers[i]); } free(buffers); //free(threads); return 0; } void free_load_threads(void *ptr) { load_args args = *(load_args *)ptr; if (args.threads == 0) args.threads = 1; int i; if (threads) { custom_atomic_store_int(&flag_exit, 1); for (i = 0; i < args.threads; ++i) { pthread_join(threads[i], 0); } free((void*)run_load_data); free(args_swap); free(threads); threads = NULL; custom_atomic_store_int(&flag_exit, 0); } } pthread_t load_data(load_args args) { pthread_t thread; struct load_args* ptr = (load_args*)xcalloc(1, sizeof(struct load_args)); *ptr = args; if(pthread_create(&thread, 0, load_threads, ptr)) error("Thread creation failed"); return thread; } data load_data_writing(char **paths, int n, int m, int w, int h, int out_w, int out_h) { if(m) paths = get_random_paths(paths, n, m); char **replace_paths = find_replace_paths(paths, n, ".png", "-label.png"); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_image_paths_gray(replace_paths, n, out_w, out_h); if(m) free(paths); int i; for(i = 0; i < n; ++i) free(replace_paths[i]); free(replace_paths); return d; } data load_data_old(char **paths, int n, int m, char **labels, int k, int w, int h) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_paths(paths, n, w, h); d.y = load_labels_paths(paths, n, labels, k, 0, 0); if(m) free(paths); return d; } /* data load_data_study(char **paths, int n, int m, char **labels, int k, int min, int max, int size, float angle, float aspect, float hue, float saturation, float exposure) { data d = {0}; d.indexes = calloc(n, sizeof(int)); if(m) paths = get_random_paths_indexes(paths, n, m, d.indexes); d.shallow = 0; d.X = load_image_augment_paths(paths, n, flip, min, max, size, angle, aspect, hue, saturation, exposure); d.y = load_labels_paths(paths, n, labels, k); if(m) free(paths); return d; } */ data load_data_super(char **paths, int n, int m, int w, int h, int scale) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; int i; d.X.rows = n; d.X.vals = (float**)xcalloc(n, sizeof(float*)); d.X.cols = w*h*3; d.y.rows = n; d.y.vals = (float**)xcalloc(n, sizeof(float*)); d.y.cols = w*scale * h*scale * 3; for(i = 0; i < n; ++i){ image im = load_image_color(paths[i], 0, 0); image crop = random_crop_image(im, w*scale, h*scale); int flip = random_gen()%2; if (flip) flip_image(crop); image resize = resize_image(crop, w, h); d.X.vals[i] = resize.data; d.y.vals[i] = crop.data; free_image(im); } if(m) free(paths); return d; } data load_data_augment(char **paths, int n, int m, char **labels, int k, tree *hierarchy, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure, int use_mixup, int use_blur, int show_imgs, float label_smooth_eps, int dontuse_opencv) { char **paths_stored = paths; if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.shallow = 0; d.X = load_image_augment_paths(paths, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv); d.y = load_labels_paths(paths, n, labels, k, hierarchy, label_smooth_eps); if (use_mixup && rand_int(0, 1)) { char **paths_mix = get_random_paths(paths_stored, n, m); data d2 = { 0 }; d2.shallow = 0; d2.X = load_image_augment_paths(paths_mix, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv); d2.y = load_labels_paths(paths_mix, n, labels, k, hierarchy, label_smooth_eps); free(paths_mix); data d3 = { 0 }; d3.shallow = 0; data d4 = { 0 }; d4.shallow = 0; if (use_mixup >= 3) { char **paths_mix3 = get_random_paths(paths_stored, n, m); d3.X = load_image_augment_paths(paths_mix3, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv); d3.y = load_labels_paths(paths_mix3, n, labels, k, hierarchy, label_smooth_eps); free(paths_mix3); char **paths_mix4 = get_random_paths(paths_stored, n, m); d4.X = load_image_augment_paths(paths_mix4, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, dontuse_opencv); d4.y = load_labels_paths(paths_mix4, n, labels, k, hierarchy, label_smooth_eps); free(paths_mix4); } // mix int i, j; for (i = 0; i < d2.X.rows; ++i) { int mixup = use_mixup; if (use_mixup == 4) mixup = rand_int(2, 3); // alternate CutMix and Mosaic // MixUp ----------------------------------- if (mixup == 1) { // mix images for (j = 0; j < d2.X.cols; ++j) { d.X.vals[i][j] = (d.X.vals[i][j] + d2.X.vals[i][j]) / 2.0f; } // mix labels for (j = 0; j < d2.y.cols; ++j) { d.y.vals[i][j] = (d.y.vals[i][j] + d2.y.vals[i][j]) / 2.0f; } } // CutMix ----------------------------------- else if (mixup == 2) { const float min = 0.3; // 0.3*0.3 = 9% const float max = 0.8; // 0.8*0.8 = 64% const int cut_w = rand_int(w*min, w*max); const int cut_h = rand_int(h*min, h*max); const int cut_x = rand_int(0, w - cut_w - 1); const int cut_y = rand_int(0, h - cut_h - 1); const int left = cut_x; const int right = cut_x + cut_w; const int top = cut_y; const int bot = cut_y + cut_h; assert(cut_x >= 0 && cut_x <= w); assert(cut_y >= 0 && cut_y <= h); assert(cut_w >= 0 && cut_w <= w); assert(cut_h >= 0 && cut_h <= h); assert(right >= 0 && right <= w); assert(bot >= 0 && bot <= h); assert(top <= bot); assert(left <= right); const float alpha = (float)(cut_w*cut_h) / (float)(w*h); const float beta = 1 - alpha; int c, x, y; for (c = 0; c < 3; ++c) { for (y = top; y < bot; ++y) { for (x = left; x < right; ++x) { int j = x + y*w + c*w*h; d.X.vals[i][j] = d2.X.vals[i][j]; } } } //printf("\n alpha = %f, beta = %f \n", alpha, beta); // mix labels for (j = 0; j < d.y.cols; ++j) { d.y.vals[i][j] = d.y.vals[i][j] * beta + d2.y.vals[i][j] * alpha; } } // Mosaic ----------------------------------- else if (mixup == 3) { const float min_offset = 0.2; // 20% const int cut_x = rand_int(w*min_offset, w*(1 - min_offset)); const int cut_y = rand_int(h*min_offset, h*(1 - min_offset)); float s1 = (float)(cut_x * cut_y) / (w*h); float s2 = (float)((w - cut_x) * cut_y) / (w*h); float s3 = (float)(cut_x * (h - cut_y)) / (w*h); float s4 = (float)((w - cut_x) * (h - cut_y)) / (w*h); int c, x, y; for (c = 0; c < 3; ++c) { for (y = 0; y < h; ++y) { for (x = 0; x < w; ++x) { int j = x + y*w + c*w*h; if (x < cut_x && y < cut_y) d.X.vals[i][j] = d.X.vals[i][j]; if (x >= cut_x && y < cut_y) d.X.vals[i][j] = d2.X.vals[i][j]; if (x < cut_x && y >= cut_y) d.X.vals[i][j] = d3.X.vals[i][j]; if (x >= cut_x && y >= cut_y) d.X.vals[i][j] = d4.X.vals[i][j]; } } } for (j = 0; j < d.y.cols; ++j) { const float max_s = 1;// max_val_cmp(s1, max_val_cmp(s2, max_val_cmp(s3, s4))); d.y.vals[i][j] = d.y.vals[i][j] * s1 / max_s + d2.y.vals[i][j] * s2 / max_s + d3.y.vals[i][j] * s3 / max_s + d4.y.vals[i][j] * s4 / max_s; } } } free_data(d2); if (use_mixup >= 3) { free_data(d3); free_data(d4); } } #ifdef OPENCV if (use_blur) { int i; for (i = 0; i < d.X.rows; ++i) { if (random_gen() % 2) { image im = make_empty_image(w, h, 3); im.data = d.X.vals[i]; int ksize = use_blur; if (use_blur == 1) ksize = 17; image blurred = blur_image(im, ksize); free_image(im); d.X.vals[i] = blurred.data; //if (i == 0) { // show_image(im, "Not blurred"); // show_image(blurred, "blurred"); // wait_until_press_key_cv(); //} } } } #endif // OPENCV if (show_imgs) { int i, j; for (i = 0; i < d.X.rows; ++i) { image im = make_empty_image(w, h, 3); im.data = d.X.vals[i]; char buff[1000]; sprintf(buff, "aug_%d_%s_%d", i, basecfg((char*)paths[i]), random_gen()); save_image(im, buff); char buff_string[1000]; sprintf(buff_string, "\n Classes: "); for (j = 0; j < d.y.cols; ++j) { if (d.y.vals[i][j] > 0) { char buff_tmp[100]; sprintf(buff_tmp, " %d (%f), ", j, d.y.vals[i][j]); strcat(buff_string, buff_tmp); } } printf("%s \n", buff_string); if (show_imgs == 1) { show_image(im, buff); wait_until_press_key_cv(); } } printf("\nYou use flag -show_imgs, so will be saved aug_...jpg images. Click on window and press ESC button \n"); } if (m) free(paths); return d; } data load_data_tag(char **paths, int n, int m, int k, int use_flip, int min, int max, int w, int h, float angle, float aspect, float hue, float saturation, float exposure) { if(m) paths = get_random_paths(paths, n, m); data d = {0}; d.w = w; d.h = h; d.shallow = 0; d.X = load_image_augment_paths(paths, n, use_flip, min, max, w, h, angle, aspect, hue, saturation, exposure, 0); d.y = load_tags_paths(paths, n, k); if(m) free(paths); return d; } matrix concat_matrix(matrix m1, matrix m2) { int i, count = 0; matrix m; m.cols = m1.cols; m.rows = m1.rows+m2.rows; m.vals = (float**)xcalloc(m1.rows + m2.rows, sizeof(float*)); for(i = 0; i < m1.rows; ++i){ m.vals[count++] = m1.vals[i]; } for(i = 0; i < m2.rows; ++i){ m.vals[count++] = m2.vals[i]; } return m; } data concat_data(data d1, data d2) { data d = {0}; d.shallow = 1; d.X = concat_matrix(d1.X, d2.X); d.y = concat_matrix(d1.y, d2.y); return d; } data concat_datas(data *d, int n) { int i; data out = {0}; for(i = 0; i < n; ++i){ data newdata = concat_data(d[i], out); free_data(out); out = newdata; } return out; } data load_categorical_data_csv(char *filename, int target, int k) { data d = {0}; d.shallow = 0; matrix X = csv_to_matrix(filename); float *truth_1d = pop_column(&X, target); float **truth = one_hot_encode(truth_1d, X.rows, k); matrix y; y.rows = X.rows; y.cols = k; y.vals = truth; d.X = X; d.y = y; free(truth_1d); return d; } data load_cifar10_data(char *filename) { data d = {0}; d.shallow = 0; long i,j; matrix X = make_matrix(10000, 3072); matrix y = make_matrix(10000, 10); d.X = X; d.y = y; FILE *fp = fopen(filename, "rb"); if(!fp) file_error(filename); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class_id = bytes[0]; y.vals[i][class_id] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i][j] = (double)bytes[j+1]; } } //translate_data_rows(d, -128); scale_data_rows(d, 1./255); //normalize_data_rows(d); fclose(fp); return d; } void get_random_batch(data d, int n, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = random_gen()%d.X.rows; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void get_next_batch(data d, int n, int offset, float *X, float *y) { int j; for(j = 0; j < n; ++j){ int index = offset + j; memcpy(X+j*d.X.cols, d.X.vals[index], d.X.cols*sizeof(float)); memcpy(y+j*d.y.cols, d.y.vals[index], d.y.cols*sizeof(float)); } } void smooth_data(data d) { int i, j; float scale = 1. / d.y.cols; float eps = .1; for(i = 0; i < d.y.rows; ++i){ for(j = 0; j < d.y.cols; ++j){ d.y.vals[i][j] = eps * scale + (1-eps) * d.y.vals[i][j]; } } } data load_all_cifar10() { data d = {0}; d.shallow = 0; int i,j,b; matrix X = make_matrix(50000, 3072); matrix y = make_matrix(50000, 10); d.X = X; d.y = y; for(b = 0; b < 5; ++b){ char buff[256]; sprintf(buff, "data/cifar/cifar-10-batches-bin/data_batch_%d.bin", b+1); FILE *fp = fopen(buff, "rb"); if(!fp) file_error(buff); for(i = 0; i < 10000; ++i){ unsigned char bytes[3073]; fread(bytes, 1, 3073, fp); int class_id = bytes[0]; y.vals[i+b*10000][class_id] = 1; for(j = 0; j < X.cols; ++j){ X.vals[i+b*10000][j] = (double)bytes[j+1]; } } fclose(fp); } //normalize_data_rows(d); //translate_data_rows(d, -128); scale_data_rows(d, 1./255); smooth_data(d); return d; } data load_go(char *filename) { FILE *fp = fopen(filename, "rb"); matrix X = make_matrix(3363059, 361); matrix y = make_matrix(3363059, 361); int row, col; if(!fp) file_error(filename); char *label; int count = 0; while((label = fgetl(fp))){ int i; if(count == X.rows){ X = resize_matrix(X, count*2); y = resize_matrix(y, count*2); } sscanf(label, "%d %d", &row, &col); char *board = fgetl(fp); int index = row*19 + col; y.vals[count][index] = 1; for(i = 0; i < 19*19; ++i){ float val = 0; if(board[i] == '1') val = 1; else if(board[i] == '2') val = -1; X.vals[count][i] = val; } ++count; free(label); free(board); } X = resize_matrix(X, count); y = resize_matrix(y, count); data d = {0}; d.shallow = 0; d.X = X; d.y = y; fclose(fp); return d; } void randomize_data(data d) { int i; for(i = d.X.rows-1; i > 0; --i){ int index = random_gen()%i; float *swap = d.X.vals[index]; d.X.vals[index] = d.X.vals[i]; d.X.vals[i] = swap; swap = d.y.vals[index]; d.y.vals[index] = d.y.vals[i]; d.y.vals[i] = swap; } } void scale_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ scale_array(d.X.vals[i], d.X.cols, s); } } void translate_data_rows(data d, float s) { int i; for(i = 0; i < d.X.rows; ++i){ translate_array(d.X.vals[i], d.X.cols, s); } } void normalize_data_rows(data d) { int i; for(i = 0; i < d.X.rows; ++i){ normalize_array(d.X.vals[i], d.X.cols); } } data get_data_part(data d, int part, int total) { data p = {0}; p.shallow = 1; p.X.rows = d.X.rows * (part + 1) / total - d.X.rows * part / total; p.y.rows = d.y.rows * (part + 1) / total - d.y.rows * part / total; p.X.cols = d.X.cols; p.y.cols = d.y.cols; p.X.vals = d.X.vals + d.X.rows * part / total; p.y.vals = d.y.vals + d.y.rows * part / total; return p; } data get_random_data(data d, int num) { data r = {0}; r.shallow = 1; r.X.rows = num; r.y.rows = num; r.X.cols = d.X.cols; r.y.cols = d.y.cols; r.X.vals = (float**)xcalloc(num, sizeof(float*)); r.y.vals = (float**)xcalloc(num, sizeof(float*)); int i; for(i = 0; i < num; ++i){ int index = random_gen()%d.X.rows; r.X.vals[i] = d.X.vals[index]; r.y.vals[i] = d.y.vals[index]; } return r; } data *split_data(data d, int part, int total) { data* split = (data*)xcalloc(2, sizeof(data)); int i; int start = part*d.X.rows/total; int end = (part+1)*d.X.rows/total; data train ={0}; data test ={0}; train.shallow = test.shallow = 1; test.X.rows = test.y.rows = end-start; train.X.rows = train.y.rows = d.X.rows - (end-start); train.X.cols = test.X.cols = d.X.cols; train.y.cols = test.y.cols = d.y.cols; train.X.vals = (float**)xcalloc(train.X.rows, sizeof(float*)); test.X.vals = (float**)xcalloc(test.X.rows, sizeof(float*)); train.y.vals = (float**)xcalloc(train.y.rows, sizeof(float*)); test.y.vals = (float**)xcalloc(test.y.rows, sizeof(float*)); for(i = 0; i < start; ++i){ train.X.vals[i] = d.X.vals[i]; train.y.vals[i] = d.y.vals[i]; } for(i = start; i < end; ++i){ test.X.vals[i-start] = d.X.vals[i]; test.y.vals[i-start] = d.y.vals[i]; } for(i = end; i < d.X.rows; ++i){ train.X.vals[i-(end-start)] = d.X.vals[i]; train.y.vals[i-(end-start)] = d.y.vals[i]; } split[0] = train; split[1] = test; return split; }
divsufsort.c.inc.h
/* * divsufsort.c for libdivsufsort * Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. * * 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. */ #include "divsufsort_private.h" #ifdef _OPENMP # include <omp.h> #endif /*- Private Functions -*/ /* Sorts suffixes of type B*. */ static saidx_t sort_typeBstar(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n) { saidx_t *PAb, *ISAb, *buf; #ifdef _OPENMP saidx_t *curbuf; saidx_t l; #endif saidx_t i, j, k, t, m, bufsize; saint_t c0, c1; #ifdef _OPENMP saint_t d0, d1; int tmp; #endif /* Initialize bucket arrays. */ for(i = 0; i < BUCKET_A_SIZE; ++i) { bucket_A[i] = 0; } for(i = 0; i < BUCKET_B_SIZE; ++i) { bucket_B[i] = 0; } /* Count the number of occurrences of the first one or two characters of each type A, B and B* suffix. Moreover, store the beginning position of all type B* suffixes into the array SA. */ for(i = n - 1, m = n, c0 = T[n - 1]; 0 <= i;) { /* type A suffix. */ do { ++BUCKET_A(c1 = c0); } while((0 <= --i) && ((c0 = T[i]) >= c1)); if(0 <= i) { /* type B* suffix. */ ++BUCKET_BSTAR(c0, c1); SA[--m] = i; /* type B suffix. */ for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { ++BUCKET_B(c0, c1); } } } m = n - m; /* note: A type B* suffix is lexicographically smaller than a type B suffix that begins with the same first two characters. */ /* Calculate the index of start/end point of each bucket. */ for(c0 = 0, i = 0, j = 0; c0 < ALPHABET_SIZE; ++c0) { t = i + BUCKET_A(c0); BUCKET_A(c0) = i + j; /* start point */ i = t + BUCKET_B(c0, c0); for(c1 = c0 + 1; c1 < ALPHABET_SIZE; ++c1) { j += BUCKET_BSTAR(c0, c1); BUCKET_BSTAR(c0, c1) = j; /* end point */ i += BUCKET_B(c0, c1); } } if(0 < m) { /* Sort the type B* suffixes by their first two characters. */ PAb = SA + n - m; ISAb = SA + m; for(i = m - 2; 0 <= i; --i) { t = PAb[i], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = i; } t = PAb[m - 1], c0 = T[t], c1 = T[t + 1]; SA[--BUCKET_BSTAR(c0, c1)] = m - 1; /* Sort the type B* substrings using sssort. */ #ifdef _OPENMP tmp = omp_get_max_threads(); buf = SA + m, bufsize = (n - (2 * m)) / tmp; c0 = ALPHABET_SIZE - 2, c1 = ALPHABET_SIZE - 1, j = m; #pragma omp parallel default(shared) private(curbuf, k, l, d0, d1, tmp) { tmp = omp_get_thread_num(); curbuf = buf + tmp * bufsize; k = 0; for(;;) { #pragma omp critical(sssort_lock) { if(0 < (l = j)) { d0 = c0, d1 = c1; do { k = BUCKET_BSTAR(d0, d1); if(--d1 <= d0) { d1 = ALPHABET_SIZE - 1; if(--d0 < 0) { break; } } } while(((l - k) <= 1) && (0 < (l = k))); c0 = d0, c1 = d1, j = k; } } if(l == 0) { break; } sssort(T, PAb, SA + k, SA + l, curbuf, bufsize, 2, n, *(SA + k) == (m - 1)); } } #else buf = SA + m, bufsize = n - (2 * m); for(c0 = ALPHABET_SIZE - 2, j = m; 0 < j; --c0) { for(c1 = ALPHABET_SIZE - 1; c0 < c1; j = i, --c1) { i = BUCKET_BSTAR(c0, c1); if(1 < (j - i)) { sssort(T, PAb, SA + i, SA + j, buf, bufsize, 2, n, *(SA + i) == (m - 1)); } } } #endif /* Compute ranks of type B* substrings. */ for(i = m - 1; 0 <= i; --i) { if(0 <= SA[i]) { j = i; do { ISAb[SA[i]] = i; } while((0 <= --i) && (0 <= SA[i])); SA[i + 1] = i - j; if(i <= 0) { break; } } j = i; do { ISAb[SA[i] = ~SA[i]] = j; } while(SA[--i] < 0); ISAb[SA[i]] = j; } /* Construct the inverse suffix array of type B* suffixes using trsort. */ trsort(ISAb, SA, m, 1); /* Set the sorted order of tyoe B* suffixes. */ for(i = n - 1, j = m, c0 = T[n - 1]; 0 <= i;) { for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) >= c1); --i, c1 = c0) { } if(0 <= i) { t = i; for(--i, c1 = c0; (0 <= i) && ((c0 = T[i]) <= c1); --i, c1 = c0) { } SA[ISAb[--j]] = ((t == 0) || (1 < (t - i))) ? t : ~t; } } /* Calculate the index of start/end point of each bucket. */ BUCKET_B(ALPHABET_SIZE - 1, ALPHABET_SIZE - 1) = n; /* end point */ for(c0 = ALPHABET_SIZE - 2, k = m - 1; 0 <= c0; --c0) { i = BUCKET_A(c0 + 1) - 1; for(c1 = ALPHABET_SIZE - 1; c0 < c1; --c1) { t = i - BUCKET_B(c0, c1); BUCKET_B(c0, c1) = i; /* end point */ /* Move all type B* suffixes to the correct position. */ for(i = t, j = BUCKET_BSTAR(c0, c1); j <= k; --i, --k) { SA[i] = SA[k]; } } BUCKET_BSTAR(c0, c0 + 1) = i - BUCKET_B(c0, c0) + 1; /* start point */ BUCKET_B(c0, c0) = i; /* end point */ } } return m; } /* Constructs the suffix array by using the sorted order of type B* suffixes. */ static void construct_SA(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m) { saidx_t *i, *j, *k; saidx_t s; saint_t c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); *j = ~s; c0 = T[--s]; if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) =(saidx_t)(k - SA); } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else { assert(((s == 0) && (T[s] == c1)) || (s < 0)); *j = ~s; } } } } /* Construct the suffix array by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~(n - 1) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; if((s == 0) || (T[s - 1] < c0)) { s = ~s; } if(c0 != c2) { BUCKET_A(c2) = (saidx_t)(k - SA); k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else { assert(s < 0); *i = ~s; } } } /* Constructs the burrows-wheeler transformed string directly by using the sorted order of type B* suffixes. */ static saidx_t construct_BWT(const sauchar_t *T, saidx_t *SA, saidx_t *bucket_A, saidx_t *bucket_B, saidx_t n, saidx_t m) { saidx_t *i, *j, *k, *orig; saidx_t s; saint_t c0, c1, c2; if(0 < m) { /* Construct the sorted order of type B suffixes by using the sorted order of type B* suffixes. */ for(c1 = ALPHABET_SIZE - 2; 0 <= c1; --c1) { /* Scan the suffix array from right to left. */ for(i = SA + BUCKET_BSTAR(c1, c1 + 1), j = SA + BUCKET_A(c1 + 1) - 1, k = NULL, c2 = -1; i <= j; --j) { if(0 < (s = *j)) { assert(T[s] == c1); assert(((s + 1) < n) && (T[s] <= T[s + 1])); assert(T[s - 1] <= T[s]); c0 = T[--s]; *j = ~((saidx_t)c0); if((0 < s) && (T[s - 1] > c0)) { s = ~s; } if(c0 != c2) { if(0 <= c2) { BUCKET_B(c2, c1) = (saidx_t)(k - SA); } k = SA + BUCKET_B(c2 = c0, c1); } assert(k < j); *k-- = s; } else if(s != 0) { *j = ~s; #ifndef NDEBUG } else { assert(T[s] == c1); #endif } } } } /* Construct the BWTed string by using the sorted order of type B suffixes. */ k = SA + BUCKET_A(c2 = T[n - 1]); *k++ = (T[n - 2] < c2) ? ~((saidx_t)T[n - 2]) : (n - 1); /* Scan the suffix array from left to right. */ for(i = SA, j = SA + n, orig = SA; i < j; ++i) { if(0 < (s = *i)) { assert(T[s - 1] >= T[s]); c0 = T[--s]; *i = c0; if((0 < s) && (T[s - 1] < c0)) { s = ~((saidx_t)T[s - 1]); } if(c0 != c2) { BUCKET_A(c2) = (saidx_t)(k - SA); k = SA + BUCKET_A(c2 = c0); } assert(i < k); *k++ = s; } else if(s != 0) { *i = ~s; } else { orig = i; } } return (saidx_t)(orig - SA); } /*---------------------------------------------------------------------------*/ /*- Function -*/ saint_t divsufsort(const sauchar_t *T, saidx_t *SA, saidx_t n) { saidx_t *bucket_A, *bucket_B; saidx_t m; saint_t err = 0; /* Check arguments. */ if((T == NULL) || (SA == NULL) || (n < 0)) { return -1; } else if(n == 0) { return 0; } else if(n == 1) { SA[0] = 0; return 0; } else if(n == 2) { m = (T[0] < T[1]); SA[m ^ 1] = 0, SA[m] = 1; return 0; } bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t)); bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t)); /* Suffixsort. */ if((bucket_A != NULL) && (bucket_B != NULL)) { m = sort_typeBstar(T, SA, bucket_A, bucket_B, n); construct_SA(T, SA, bucket_A, bucket_B, n, m); } else { err = -2; } free(bucket_B); free(bucket_A); return err; } saidx_t divbwt(const sauchar_t *T, sauchar_t *U, saidx_t *A, saidx_t n) { saidx_t *B; saidx_t *bucket_A, *bucket_B; saidx_t m, pidx, i; /* Check arguments. */ if((T == NULL) || (U == NULL) || (n < 0)) { return -1; } else if(n <= 1) { if(n == 1) { U[0] = T[0]; } return n; } if((B = A) == NULL) { B = (saidx_t *)malloc((size_t)(n + 1) * sizeof(saidx_t)); } bucket_A = (saidx_t *)malloc(BUCKET_A_SIZE * sizeof(saidx_t)); bucket_B = (saidx_t *)malloc(BUCKET_B_SIZE * sizeof(saidx_t)); /* Burrows-Wheeler Transform. */ if((B != NULL) && (bucket_A != NULL) && (bucket_B != NULL)) { m = sort_typeBstar(T, B, bucket_A, bucket_B, n); pidx = construct_BWT(T, B, bucket_A, bucket_B, n, m); /* Copy to output string. */ U[0] = T[n - 1]; for(i = 0; i < pidx; ++i) { U[i + 1] = (sauchar_t)B[i]; } for(i += 1; i < n; ++i) { U[i] = (sauchar_t)B[i]; } pidx += 1; } else { pidx = -2; } free(bucket_B); free(bucket_A); if(A == NULL) { free(B); } return pidx; } const char * divsufsort_version(void) { return PROJECT_VERSION_FULL; }
mixed_tentusscher_myo_epi_2004_S1_10.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S1_10.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.6838324354870,0.00125861532112849,0.782531022046086,0.782339747189463,0.000171890042887048,0.486292974625246,0.00291620263464322,0.999998385881296,1.89662206007922e-08,1.86215027927160e-05,0.999772605771797,1.00726021297708,0.999997303478017,4.12841986112007e-05,0.532834056372551,10.1676164688339,139.406744560708}; 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 []={14.3749143448083,0.000106604137464535,0.000163318890080367,0.000429744441186708,0.266262734691489,0.186959465205765,0.123266589202760,3.29275100569290,0.0156860789687658,1.60533641843158,1092.89191410508,0.000432813436608356,0.580002884264747,0.0196175412254594,0.00284974997889632,3.23076589501517e-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; }
remarks_parallel_in_target_state_machine.c
// RUN: %clang_cc1 -verify=host -Rpass=openmp-opt -Rpass-analysis=openmp-opt -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -Rpass=openmp-opt -Rpass-analysis=openmp-opt -fopenmp -O2 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t.out // RUN: %clang_cc1 -fexperimental-new-pass-manager -verify -Rpass=openmp-opt -Rpass-analysis=openmp-opt -fopenmp -O2 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t.out // host-no-diagnostics void bar(void) { #pragma omp parallel // #1 \ // expected-remark@#1 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}} \ // expected-remark@#1 {{Parallel region is used in unknown ways; will not attempt to rewrite the state machine.}} { } } void foo(void) { #pragma omp target teams // #2 \ // expected-remark@#2 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__1_wrapper, kernel ID: __omp_offloading}} \ // expected-remark@#2 {{Target region containing the parallel region that is specialized. (parallel region ID: __omp_outlined__2_wrapper, kernel ID: __omp_offloading}} { #pragma omp parallel // #3 \ // expected-remark@#3 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}} \ // expected-remark@#3 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__1_wrapper, kernel ID: __omp_offloading}} { } bar(); #pragma omp parallel // #4 \ // expected-remark@#4 {{Found a parallel region that is called in a target region but not part of a combined target construct nor nested inside a target construct without intermediate code. This can lead to excessive register usage for unrelated target regions in the same translation unit due to spurious call edges assumed by ptxas.}} \ // expected-remark@#4 {{Specialize parallel region that is only reached from a single target region to avoid spurious call edges and excessive register usage in other target regions. (parallel region ID: __omp_outlined__2_wrapper, kernel ID: __omp_offloading}} { } } } void spmd(void) { // Verify we do not emit the remarks above for "SPMD" regions. #pragma omp target teams #pragma omp parallel { } #pragma omp target teams distribute parallel for for (int i = 0; i < 100; ++i) { } } // expected-remark@* {{OpenMP runtime call __kmpc_global_thread_num moved to beginning of OpenMP region}} // expected-remark@* 2 {{OpenMP runtime call __kmpc_global_thread_num deduplicated}}
workgroup_size_option1.c
#include <stdio.h> #include <omp.h> int main() { int num_threads = 0; int N = 100000; int a[N]; int b[N]; int c[N]; int i; #pragma omp target map(from: num_threads) { num_threads = omp_get_num_threads(); } printf("num_threads = %d\n", num_threads); for (i=0; i<N; i++) a[i]=0; for (i=0; i<N; i++) b[i]=i; #pragma omp target parallel for { for (int j = 0; j< N; j++) a[j]=b[j]; } #pragma omp target teams { #pragma omp distribute parallel for for (int j = 0; j< N; j++) a[j]=b[j]; #pragma omp distribute parallel for for (int j = 0; j< N; j++) c[j]=b[j]; } #pragma omp target teams distribute parallel for { for (int j = 0; j< N; j++) a[j]=b[j]; } #pragma omp target teams distribute parallel for thread_limit(64) { for (int j = 0; j< N; j++) a[j]=b[j]; } int rc = 0; for (i=0; i<N; i++) if (a[i] != b[i] || c[i] != b[i]) { rc++; printf ("Wrong value: a[%d]=%d c[%d]=%d\n", i, a[i], i, c[i]); } if (!rc) printf("Success\n"); return rc; } // Compiled with -fopenmp-gpu-threads-per-team=1024 /// CHECK: DEVID: 0 SGN:1 ConstWGSize:257 args: 1 teamsXthrds:([[S:[ ]*]][[NUM_TEAMS:[0-9]+]]X 257) /// CHECK: DEVID: 0 SGN:2 ConstWGSize:1024 args: 5 teamsXthrds:([[S:[ ]*]][[NUM_TEAMS:[0-9]+]]X1024) /// CHECK: DEVID: 0 SGN:3 ConstWGSize:257 args: 7 teamsXthrds:([[S:[ ]*]][[NUM_TEAMS:[0-9]+]]X 256) /// CHECK: DEVID: 0 SGN:2 ConstWGSize:1024 args: 5 teamsXthrds:([[S:[ ]*]][[NUM_TEAMS:[0-9]+]]X1024) /// CHECK: DEVID: 0 SGN:2 ConstWGSize:256 args: 5 teamsXthrds:([[S:[ ]*]][[NUM_TEAMS:[0-9]+]]X 64)
satravelling.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <omp.h> #include <unistd.h> #include <math.h> double initial_time; double clearcache [30000000]; float** matrix_distances; int * path; int cities; void clearCache () { int i; for (i = 0; i < 30000000; ++i) clearcache[i] = i; } void start (void) { double time = omp_get_wtime(); initial_time = time * 1000000; } double stop() { double time = omp_get_wtime(); double final_time = time * 1000000; return final_time - initial_time; } //calcula as permutações aleatórias void randperm(int* perm,int N){ int i,j,tmp; for(i=0;i<N;i++) perm[i] = i; for(i=0;i<N;i++){ j=rand()% ( N-i) + i; tmp = perm[j]; perm[j] = perm [i]; perm[i] = tmp; } } //calcula custos do caminho calculado float calculate_cost(int* path,int N){ int i,cost; cost = matrix_distances[path[N-1]][path[0]]; for(i=0;i<N;i++) cost += matrix_distances[path[i]][path[i+1]]; return cost; } //calcula distancia entre cidades void find_distances(int* x, int* y,int N){ int i,j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) matrix_distances[i][j] = sqrt(pow(x[i]-x[j],2) + pow(y[i]-y[j],2)); } void initialize_matrix(){ int i,j; matrix_distances = (float**) malloc(sizeof(float*) * cities ); path = (int*) malloc(sizeof(int) * cities); for (i =0;i<cities;i++){ path[i] = -1; matrix_distances[i] =malloc(sizeof(float) * cities); } for(i=0;i<cities;i++){ for(j=0;j<cities;j++){ matrix_distances[i][j] = 0; } } } float tspAnnealing(float** dist, int* path, int N, int iter, int num_proc,float temperatura){ int i,c,previous,next1,next2,priv_path[N],tmp; float cost,delta,newCost,random; delta = 0.0; cost = calculate_cost(path,N); #pragma omp parallel num_threads(num_proc) { newCost = cost; for (i = 0; i < N; i++) { priv_path[i] = path[i]; } i=0; while(i<iter){ c= (rand() % N); if(c==0){ previous = N-1; next1=1; next2=2; } else{ previous = c-1; next1=(c+1) % N; next2 = (c+2) % N; } delta = dist[priv_path[previous]][next1] + dist[priv_path[c]][priv_path[next2]] - dist[priv_path[previous]][priv_path[c]] - dist[priv_path[next1]][priv_path[next2]]; random = (float)((double)rand()/(double)(RAND_MAX)) * 1; // nr random entre 0 e 1 para ver se aceita o caminho ou não if(delta < 0 || (exp(-delta/temperatura))>random){ tmp = priv_path[c]; priv_path[c] = priv_path[next1]; priv_path[next1] = tmp; newCost += delta; } if (delta<0) i=0; else i++; temperatura = 0.999*temperatura; } #pragma omp critical { if(newCost < cost){ cost = newCost; for(i=0;i<iter;i++) path [i] = priv_path [i]; } } } return cost ; } int main(int argc, char const *argv[]) { int i; float cost, tspCost; srand((unsigned) time(NULL)); if ( argc != 5 ){ printf ("Usage : ./ tsp <nr cidades> <nr de processos ><nr de iteracoes><temperatura inicial>\n"); return 0; } cities = atoi(argv[1]); int num_proc = atoi(argv[2]); int iter = atoi(argv[3]); int temp = atof(argv[4]); int* x_pos = malloc (cities * sizeof (int)) ; int* y_pos = malloc (cities * sizeof (int)) ; //gera coordenadas para cada cidade num quadrado de lado 50 for ( i = 0; i < cities; i++ ) { x_pos [i] = rand () % 50; y_pos [i] = rand () % 50; } for ( i = 0; i < cities; i++ ) { //printf("%f",y_pos[i]); } initialize_matrix(); find_distances(x_pos,y_pos,cities); randperm(path,cities); cost = calculate_cost(path,cities); printf("Custo Inicial :%f\n",cost); /* printf("Distancias:\n"); for(i = 0; i < cities; i++){ for(int j = 0; j < cities; j++){ printf("%f ", matrix_distances[i][j]); } printf("\n"); } printf("\n"); */ clearCache(); start(); tspCost = tspAnnealing(matrix_distances,path,cities,iter,num_proc,temp); printf("Tempo Simulated Annealing:%f\n",stop()); printf("Custo Ann : %f\n", tspCost); for(i = 0; i < cities; i++) printf("Permutações Ann: %d\n", path[i]); return 0; }
3d25pt_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 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 4; 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<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=floord(Nt-1,3);t1++) { lbp=max(ceild(t1,2),ceild(6*t1-Nt+2,6)); ubp=min(floord(4*Nt+Nz-9,24),floord(12*t1+Nz+6,24)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(max(1,ceild(24*t2-Nz+9,4)),3*t1+1),6*t1-6*t2+2);t3<=min(min(min(floord(4*Nt+Ny-9,4),floord(12*t1+Ny+15,4)),floord(24*t2+Ny+11,4)),floord(24*t1-24*t2+Nz+Ny+13,4));t3++) { for (t4=max(max(max(max(0,ceild(3*t1-3*t2-126,128)),ceild(3*t1-254,256)),ceild(24*t2-Nz-1011,1024)),ceild(4*t3-Ny-1011,1024));t4<=min(min(min(min(floord(4*Nt+Nx-9,1024),floord(12*t1+Nx+15,1024)),floord(24*t2+Nx+11,1024)),floord(4*t3+Nx-9,1024)),floord(24*t1-24*t2+Nz+Nx+13,1024));t4++) { for (t5=max(max(max(max(max(0,ceild(24*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(1024*t4-Nx+5,4)),3*t1),6*t1-6*t2+1);t5<=min(min(min(min(min(floord(24*t1-24*t2+Nz+18,4),Nt-1),3*t1+5),6*t2+4),t3-1),256*t4+254);t5++) { for (t6=max(max(24*t2,4*t5+4),-24*t1+24*t2+8*t5-23);t6<=min(min(24*t2+23,-24*t1+24*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) { lbv=max(1024*t4,4*t5+4); ubv=min(1024*t4+1023,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
validate.c
/* Copyright (C) 2010-2011 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #include "onesided.h" #include "common.h" #include <mpi.h> #include <stdint.h> #include <inttypes.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <stdio.h> #include <assert.h> /* This code assumes signed shifts are arithmetic, which they are on * practically all modern systems but is not guaranteed by C. */ static inline int64_t get_pred_from_pred_entry(int64_t val) { return (val << 16) >> 16; } static inline uint16_t get_depth_from_pred_entry(int64_t val) { return (val >> 48) & 0xFFFF; } static inline void write_pred_entry_depth(int64_t* loc, uint16_t depth) { *loc = (*loc & INT64_C(0xFFFFFFFFFFFF)) | ((int64_t)(depth & 0xFFFF) << 48); } /* Returns true if all values are in range. */ static int check_value_ranges(const int64_t nglobalverts, const size_t nlocalverts, const int64_t* const pred) { int any_range_errors = 0; { size_t ii; for (ii = 0; ii < nlocalverts; ii += CHUNKSIZE) { ptrdiff_t i_start = ii; ptrdiff_t i_end = ptrdiff_min(ii + CHUNKSIZE, nlocalverts); ptrdiff_t i; assert (i_start >= 0 && i_start <= (ptrdiff_t)nlocalverts); assert (i_end >= 0 && i_end <= (ptrdiff_t)nlocalverts); #pragma omp parallel for reduction(||:any_range_errors) for (i = i_start; i < i_end; ++i) { int64_t p = get_pred_from_pred_entry(pred[i]); if (p < -1 || p >= nglobalverts) { fprintf(stderr, "%d: Validation error: parent of vertex %" PRId64 " is out-of-range value %" PRId64 ".\n", rank, vertex_to_global_for_pred(rank, i), p); any_range_errors = 1; } } } } MPI_Allreduce(MPI_IN_PLACE, &any_range_errors, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD); return !any_range_errors; } /* Use the predecessors in the given map to write the BFS levels to the high 16 * bits of each element in pred; this also catches some problems in pred * itself. Returns true if the predecessor map is valid. */ static int build_bfs_depth_map(const int64_t nglobalverts, const size_t nlocalverts, const size_t maxlocalverts, const int64_t root, int64_t* const pred) { (void)nglobalverts; int validation_passed = 1; int root_owner; size_t root_local; get_vertex_distribution_for_pred(1, &root, &root_owner, &root_local); int root_is_mine = (root_owner == rank); if (root_is_mine) assert (root_local < nlocalverts); { ptrdiff_t i; #pragma omp parallel for for (i = 0; i < (ptrdiff_t)nlocalverts; ++i) write_pred_entry_depth(&pred[i], UINT16_MAX); if (root_is_mine) write_pred_entry_depth(&pred[root_local], 0); } int64_t* restrict pred_pred = (int64_t*)xMPI_Alloc_mem(size_min(CHUNKSIZE, nlocalverts) * sizeof(int64_t)); /* Predecessor info of predecessor vertex for each local vertex */ gather* pred_win = init_gather((void*)pred, nlocalverts, sizeof(int64_t), pred_pred, size_min(CHUNKSIZE, nlocalverts), size_min(CHUNKSIZE, nlocalverts), MPI_INT64_T); int64_t* restrict pred_vtx = (int64_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int64_t)); /* Vertex (not depth) part of pred map */ int* restrict pred_owner = (int*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int)); size_t* restrict pred_local = (size_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(size_t)); int iter_number = 0; { /* Iteratively update depth[v] = min(depth[v], depth[pred[v]] + 1) [saturating at UINT16_MAX] until no changes. */ while (1) { ++iter_number; int any_changes = 0; ptrdiff_t ii; for (ii = 0; ii < (ptrdiff_t)maxlocalverts; ii += CHUNKSIZE) { ptrdiff_t i_start = ptrdiff_min(ii, nlocalverts); ptrdiff_t i_end = ptrdiff_min(ii + CHUNKSIZE, nlocalverts); begin_gather(pred_win); ptrdiff_t i; assert (i_start >= 0 && i_start <= (ptrdiff_t)nlocalverts); assert (i_end >= 0 && i_end <= (ptrdiff_t)nlocalverts); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { pred_vtx[i - i_start] = get_pred_from_pred_entry(pred[i]); } get_vertex_distribution_for_pred(i_end - i_start, pred_vtx, pred_owner, pred_local); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { if (pred[i] != -1) { add_gather_request(pred_win, i - i_start, pred_owner[i - i_start], pred_local[i - i_start], i - i_start); } else { pred_pred[i - i_start] = -1; } } end_gather(pred_win); #pragma omp parallel for reduction(&&:validation_passed) reduction(||:any_changes) for (i = i_start; i < i_end; ++i) { if (rank == root_owner && (size_t)i == root_local) continue; if (get_depth_from_pred_entry(pred_pred[i - i_start]) != UINT16_MAX) { if (get_depth_from_pred_entry(pred[i]) != UINT16_MAX && get_depth_from_pred_entry(pred[i]) != get_depth_from_pred_entry(pred_pred[i - i_start]) + 1) { fprintf(stderr, "%d: Validation error: BFS predecessors do not form a tree; see vertices %" PRId64 " (depth %" PRIu16 ") and %" PRId64 " (depth %" PRIu16 ").\n", rank, vertex_to_global_for_pred(rank, i), get_depth_from_pred_entry(pred[i]), get_pred_from_pred_entry(pred[i]), get_depth_from_pred_entry(pred_pred[i - i_start])); validation_passed = 0; } else if (get_depth_from_pred_entry(pred[i]) == get_depth_from_pred_entry(pred_pred[i - i_start]) + 1) { /* Nothing to do */ } else { write_pred_entry_depth(&pred[i], get_depth_from_pred_entry(pred_pred[i - i_start]) + 1); any_changes = 1; } } } } MPI_Allreduce(MPI_IN_PLACE, &any_changes, 1, MPI_INT, MPI_LOR, MPI_COMM_WORLD); if (!any_changes) break; } } destroy_gather(pred_win); MPI_Free_mem(pred_pred); free(pred_owner); free(pred_local); free(pred_vtx); return validation_passed; } /* Check the BFS levels in pred against the predecessors given there. Returns * true if the maps are valid. */ static int check_bfs_depth_map_using_predecessors(const tuple_graph* const tg, const int64_t nglobalverts, const size_t nlocalverts, const size_t maxlocalverts, const int64_t root, const int64_t* const pred) { (void)nglobalverts; /* Avoid warning */ assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (root >= 0 && root < nglobalverts); assert (nglobalverts >= 0); assert (pred); int validation_passed = 1; int root_owner; size_t root_local; get_vertex_distribution_for_pred(1, &root, &root_owner, &root_local); int root_is_mine = (root_owner == rank); if (root_is_mine) assert (root_local < nlocalverts); { ptrdiff_t i; if (root_is_mine && get_depth_from_pred_entry(pred[root_local]) != 0) { fprintf(stderr, "%d: Validation error: depth of root vertex %" PRId64 " is %" PRIu16 ", not 0.\n", rank, root, get_depth_from_pred_entry(pred[root_local])); validation_passed = 0; } #pragma omp parallel for reduction(&&:validation_passed) for (i = 0; i < (ptrdiff_t)nlocalverts; ++i) { if (get_pred_from_pred_entry(pred[i]) == -1 && get_depth_from_pred_entry(pred[i]) != UINT16_MAX) { fprintf(stderr, "%d: Validation error: depth of vertex %" PRId64 " with no predecessor is %" PRIu16 ", not UINT16_MAX.\n", rank, vertex_to_global_for_pred(rank, i), get_depth_from_pred_entry(pred[i])); validation_passed = 0; } else if (get_pred_from_pred_entry(pred[i]) != -1 && get_depth_from_pred_entry(pred[i]) == UINT16_MAX) { fprintf(stderr, "%d: Validation error: predecessor of claimed unreachable vertex %" PRId64 " is %" PRId64 ", not -1.\n", rank, vertex_to_global_for_pred(rank, i), get_pred_from_pred_entry(pred[i])); validation_passed = 0; } } } int64_t* restrict pred_pred = (int64_t*)xMPI_Alloc_mem(size_min(CHUNKSIZE, nlocalverts) * sizeof(int64_t)); /* Predecessor info of predecessor vertex for each local vertex */ gather* pred_win = init_gather((void*)pred, nlocalverts, sizeof(int64_t), pred_pred, size_min(CHUNKSIZE, nlocalverts), size_min(CHUNKSIZE, nlocalverts), MPI_INT64_T); int64_t* restrict pred_vtx = (int64_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int64_t)); /* Vertex (not depth) part of pred map */ int* restrict pred_owner = (int*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int)); size_t* restrict pred_local = (size_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(size_t)); size_t ii; for (ii = 0; ii < maxlocalverts; ii += CHUNKSIZE) { ptrdiff_t i_start = ptrdiff_min(ii, nlocalverts); ptrdiff_t i_end = ptrdiff_min(ii + CHUNKSIZE, nlocalverts); begin_gather(pred_win); ptrdiff_t i; assert (i_start >= 0 && i_start <= (ptrdiff_t)nlocalverts); assert (i_end >= 0 && i_end <= (ptrdiff_t)nlocalverts); assert (i_end >= i_start); assert (i_end - i_start >= 0 && i_end - i_start <= (ptrdiff_t)size_min(CHUNKSIZE, nlocalverts)); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { pred_vtx[i - i_start] = get_pred_from_pred_entry(pred[i]); } get_vertex_distribution_for_pred(i_end - i_start, pred_vtx, pred_owner, pred_local); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { if (pred[i] != -1) { add_gather_request(pred_win, i - i_start, pred_owner[i - i_start], pred_local[i - i_start], i - i_start); } else { pred_pred[i - i_start] = -1; } } end_gather(pred_win); #pragma omp parallel for reduction(&&:validation_passed) for (i = i_start; i < i_end; ++i) { if (rank == root_owner && (size_t)i == root_local) continue; if (get_pred_from_pred_entry(pred[i]) == -1) continue; /* Already checked */ if (get_depth_from_pred_entry(pred_pred[i - i_start]) == UINT16_MAX) { fprintf(stderr, "%d: Validation error: predecessor %" PRId64 " of vertex %" PRId64 " (depth %" PRIu16 ") is marked as unreachable.\n", rank, get_pred_from_pred_entry(pred[i]), vertex_to_global_for_pred(rank, i), get_depth_from_pred_entry(pred[i])); validation_passed = 0; } if (get_depth_from_pred_entry(pred[i]) != get_depth_from_pred_entry(pred_pred[i - i_start]) + 1) { fprintf(stderr, "%d: Validation error: BFS predecessors do not form a tree; see vertices %" PRId64 " (depth %" PRIu16 ") and %" PRId64 " (depth %" PRIu16 ").\n", rank, vertex_to_global_for_pred(rank, i), get_depth_from_pred_entry(pred[i]), get_pred_from_pred_entry(pred[i]), get_depth_from_pred_entry(pred_pred[i - i_start])); validation_passed = 0; } } } destroy_gather(pred_win); MPI_Free_mem(pred_pred); free(pred_owner); free(pred_local); free(pred_vtx); return validation_passed; } /* Returns true if result is valid. Also, updates high 16 bits of each element * of pred to contain the BFS level number (or -1 if not visited) of each * vertex; this is based on the predecessor map if the user didn't provide it. * */ int validate_bfs_result(const tuple_graph* const tg, const int64_t nglobalverts, const size_t nlocalverts, const int64_t root, int64_t* const pred, int64_t* const edge_visit_count_ptr, int64_t *maxdepth_out) { assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (pred); *edge_visit_count_ptr = 0; /* Ensure it is a valid pointer */ int ranges_ok = check_value_ranges(nglobalverts, nlocalverts, pred); if (root < 0 || root >= nglobalverts) { fprintf(stderr, "%d: Validation error: root vertex %" PRId64 " is invalid.\n", rank, root); ranges_ok = 0; } if (!ranges_ok) return 0; /* Fail */ assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (pred); int validation_passed = 1; int root_owner; size_t root_local; get_vertex_distribution_for_pred(1, &root, &root_owner, &root_local); int root_is_mine = (root_owner == rank); /* Get maximum values so loop counts are consistent across ranks. */ uint64_t maxlocalverts_ui = nlocalverts; MPI_Allreduce(MPI_IN_PLACE, &maxlocalverts_ui, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD); size_t maxlocalverts = (size_t)maxlocalverts_ui; ptrdiff_t max_bufsize = tuple_graph_max_bufsize(tg); ptrdiff_t edge_chunk_size = ptrdiff_min(HALF_CHUNKSIZE, max_bufsize); assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (pred); /* Check that root is its own parent. */ if (root_is_mine) { assert (root_local < nlocalverts); if (get_pred_from_pred_entry(pred[root_local]) != root) { fprintf(stderr, "%d: Validation error: parent of root vertex %" PRId64 " is %" PRId64 ", not the root itself.\n", rank, root, get_pred_from_pred_entry(pred[root_local])); validation_passed = 0; } } assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (pred); /* Check that nothing else is its own parent. */ { int* restrict pred_owner = (int*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int)); size_t* restrict pred_local = (size_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(size_t)); int64_t* restrict pred_vtx = (int64_t*)xmalloc(size_min(CHUNKSIZE, nlocalverts) * sizeof(int64_t)); /* Vertex (not depth) part of pred map */ ptrdiff_t ii; for (ii = 0; ii < (ptrdiff_t)nlocalverts; ii += CHUNKSIZE) { ptrdiff_t i_start = ii; ptrdiff_t i_end = ptrdiff_min(ii + CHUNKSIZE, nlocalverts); ptrdiff_t i; assert (i_start >= 0 && i_start <= (ptrdiff_t)nlocalverts); assert (i_end >= 0 && i_end <= (ptrdiff_t)nlocalverts); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { pred_vtx[i - i_start] = get_pred_from_pred_entry(pred[i]); } get_vertex_distribution_for_pred(i_end - i_start, pred_vtx, pred_owner, pred_local); #pragma omp parallel for reduction(&&:validation_passed) for (i = i_start; i < i_end; ++i) { if ((!root_is_mine || (size_t)i != root_local) && get_pred_from_pred_entry(pred[i]) != -1 && pred_owner[i - i_start] == rank && pred_local[i - i_start] == (size_t)i) { fprintf(stderr, "%d: Validation error: parent of non-root vertex %" PRId64 " is itself.\n", rank, vertex_to_global_for_pred(rank, i)); validation_passed = 0; } } } free(pred_owner); free(pred_local); free(pred_vtx); } assert (tg->edgememory_size >= 0 && tg->max_edgememory_size >= tg->edgememory_size && tg->max_edgememory_size <= tg->nglobaledges); assert (pred); if (bfs_writes_depth_map()) { int check_ok = check_bfs_depth_map_using_predecessors(tg, nglobalverts, nlocalverts, maxlocalverts, root, pred); if (!check_ok) validation_passed = 0; } else { /* Create a vertex depth map to use for later validation. */ int pred_ok = build_bfs_depth_map(nglobalverts, nlocalverts, maxlocalverts, root, pred); if (!pred_ok) validation_passed = 0; } { /* Check that all edges connect vertices whose depths differ by at most * one, and check that there is an edge from each vertex to its claimed * predecessor. Also, count visited edges (including duplicates and * self-loops). */ unsigned char* restrict pred_valid = (unsigned char*)xMPI_Alloc_mem(nlocalverts * sizeof(unsigned char)); memset(pred_valid, 0, nlocalverts * sizeof(unsigned char)); int64_t* restrict edge_endpoint = (int64_t*)xmalloc(2 * edge_chunk_size * sizeof(int64_t)); int* restrict edge_owner = (int*)xmalloc(2 * edge_chunk_size * sizeof(int)); size_t* restrict edge_local = (size_t*)xmalloc(2 * edge_chunk_size * sizeof(size_t)); int64_t* restrict edge_preds = (int64_t*)xMPI_Alloc_mem(2 * edge_chunk_size * sizeof(int64_t)); gather* pred_win = init_gather((void*)pred, nlocalverts, sizeof(int64_t), edge_preds, 2 * edge_chunk_size, 2 * edge_chunk_size, MPI_INT64_T); unsigned char one = 1; scatter_constant* pred_valid_win = init_scatter_constant((void*)pred_valid, nlocalverts, sizeof(unsigned char), &one, 2 * edge_chunk_size, MPI_UNSIGNED_CHAR); int64_t edge_visit_count = 0; ITERATE_TUPLE_GRAPH_BEGIN(tg, buf, bufsize) { ptrdiff_t ii; for (ii = 0; ii < max_bufsize; ii += HALF_CHUNKSIZE) { ptrdiff_t i_start = ptrdiff_min(ii, bufsize); ptrdiff_t i_end = ptrdiff_min(ii + HALF_CHUNKSIZE, bufsize); assert (i_end - i_start <= edge_chunk_size); ptrdiff_t i; #pragma omp parallel for for (i = i_start; i < i_end; ++i) { int64_t v0 = get_v0_from_edge(&buf[i]); int64_t v1 = get_v1_from_edge(&buf[i]); edge_endpoint[(i - i_start) * 2 + 0] = v0; edge_endpoint[(i - i_start) * 2 + 1] = v1; } get_vertex_distribution_for_pred(2 * (i_end - i_start), edge_endpoint, edge_owner, edge_local); begin_gather(pred_win); #pragma omp parallel for for (i = i_start; i < i_end; ++i) { add_gather_request(pred_win, (i - i_start) * 2 + 0, edge_owner[(i - i_start) * 2 + 0], edge_local[(i - i_start) * 2 + 0], (i - i_start) * 2 + 0); add_gather_request(pred_win, (i - i_start) * 2 + 1, edge_owner[(i - i_start) * 2 + 1], edge_local[(i - i_start) * 2 + 1], (i - i_start) * 2 + 1); } end_gather(pred_win); begin_scatter_constant(pred_valid_win); #pragma omp parallel for reduction(&&:validation_passed) reduction(+:edge_visit_count) for (i = i_start; i < i_end; ++i) { int64_t src = get_v0_from_edge(&buf[i]); int64_t tgt = get_v1_from_edge(&buf[i]); uint16_t src_depth = get_depth_from_pred_entry(edge_preds[(i - i_start) * 2 + 0]); uint16_t tgt_depth = get_depth_from_pred_entry(edge_preds[(i - i_start) * 2 + 1]); if (src_depth != UINT16_MAX && tgt_depth == UINT16_MAX) { fprintf(stderr, "%d: Validation error: edge connects vertex %" PRId64 " in the BFS tree (depth %" PRIu16 ") to vertex %" PRId64 " outside the tree.\n", rank, src, src_depth, tgt); validation_passed = 0; } else if (src_depth == UINT16_MAX && tgt_depth != UINT16_MAX) { fprintf(stderr, "%d: Validation error: edge connects vertex %" PRId64 " in the BFS tree (depth %" PRIu16 ") to vertex %" PRId64 " outside the tree.\n", rank, tgt, tgt_depth, src); validation_passed = 0; } else if (src_depth - tgt_depth < -1 || src_depth - tgt_depth > 1) { fprintf(stderr, "%d: Validation error: depths of edge endpoints %" PRId64 " (depth %" PRIu16 ") and %" PRId64 " (depth %" PRIu16 ") are too far apart (abs. val. > 1).\n", rank, src, src_depth, tgt, tgt_depth); validation_passed = 0; } else if (src_depth != UINT16_MAX) { ++edge_visit_count; } if (get_pred_from_pred_entry(edge_preds[(i - i_start) * 2 + 0]) == tgt) { add_scatter_constant_request(pred_valid_win, edge_owner[(i - i_start) * 2 + 0], edge_local[(i - i_start) * 2 + 0], (i - i_start) * 2 + 0); } if (get_pred_from_pred_entry(edge_preds[(i - i_start) * 2 + 1]) == src) { add_scatter_constant_request(pred_valid_win, edge_owner[(i - i_start) * 2 + 1], edge_local[(i - i_start) * 2 + 1], (i - i_start) * 2 + 1); } } end_scatter_constant(pred_valid_win); } } ITERATE_TUPLE_GRAPH_END; destroy_gather(pred_win); MPI_Free_mem(edge_preds); free(edge_owner); free(edge_local); free(edge_endpoint); destroy_scatter_constant(pred_valid_win); ptrdiff_t i; *maxdepth_out = -1; #pragma omp parallel { int64_t tmaxdepth = -1; #pragma omp for reduction(&&:validation_passed) for (i = 0; i < (ptrdiff_t)nlocalverts; ++i) { int64_t p = get_pred_from_pred_entry(pred[i]); if (p == -1) continue; int64_t d = get_depth_from_pred_entry(pred[i]); if (d > tmaxdepth) tmaxdepth = d; int found_pred_edge = pred_valid[i]; if (root_owner == rank && root_local == (size_t)i) found_pred_edge = 1; /* Root vertex */ if (!found_pred_edge) { int64_t v = vertex_to_global_for_pred(rank, i); fprintf(stderr, "%d: Validation error: no graph edge from vertex %" PRId64 " to its parent %" PRId64 ".\n", rank, v, get_pred_from_pred_entry(pred[i])); validation_passed = 0; } } #pragma omp critical if (tmaxdepth > *maxdepth_out) *maxdepth_out = tmaxdepth; } MPI_Free_mem(pred_valid); MPI_Allreduce(MPI_IN_PLACE, &edge_visit_count, 1, MPI_INT64_T, MPI_SUM, MPI_COMM_WORLD); *edge_visit_count_ptr = edge_visit_count; } MPI_Allreduce(MPI_IN_PLACE, maxdepth_out, 1, MPI_INT64_T, MPI_MAX, MPI_COMM_WORLD); /* Collect the global validation result. */ MPI_Allreduce(MPI_IN_PLACE, &validation_passed, 1, MPI_INT, MPI_LAND, MPI_COMM_WORLD); return validation_passed; }
OpenMPClause.h
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file defines OpenMP AST classes for clauses. /// There are clauses for executable directives, clauses for declarative /// directives and clauses which can be used in both kinds of directives. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H #define LLVM_CLANG_AST_OPENMPCLAUSE_H #include "clang/AST/Expr.h" #include "clang/AST/Stmt.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" namespace clang { //===----------------------------------------------------------------------===// // AST classes for clauses. //===----------------------------------------------------------------------===// /// \brief This is a basic class for representing single OpenMP clause. /// class OMPClause { /// \brief Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// \brief Ending location of the clause. SourceLocation EndLoc; /// \brief Kind of the clause. OpenMPClauseKind Kind; protected: OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc) : StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {} public: /// \brief Returns the starting location of the clause. SourceLocation getLocStart() const { return StartLoc; } /// \brief Returns the ending location of the clause. SourceLocation getLocEnd() const { return EndLoc; } /// \brief Sets the starting location of the clause. void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// \brief Sets the ending location of the clause. void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// \brief Returns kind of OpenMP clause (private, shared, reduction, etc.). OpenMPClauseKind getClauseKind() const { return Kind; } bool isImplicit() const { return StartLoc.isInvalid(); } StmtRange children(); ConstStmtRange children() const { return const_cast<OMPClause *>(this)->children(); } static bool classof(const OMPClause *T) { return true; } }; /// \brief This represents clauses with the list of variables like 'private', /// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the /// '#pragma omp ...' directives. template <class T> class OMPVarListClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Number of variables in the list. unsigned NumVars; protected: /// \brief Fetches list of variables associated with this clause. MutableArrayRef<Expr *> getVarRefs() { return MutableArrayRef<Expr *>( reinterpret_cast<Expr **>( reinterpret_cast<char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())), NumVars); } /// \brief Sets the list of variables for this clause. void setVarRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::copy( VL.begin(), VL.end(), reinterpret_cast<Expr **>( reinterpret_cast<char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>()))); } /// \brief Build a clause with \a N variables /// /// \param K Kind of the clause. /// \param StartLoc Starting location of the clause (the clause keyword). /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {} public: typedef MutableArrayRef<Expr *>::iterator varlist_iterator; typedef ArrayRef<const Expr *>::iterator varlist_const_iterator; typedef llvm::iterator_range<varlist_iterator> varlist_range; typedef llvm::iterator_range<varlist_const_iterator> varlist_const_range; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_range varlists() { return varlist_range(varlist_begin(), varlist_end()); } varlist_const_range varlists() const { return varlist_const_range(varlist_begin(), varlist_end()); } varlist_iterator varlist_begin() { return getVarRefs().begin(); } varlist_iterator varlist_end() { return getVarRefs().end(); } varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); } varlist_const_iterator varlist_end() const { return getVarRefs().end(); } /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Fetches list of all variables in the clause. ArrayRef<const Expr *> getVarRefs() const { return ArrayRef<const Expr *>( reinterpret_cast<const Expr *const *>( reinterpret_cast<const char *>(this) + llvm::RoundUpToAlignment(sizeof(T), llvm::alignOf<Expr *>())), NumVars); } }; /// \brief This represents 'if' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel if(a > 5) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'if' /// clause with condition 'a > 5'. /// class OMPIfClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'if' clause. Stmt *Condition; /// \brief Set condition. /// void setCondition(Expr *Cond) { Condition = Cond; } public: /// \brief Build 'if' clause with condition \a Cond. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Cond Condition of the clause. /// \param EndLoc Ending location of the clause. /// OMPIfClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_if, StartLoc, EndLoc), LParenLoc(LParenLoc), Condition(Cond) {} /// \brief Build an empty clause. /// OMPIfClause() : OMPClause(OMPC_if, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Condition(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_if; } StmtRange children() { return StmtRange(&Condition, &Condition + 1); } }; /// \brief This represents 'final' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task final(a > 5) /// \endcode /// In this example directive '#pragma omp task' has simple 'final' /// clause with condition 'a > 5'. /// class OMPFinalClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'if' clause. Stmt *Condition; /// \brief Set condition. /// void setCondition(Expr *Cond) { Condition = Cond; } public: /// \brief Build 'final' clause with condition \a Cond. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Cond Condition of the clause. /// \param EndLoc Ending location of the clause. /// OMPFinalClause(Expr *Cond, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_final, StartLoc, EndLoc), LParenLoc(LParenLoc), Condition(Cond) {} /// \brief Build an empty clause. /// OMPFinalClause() : OMPClause(OMPC_final, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Condition(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_final; } StmtRange children() { return StmtRange(&Condition, &Condition + 1); } }; /// \brief This represents 'num_threads' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel num_threads(6) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'num_threads' /// clause with number of threads '6'. /// class OMPNumThreadsClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Condition of the 'num_threads' clause. Stmt *NumThreads; /// \brief Set condition. /// void setNumThreads(Expr *NThreads) { NumThreads = NThreads; } public: /// \brief Build 'num_threads' clause with condition \a NumThreads. /// /// \param NumThreads Number of threads for the construct. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_num_threads, StartLoc, EndLoc), LParenLoc(LParenLoc), NumThreads(NumThreads) {} /// \brief Build an empty clause. /// OMPNumThreadsClause() : OMPClause(OMPC_num_threads, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), NumThreads(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns number of threads. Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_num_threads; } StmtRange children() { return StmtRange(&NumThreads, &NumThreads + 1); } }; /// \brief This represents 'safelen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd safelen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'safelen' /// with single expression '4'. /// If the safelen clause is used then no two iterations executed /// concurrently with SIMD instructions can have a greater distance /// in the logical iteration space than its value. The parameter of /// the safelen clause must be a constant positive integer expression. /// class OMPSafelenClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Safe iteration space distance. Stmt *Safelen; /// \brief Set safelen. void setSafelen(Expr *Len) { Safelen = Len; } public: /// \brief Build 'safelen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// \brief Build an empty clause. /// explicit OMPSafelenClause() : OMPClause(OMPC_safelen, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Safelen(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Return safe iteration space distance. Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_safelen; } StmtRange children() { return StmtRange(&Safelen, &Safelen + 1); } }; /// \brief This represents 'collapse' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd collapse(3) /// \endcode /// In this example directive '#pragma omp simd' has clause 'collapse' /// with single expression '3'. /// The parameter must be a constant positive integer expression, it specifies /// the number of nested loops that should be collapsed into a single iteration /// space. /// class OMPCollapseClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief Number of for-loops. Stmt *NumForLoops; /// \brief Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// \brief Build 'collapse' clause. /// /// \param Num Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPCollapseClause(Expr *Num, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// \brief Build an empty clause. /// explicit OMPCollapseClause() : OMPClause(OMPC_collapse, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), NumForLoops(nullptr) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_collapse; } StmtRange children() { return StmtRange(&NumForLoops, &NumForLoops + 1); } }; /// \brief This represents 'default' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel default(shared) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'default' /// clause with kind 'shared'. /// class OMPDefaultClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'default' clause. OpenMPDefaultClauseKind Kind; /// \brief Start location of the kind in source code. SourceLocation KindKwLoc; /// \brief Set kind of the clauses. /// /// \param K Argument of clause. /// void setDefaultKind(OpenMPDefaultClauseKind K) { Kind = K; } /// \brief Set argument location. /// /// \param KLoc Argument location. /// void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// \brief Build 'default' clause with argument \a A ('none' or 'shared'). /// /// \param A Argument of the clause ('none' or 'shared'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPDefaultClause(OpenMPDefaultClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// \brief Build an empty clause. /// OMPDefaultClause() : OMPClause(OMPC_default, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Kind(OMPC_DEFAULT_unknown), KindKwLoc(SourceLocation()) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns kind of the clause. OpenMPDefaultClauseKind getDefaultKind() const { return Kind; } /// \brief Returns location of clause kind. SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_default; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'proc_bind' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel proc_bind(master) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'proc_bind' /// clause with kind 'master'. /// class OMPProcBindClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'proc_bind' clause. OpenMPProcBindClauseKind Kind; /// \brief Start location of the kind in source code. SourceLocation KindKwLoc; /// \brief Set kind of the clause. /// /// \param K Kind of clause. /// void setProcBindKind(OpenMPProcBindClauseKind K) { Kind = K; } /// \brief Set clause kind location. /// /// \param KLoc Kind location. /// void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// \brief Build 'proc_bind' clause with argument \a A ('master', 'close' or /// 'spread'). /// /// \param A Argument of the clause ('master', 'close' or 'spread'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// OMPProcBindClause(OpenMPProcBindClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// \brief Build an empty clause. /// OMPProcBindClause() : OMPClause(OMPC_proc_bind, SourceLocation(), SourceLocation()), LParenLoc(SourceLocation()), Kind(OMPC_PROC_BIND_unknown), KindKwLoc(SourceLocation()) {} /// \brief Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// \brief Returns kind of the clause. OpenMPProcBindClauseKind getProcBindKind() const { return Kind; } /// \brief Returns location of clause kind. SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_proc_bind; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'schedule' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for schedule(static, 3) /// \endcode /// In this example directive '#pragma omp for' has 'schedule' clause with /// arguments 'static' and '3'. /// class OMPScheduleClause : public OMPClause { friend class OMPClauseReader; /// \brief Location of '('. SourceLocation LParenLoc; /// \brief A kind of the 'schedule' clause. OpenMPScheduleClauseKind Kind; /// \brief Start location of the schedule ind in source code. SourceLocation KindLoc; /// \brief Location of ',' (if any). SourceLocation CommaLoc; /// \brief Chunk size. Stmt *ChunkSize; /// \brief Set schedule kind. /// /// \param K Schedule kind. /// void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; } /// \brief Sets the location of '('. /// /// \param Loc Location of '('. /// void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// \brief Set schedule kind start location. /// /// \param KLoc Schedule kind location. /// void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// \brief Set location of ','. /// /// \param Loc Location of ','. /// void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// \brief Set chunk size. /// /// \param E Chunk size. /// void setChunkSize(Expr *E) { ChunkSize = E; } public: /// \brief Build 'schedule' clause with schedule kind \a Kind and chunk size /// expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind Schedule kind. /// \param ChunkSize Chunk size. /// OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPScheduleClauseKind Kind, Expr *ChunkSize) : OMPClause(OMPC_schedule, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) {} /// \brief Build an empty clause. /// explicit OMPScheduleClause() : OMPClause(OMPC_schedule, SourceLocation(), SourceLocation()), Kind(OMPC_SCHEDULE_unknown), ChunkSize(nullptr) {} /// \brief Get kind of the clause. /// OpenMPScheduleClauseKind getScheduleKind() const { return Kind; } /// \brief Get location of '('. /// SourceLocation getLParenLoc() { return LParenLoc; } /// \brief Get kind location. /// SourceLocation getScheduleKindLoc() { return KindLoc; } /// \brief Get location of ','. /// SourceLocation getCommaLoc() { return CommaLoc; } /// \brief Get chunk size. /// Expr *getChunkSize() { return dyn_cast_or_null<Expr>(ChunkSize); } /// \brief Get chunk size. /// Expr *getChunkSize() const { return dyn_cast_or_null<Expr>(ChunkSize); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_schedule; } StmtRange children() { return StmtRange(&ChunkSize, &ChunkSize + 1); } }; /// \brief This represents 'ordered' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for ordered /// \endcode /// In this example directive '#pragma omp for' has 'ordered' clause. /// class OMPOrderedClause : public OMPClause { public: /// \brief Build 'ordered' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_ordered, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPOrderedClause() : OMPClause(OMPC_ordered, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_ordered; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'nowait' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for nowait /// \endcode /// In this example directive '#pragma omp for' has 'nowait' clause. /// class OMPNowaitClause : public OMPClause { public: /// \brief Build 'nowait' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_nowait, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPNowaitClause() : OMPClause(OMPC_nowait, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_nowait; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'untied' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task untied /// \endcode /// In this example directive '#pragma omp task' has 'untied' clause. /// class OMPUntiedClause : public OMPClause { public: /// \brief Build 'untied' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_untied, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPUntiedClause() : OMPClause(OMPC_untied, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_untied; } StmtRange children() { return StmtRange(); } }; /// \brief This represents 'mergeable' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task mergeable /// \endcode /// In this example directive '#pragma omp task' has 'mergeable' clause. /// class OMPMergeableClause : public OMPClause { public: /// \brief Build 'mergeable' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. /// OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(OMPC_mergeable, StartLoc, EndLoc) {} /// \brief Build an empty clause. /// OMPMergeableClause() : OMPClause(OMPC_mergeable, SourceLocation(), SourceLocation()) {} static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_mergeable; } StmtRange children() { return StmtRange(); } }; /// \brief This represents clause 'private' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// with the variables 'a' and 'b'. /// class OMPPrivateClause : public OMPVarListClause<OMPPrivateClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPPrivateClause>(OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(OMPC_private, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_private; } }; /// \brief This represents clause 'firstprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel firstprivate(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'firstprivate' /// with the variables 'a' and 'b'. /// class OMPFirstprivateClause : public OMPVarListClause<OMPFirstprivateClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFirstprivateClause>(OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( OMPC_firstprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPFirstprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_firstprivate; } }; /// \brief This represents clause 'lastprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd lastprivate(a,b) /// \endcode /// In this example directive '#pragma omp simd' has clause 'lastprivate' /// with the variables 'a' and 'b'. /// class OMPLastprivateClause : public OMPVarListClause<OMPLastprivateClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPLastprivateClause>(OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( OMPC_lastprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPLastprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_lastprivate; } }; /// \brief This represents clause 'shared' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel shared(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'shared' /// with the variables 'a' and 'b'. /// class OMPSharedClause : public OMPVarListClause<OMPSharedClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPSharedClause>(OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(OMPC_shared, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_shared; } }; /// \brief This represents clause 'reduction' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'reduction' /// with operator '+' and the variables 'a' and 'b'. /// class OMPReductionClause : public OMPVarListClause<OMPReductionClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// \brief Name of custom operator. DeclarationNameInfo NameInfo; /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(OMPC_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), ColonLoc(), QualifierLoc(), NameInfo() {} /// \brief Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// \brief Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// \brief Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } public: /// \brief Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// static OMPReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo); /// \brief Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// \brief Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// \brief Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_reduction; } }; /// \brief This represents clause 'linear' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd linear(a,b : 2) /// \endcode /// In this example directive '#pragma omp simd' has clause 'linear' /// with variables 'a', 'b' and linear step '2'. /// class OMPLinearClause : public OMPVarListClause<OMPLinearClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Sets the linear step for clause. void setStep(Expr *Step) { *varlist_end() = Step; } /// \brief Build 'linear' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. /// OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPLinearClause>(OMPC_linear, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// \brief Build an empty clause. /// /// \param NumVars Number of variables. /// explicit OMPLinearClause(unsigned NumVars) : OMPVarListClause<OMPLinearClause>(OMPC_linear, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), ColonLoc(SourceLocation()) {} public: /// \brief Creates clause with a list of variables \a VL and a linear step /// \a Step. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param Step Linear step. static OMPLinearClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *Step); /// \brief Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. /// static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// \brief Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// \brief Returns the location of '('. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Returns linear step. Expr *getStep() { return *varlist_end(); } /// \brief Returns linear step. const Expr *getStep() const { return *varlist_end(); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end() + 1)); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_linear; } }; /// \brief This represents clause 'aligned' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd aligned(a,b : 8) /// \endcode /// In this example directive '#pragma omp simd' has clause 'aligned' /// with variables 'a', 'b' and alignment '8'. /// class OMPAlignedClause : public OMPVarListClause<OMPAlignedClause> { friend class OMPClauseReader; /// \brief Location of ':'. SourceLocation ColonLoc; /// \brief Sets the alignment for clause. void setAlignment(Expr *A) { *varlist_end() = A; } /// \brief Build 'aligned' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. /// OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// \brief Build an empty clause. /// /// \param NumVars Number of variables. /// explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(OMPC_aligned, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), ColonLoc(SourceLocation()) {} public: /// \brief Creates clause with a list of variables \a VL and alignment \a A. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param A Alignment. static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *A); /// \brief Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. /// static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// \brief Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// \brief Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// \brief Returns alignment. Expr *getAlignment() { return *varlist_end(); } /// \brief Returns alignment. const Expr *getAlignment() const { return *varlist_end(); } StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end() + 1)); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_aligned; } }; /// \brief This represents clause 'copyin' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel copyin(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'copyin' /// with the variables 'a' and 'b'. /// class OMPCopyinClause : public OMPVarListClause<OMPCopyinClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyinClause>(OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(OMPC_copyin, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPCopyinClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_copyin; } }; /// \brief This represents clause 'copyprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp single copyprivate(a,b) /// \endcode /// In this example directive '#pragma omp single' has clause 'copyprivate' /// with the variables 'a' and 'b'. /// class OMPCopyprivateClause : public OMPVarListClause<OMPCopyprivateClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyprivateClause>(OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( OMPC_copyprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPCopyprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_copyprivate; } }; /// \brief This represents pseudo clause 'flush' for the '#pragma omp flush' /// directive. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has pseudo clause 'flush' /// with the variables 'a' and 'b'. /// class OMPFlushClause : public OMPVarListClause<OMPFlushClause> { /// \brief Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFlushClause>(OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// \brief Build an empty clause. /// /// \param N Number of variables. /// explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(OMPC_flush, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// \brief Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// \brief Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N); StmtRange children() { return StmtRange(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } static bool classof(const OMPClause *T) { return T->getClauseKind() == OMPC_flush; } }; } // end namespace clang #endif
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 4; 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<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
polybench.c
/** * This version is stamped on Apr. 14, 2015 * * Contact: * Louis-Noel Pouchet <pouchet.ohio-state.edu> * Tomofumi Yuki <tomofumi.yuki.fr> * * Web address: http://polybench.sourceforge.net */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <assert.h> #include <time.h> #include <sys/time.h> #include <sys/resource.h> #include <sched.h> #include <math.h> #ifdef _OPENMP # include <omp.h> #endif /* By default, collect PAPI counters on thread 0. */ #ifndef POLYBENCH_THREAD_MONITOR # define POLYBENCH_THREAD_MONITOR 0 #endif /* Total LLC cache size. By default 32+MB.. */ #ifndef POLYBENCH_CACHE_SIZE_KB # define POLYBENCH_CACHE_SIZE_KB 32770 #endif int polybench_papi_counters_threadid = POLYBENCH_THREAD_MONITOR; double polybench_program_total_flops = 0; #ifdef POLYBENCH_PAPI # include <papi.h> # define POLYBENCH_MAX_NB_PAPI_COUNTERS 96 char* _polybench_papi_eventlist[] = { #include "papi_counters.list" NULL }; int polybench_papi_eventset; int polybench_papi_eventlist[POLYBENCH_MAX_NB_PAPI_COUNTERS]; long_long polybench_papi_values[POLYBENCH_MAX_NB_PAPI_COUNTERS]; #endif /* Timer code (gettimeofday). */ double polybench_t_start, polybench_t_end; /* Timer code (RDTSC). */ unsigned long long int polybench_c_start, polybench_c_end; static double rtclock() { #if defined(POLYBENCH_TIME) || defined(POLYBENCH_GFLOPS) struct timeval Tp; int stat; stat = gettimeofday (&Tp, NULL); if (stat != 0) printf ("Error return from gettimeofday: %d", stat); return (Tp.tv_sec + Tp.tv_usec * 1.0e-6); #else return 0; #endif } #ifdef POLYBENCH_CYCLE_ACCURATE_TIMER static unsigned long long int rdtsc() { unsigned long long int ret = 0; unsigned int cycles_lo; unsigned int cycles_hi; __asm__ volatile ("RDTSC" : "=a" (cycles_lo), "=d" (cycles_hi)); ret = (unsigned long long int)cycles_hi << 32 | cycles_lo; return ret; } #endif void polybench_flush_cache() { int cs = POLYBENCH_CACHE_SIZE_KB * 1024 / sizeof(double); double* flush = (double*) calloc (cs, sizeof(double)); int i; double tmp = 0.0; #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < cs; i++) tmp += flush[i]; assert (tmp <= 10.0); free (flush); } #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER void polybench_linux_fifo_scheduler() { /* Use FIFO scheduler to limit OS interference. Program must be run as root, and this works only for Linux kernels. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max (SCHED_FIFO); sched_setscheduler (0, SCHED_FIFO, &schedParam); } void polybench_linux_standard_scheduler() { /* Restore to standard scheduler policy. */ struct sched_param schedParam; schedParam.sched_priority = sched_get_priority_max (SCHED_OTHER); sched_setscheduler (0, SCHED_OTHER, &schedParam); } #endif #ifdef POLYBENCH_PAPI static void test_fail(char *file, int line, char *call, int retval) { char buf[128]; memset(buf, '\0', sizeof(buf)); if (retval != 0) fprintf (stdout,"%-40s FAILED\nLine # %d\n", file, line); else { fprintf (stdout,"%-40s SKIPPED\n", file); fprintf (stdout,"Line # %d\n", line); } if (retval == PAPI_ESYS) { sprintf (buf, "System error in %s", call); perror (buf); } else if (retval > 0) fprintf (stdout,"Error: %s\n", call); else if (retval == 0) fprintf (stdout,"Error: %s\n", call); else { char errstring[PAPI_MAX_STR_LEN]; PAPI_perror (retval, errstring, PAPI_MAX_STR_LEN); fprintf (stdout,"Error in %s: %s\n", call, errstring); } fprintf (stdout,"\n"); if (PAPI_is_initialized ()) PAPI_shutdown (); exit (1); } void polybench_papi_init() { # ifdef _OPENMP #pragma omp parallel { #pragma omp master { if (omp_get_max_threads () < polybench_papi_counters_threadid) polybench_papi_counters_threadid = omp_get_max_threads () - 1; } #pragma omp barrier if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; polybench_papi_eventset = PAPI_NULL; if ((retval = PAPI_library_init (PAPI_VER_CURRENT)) != PAPI_VER_CURRENT) test_fail (__FILE__, __LINE__, "PAPI_library_init", retval); if ((retval = PAPI_create_eventset (&polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_create_eventset", retval); int k; for (k = 0; _polybench_papi_eventlist[k]; ++k) { if ((retval = PAPI_event_name_to_code (_polybench_papi_eventlist[k], &(polybench_papi_eventlist[k]))) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_event_name_to_code", retval); } polybench_papi_eventlist[k] = 0; # ifdef _OPENMP } } #pragma omp barrier # endif } void polybench_papi_close() { # ifdef _OPENMP #pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; if ((retval = PAPI_destroy_eventset (&polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_destroy_eventset", retval); if (PAPI_is_initialized ()) PAPI_shutdown (); # ifdef _OPENMP } } #pragma omp barrier # endif } int polybench_papi_start_counter(int evid) { # ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache(); # endif # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval = 1; char descr[PAPI_MAX_STR_LEN]; PAPI_event_info_t evinfo; PAPI_event_code_to_name (polybench_papi_eventlist[evid], descr); if (PAPI_add_event (polybench_papi_eventset, polybench_papi_eventlist[evid]) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_add_event", 1); if (PAPI_get_event_info (polybench_papi_eventlist[evid], &evinfo) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_get_event_info", retval); if ((retval = PAPI_start (polybench_papi_eventset)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_start", retval); # ifdef _OPENMP } } #pragma omp barrier # endif return 0; } void polybench_papi_stop_counter(int evid) { # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num () == polybench_papi_counters_threadid) { # endif int retval; long_long values[1]; values[0] = 0; if ((retval = PAPI_read (polybench_papi_eventset, &values[0])) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_read", retval); if ((retval = PAPI_stop (polybench_papi_eventset, NULL)) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_stop", retval); polybench_papi_values[evid] = values[0]; if ((retval = PAPI_remove_event (polybench_papi_eventset, polybench_papi_eventlist[evid])) != PAPI_OK) test_fail (__FILE__, __LINE__, "PAPI_remove_event", retval); # ifdef _OPENMP } } #pragma omp barrier # endif } void polybench_papi_print() { int verbose = 0; # ifdef _OPENMP # pragma omp parallel { if (omp_get_thread_num() == polybench_papi_counters_threadid) { #ifdef POLYBENCH_PAPI_VERBOSE verbose = 1; #endif if (verbose) printf ("On thread %d:\n", polybench_papi_counters_threadid); #endif int evid; for (evid = 0; polybench_papi_eventlist[evid] != 0; ++evid) { if (verbose) printf ("%s=", _polybench_papi_eventlist[evid]); printf ("%llu ", polybench_papi_values[evid]); if (verbose) printf ("\n"); } printf ("\n"); # ifdef _OPENMP } } #pragma omp barrier # endif } #endif /* ! POLYBENCH_PAPI */ void polybench_prepare_instruments() { #ifndef POLYBENCH_NO_FLUSH_CACHE polybench_flush_cache (); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_fifo_scheduler (); #endif } void polybench_timer_start() { polybench_prepare_instruments (); #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_start = rtclock (); #else polybench_c_start = rdtsc (); #endif } void polybench_timer_stop() { #ifndef POLYBENCH_CYCLE_ACCURATE_TIMER polybench_t_end = rtclock (); #else polybench_c_end = rdtsc (); #endif #ifdef POLYBENCH_LINUX_FIFO_SCHEDULER polybench_linux_standard_scheduler (); #endif } void polybench_timer_print() { #ifdef POLYBENCH_GFLOPS if (polybench_program_total_flops == 0) { printf ("[PolyBench][WARNING] Program flops not defined, use polybench_set_program_flops(value)\n"); printf ("%0.6lf\n", polybench_t_end - polybench_t_start); } else printf ("%0.2lf\n", (polybench_program_total_flops / (double)(polybench_t_end - polybench_t_start)) / 1000000000); #else # ifndef POLYBENCH_CYCLE_ACCURATE_TIMER printf ("%0.6f\n", polybench_t_end - polybench_t_start); # else printf ("%Ld\n", polybench_c_end - polybench_c_start); # endif #endif } static void * xmalloc (size_t num) { void* cur = NULL; int ret = posix_memalign (&cur, 32, num); if (! cur || ret) { fprintf (stderr, "[PolyBench] posix_memalign: cannot allocate memory"); exit (1); } return cur; } void* polybench_alloc_data(unsigned long long int n, int elt_size) { /// FIXME: detect overflow! size_t val = n; val *= elt_size; void* ret = xmalloc (val); return ret; }
attention.c
#include "darknet.h" #include <sys/time.h> #include <assert.h> void extend_data_truth(data* d, int n, float val) { int i, j; for (i = 0; i < d->y.rows; ++i) { d->y.vals[i] = realloc(d->y.vals[i], (d->y.cols + n) * sizeof(float)); for (j = 0; j < n; ++j) { d->y.vals[i][d->y.cols + j] = val; } } d->y.cols += n; } matrix network_loss_data(network* net, data test) { int i, b; int k = 1; matrix pred = make_matrix(test.X.rows, k); float* X = calloc(net->batch * test.X.cols, sizeof(float)); float* y = calloc(net->batch * test.y.cols, sizeof(float)); for (i = 0; i < test.X.rows; i += net->batch) { for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; memcpy(X + b * test.X.cols, test.X.vals[i + b], test.X.cols * sizeof(float)); memcpy(y + b * test.y.cols, test.y.vals[i + b], test.y.cols * sizeof(float)); } network orig = *net; net->input = X; net->truth = y; net->train = 0; net->delta = 0; forward_network(net); *net = orig; float* delta = net->layers[net->n - 1].output; for (b = 0; b < net->batch; ++b) { if (i + b == test.X.rows) break; int t = max_index(y + b * test.y.cols, 1000); float err = sum_array(delta + b * net->outputs, net->outputs); pred.vals[i + b][0] = -err; // pred.vals[i+b][0] = 1-delta[b*net->outputs + t]; } } free(X); free(y); return pred; } void train_attention(char* datacfg, char* cfgfile, char* weightfile, int* gpus, int ngpus, int clear) { int i, j; float avg_cls_loss = -1; float avg_att_loss = -1; char* base = basecfg(cfgfile); printf("%s\n", base); printf("%d\n", ngpus); network** nets = calloc(ngpus, sizeof(network*)); srand(time(0)); int seed = rand(); for (i = 0; i < ngpus; ++i) { srand(seed); #ifdef GPU cuda_set_device(gpus[i]); #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network* net = nets[0]; int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); list* options = read_data_cfg(datacfg); char* backup_directory = option_find_str(options, "backup", "/backup/"); char* label_list = option_find_str(options, "labels", "data/labels.list"); char* train_list = option_find_str(options, "train", "data/train.list"); int classes = option_find_int(options, "classes", 2); char** labels = get_labels(label_list); list* plist = get_paths(train_list); char** paths = (char**)list_to_array(plist); printf("%d\n", plist->size); int N = plist->size; double time; int divs = 3; int size = 2; load_args args = { 0 }; args.w = divs * net->w / size; args.h = divs * net->h / size; args.size = divs * net->w / size; args.threads = 32; args.hierarchy = net->hierarchy; args.min = net->min_ratio * args.w; args.max = net->max_ratio * args.w; args.angle = net->angle; args.aspect = net->aspect; args.exposure = net->exposure; args.saturation = net->saturation; args.hue = net->hue; args.paths = paths; args.classes = classes; args.n = imgs; args.m = N; args.labels = labels; args.type = CLASSIFICATION_DATA; data train; data buffer; pthread_t load_thread; args.d = &buffer; load_thread = load_data(args); int epoch = (*net->seen) / N; while (get_current_batch(net) < net->max_batches || net->max_batches == 0) { time = what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); data resized = resize_data(train, net->w, net->h); extend_data_truth(&resized, divs * divs, 0); data* tiles = tile_data(train, divs, size); printf("Loaded: %lf seconds\n", what_time_is_it_now() - time); time = what_time_is_it_now(); float aloss = 0; float closs = 0; int z; for (i = 0; i < divs * divs / ngpus; ++i) { #pragma omp parallel for for (j = 0; j < ngpus; ++j) { int index = i * ngpus + j; extend_data_truth(tiles + index, divs * divs, SECRET_NUM); matrix deltas = network_loss_data(nets[j], tiles[index]); for (z = 0; z < resized.y.rows; ++z) { resized.y.vals[z][train.y.cols + index] = deltas.vals[z][0]; } free_matrix(deltas); } } int* inds = calloc(resized.y.rows, sizeof(int)); for (z = 0; z < resized.y.rows; ++z) { int index = max_index(resized.y.vals[z] + train.y.cols, divs * divs); inds[z] = index; for (i = 0; i < divs * divs; ++i) { resized.y.vals[z][train.y.cols + i] = (i == index) ? 1 : 0; } } data best = select_data(tiles, inds); free(inds); #ifdef GPU if (ngpus == 1) { closs = train_network(net, best); } else { closs = train_networks(nets, ngpus, best, 4); } #endif for (i = 0; i < divs * divs; ++i) { printf("%.2f ", resized.y.vals[0][train.y.cols + i]); if ((i + 1) % divs == 0) printf("\n"); free_data(tiles[i]); } free_data(best); printf("\n"); image im = float_to_image(64, 64, 3, resized.X.vals[0]); // show_image(im, "orig"); // cvWaitKey(100); /* image im1 = float_to_image(64,64,3,tiles[i].X.vals[0]); image im2 = float_to_image(64,64,3,resized.X.vals[0]); show_image(im1, "tile"); show_image(im2, "res"); */ #ifdef GPU if (ngpus == 1) { aloss = train_network(net, resized); } else { aloss = train_networks(nets, ngpus, resized, 4); } #endif for (i = 0; i < divs * divs; ++i) { printf("%f ", nets[0]->output[1000 + i]); if ((i + 1) % divs == 0) printf("\n"); } printf("\n"); free_data(resized); free_data(train); if (avg_cls_loss == -1) avg_cls_loss = closs; if (avg_att_loss == -1) avg_att_loss = aloss; avg_cls_loss = avg_cls_loss * .9 + closs * .1; avg_att_loss = avg_att_loss * .9 + aloss * .1; printf("%ld, %.3f: Att: %f, %f avg, Class: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen) / N, aloss, avg_att_loss, closs, avg_cls_loss, get_current_rate(net), what_time_is_it_now() - time, *net->seen); if (*net->seen / N > epoch) { epoch = *net->seen / N; char buff[256]; sprintf(buff, "%s/%s_%d.weights", backup_directory, base, epoch); save_weights(net, buff); } if (get_current_batch(net) % 1000 == 0) { char buff[256]; sprintf(buff, "%s/%s.backup", backup_directory, base); save_weights(net, buff); } } char buff[256]; sprintf(buff, "%s/%s.weights", backup_directory, base); save_weights(net, buff); pthread_join(load_thread, 0); free_network(net); free_ptrs((void**)labels, classes); free_ptrs((void**)paths, plist->size); free_list(plist); free(base); } void validate_attention_single(char* datacfg, char* filename, char* weightfile) { int i, j; network* net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list* options = read_data_cfg(datacfg); char* label_list = option_find_str(options, "labels", "data/labels.list"); char* leaf_list = option_find_str(options, "leaves", 0); if (leaf_list) change_leaves(net->hierarchy, leaf_list); char* valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char** labels = get_labels(label_list); list* plist = get_paths(valid_list); char** paths = (char**)list_to_array(plist); int m = plist->size; free_list(plist); float avg_acc = 0; float avg_topk = 0; int* indexes = calloc(topk, sizeof(int)); int divs = 4; int size = 2; int extra = 0; float* avgs = calloc(classes, sizeof(float)); int* inds = calloc(divs * divs, sizeof(int)); for (i = 0; i < m; ++i) { int class = -1; char* path = paths[i]; for (j = 0; j < classes; ++j) { if (strstr(path, labels[j])) { class = j; break; } } image im = load_image_color(paths[i], 0, 0); image resized = resize_min(im, net->w * divs / size); image crop = crop_image(resized, (resized.w - net->w * divs / size) / 2, (resized.h - net->h * divs / size) / 2, net->w * divs / size, net->h * divs / size); image rcrop = resize_image(crop, net->w, net->h); // show_image(im, "orig"); // show_image(crop, "cropped"); // cvWaitKey(0); float* pred = network_predict(net, rcrop.data); // pred[classes + 56] = 0; for (j = 0; j < divs * divs; ++j) { printf("%.2f ", pred[classes + j]); if ((j + 1) % divs == 0) printf("\n"); } printf("\n"); copy_cpu(classes, pred, 1, avgs, 1); top_k(pred + classes, divs * divs, divs * divs, inds); show_image(crop, "crop"); for (j = 0; j < extra; ++j) { int index = inds[j]; int row = index / divs; int col = index % divs; int y = row * crop.h / divs - (net->h - crop.h / divs) / 2; int x = col * crop.w / divs - (net->w - crop.w / divs) / 2; printf("%d %d %d %d\n", row, col, y, x); image tile = crop_image(crop, x, y, net->w, net->h); float* pred = network_predict(net, tile.data); axpy_cpu(classes, 1., pred, 1, avgs, 1); show_image(tile, "tile"); // cvWaitKey(10); } if (net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1); if (rcrop.data != resized.data) free_image(rcrop); if (resized.data != im.data) free_image(resized); free_image(im); free_image(crop); top_k(pred, classes, topk, indexes); if (indexes[0] == class) avg_acc += 1; for (j = 0; j < topk; ++j) { if (indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc / (i + 1), topk, avg_topk / (i + 1)); } } void validate_attention_multi(char* datacfg, char* filename, char* weightfile) { int i, j; network* net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list* options = read_data_cfg(datacfg); char* label_list = option_find_str(options, "labels", "data/labels.list"); char* valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char** labels = get_labels(label_list); list* plist = get_paths(valid_list); int scales[] = { 224, 288, 320, 352, 384 }; int nscales = sizeof(scales) / sizeof(scales[0]); char** paths = (char**)list_to_array(plist); int m = plist->size; free_list(plist); float avg_acc = 0; float avg_topk = 0; int* indexes = calloc(topk, sizeof(int)); for (i = 0; i < m; ++i) { int class = -1; char* path = paths[i]; for (j = 0; j < classes; ++j) { if (strstr(path, labels[j])) { class = j; break; } } float* pred = calloc(classes, sizeof(float)); image im = load_image_color(paths[i], 0, 0); for (j = 0; j < nscales; ++j) { image r = resize_min(im, scales[j]); resize_network(net, r.w, r.h); float* p = network_predict(net, r.data); if (net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1, 1); axpy_cpu(classes, 1, p, 1, pred, 1); flip_image(r); p = network_predict(net, r.data); axpy_cpu(classes, 1, p, 1, pred, 1); if (r.data != im.data) free_image(r); } free_image(im); top_k(pred, classes, topk, indexes); free(pred); if (indexes[0] == class) avg_acc += 1; for (j = 0; j < topk; ++j) { if (indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc / (i + 1), topk, avg_topk / (i + 1)); } } void predict_attention(char* datacfg, char* cfgfile, char* weightfile, char* filename, int top) { network* net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); list* options = read_data_cfg(datacfg); char* name_list = option_find_str(options, "names", 0); if (!name_list) name_list = option_find_str(options, "labels", "data/labels.list"); if (top == 0) top = option_find_int(options, "top", 1); int i = 0; char** names = get_labels(name_list); clock_t time; int* indexes = calloc(top, sizeof(int)); char buff[256]; char* input = buff; while (1) { if (filename) { strncpy(input, filename, 256); } else { printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if (!input) return; strtok(input, "\n"); } image im = load_image_color(input, 0, 0); image r = letterbox_image(im, net->w, net->h); // resize_network(&net, r.w, r.h); // printf("%d %d\n", r.w, r.h); float* X = r.data; time = clock(); float* predictions = network_predict(net, X); if (net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1); top_k(predictions, net->outputs, top, indexes); fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock() - time)); for (i = 0; i < top; ++i) { int index = indexes[i]; // if(net->hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], // (net->hierarchy->parent[index] >= 0) ? names[net->hierarchy->parent[index]] : "Root"); // else printf("%s: %f\n",names[index], predictions[index]); printf("%5.2f%%: %s\n", predictions[index] * 100, names[index]); } if (r.data != im.data) free_image(r); free_image(im); if (filename) break; } } void run_attention(int argc, char** argv) { if (argc < 4) { fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char* gpu_list = find_char_arg(argc, argv, "-gpus", 0); int ngpus; int* gpus = read_intlist(gpu_list, &ngpus, gpu_index); int top = find_int_arg(argc, argv, "-t", 0); int clear = find_arg(argc, argv, "-clear"); char* data = argv[3]; char* cfg = argv[4]; char* weights = (argc > 5) ? argv[5] : 0; char* filename = (argc > 6) ? argv[6] : 0; char* layer_s = (argc > 7) ? argv[7] : 0; if (0 == strcmp(argv[2], "predict")) predict_attention(data, cfg, weights, filename, top); else if (0 == strcmp(argv[2], "train")) train_attention(data, cfg, weights, gpus, ngpus, clear); else if (0 == strcmp(argv[2], "valid")) validate_attention_single(data, cfg, weights); else if (0 == strcmp(argv[2], "validmulti")) validate_attention_multi(data, cfg, weights); }
math.h
#ifndef KUTILITY_MATH_H #define KUTILITY_MATH_H #include "kutility/general.h" // #include "kutility/linear_algebra.h" #include "kutility/convolution.h" namespace kutility { template<typename T> inline T distance( T a[2], T b[2] ) { T d0 = a[0]-b[0]; T d1 = a[1]-b[1]; return sqrt( d0*d0+d1*d1 ); } template<typename T> inline void shift_array_right( T* arr, int sz, int start ) { for( int i=sz-2; i>=start; i-- ) { arr[i+1] = arr[i]; } } /// creates a 1D gaussian filter with N(mean,sigma). inline void gaussian_1d(float* fltr, int fsz, float sigma, float mean ) { assert(fltr != NULL); int sz = (fsz-1)/2; int counter=-1; float sum = 0.0; float v = 2*sigma*sigma; for( int x=-sz; x<=sz; x++ ) { counter++; fltr[counter] = exp((-(x-mean)*(x-mean))/v); sum += fltr[counter]; } if( sum != 0 ) { for( int x=0; x<fsz; x++ ) fltr[x] /= sum; } } /// creates a 2D gaussian filter with N(mean,sigma). inline float* gaussian_2d(int fsz, float sigma, float mn) { int fltr_size = fsz * fsz; float* fltr = new float[fltr_size]; int sz = (fsz-1)/2; int y,x; int counter=-1; float sum=0; float v = 2*sigma*sigma; for( y=-sz; y<=sz; y++ ) { for( x=-sz; x<=sz; x++ ) { counter++; fltr[counter] = exp((-(x)*(x-mn)-(y-mn)*(y-mn))/v); sum += fltr[counter]; } } if( sum != 0 ) { for( x=0; x<fltr_size; x++ ) fltr[x] /= sum; } return fltr; } template<class T1, class T2> inline double normalized_cross_correlation( T1* a, T2* b, int sz ) { double mean_a = 0; double mean_b = 0; for( int i=0; i<sz; i++ ) { mean_a += a[i]; mean_b += b[i]; } mean_a /= sz; mean_b /= sz; double var_a = 0; double var_b = 0; double var_ab = 0; double a_part = 0; double b_part = 0; for( int i=0; i<sz; i++ ) { a_part = ( a[i] - mean_a ); b_part = ( b[i] - mean_b ); var_a += a_part * a_part; var_b += b_part * b_part; var_ab += a_part * b_part; } var_a /= sz; var_b /= sz; var_ab /= sz; if( var_a != 0 && var_b != 0 ) return var_ab / sqrt(var_a * var_b); else if ( var_a == 0 && var_b == 0 ) return 1; else return -1; } inline float pi() { return atan2( 0.0f, -1.0f ); } /// Applies a 2d gaussian blur of sigma std to the input array. if /// kernel_size is not set or it is set to 0, then it is taken as /// 3*sigma and if it is set to an even number, it is incremented /// to be an odd number. if in_place=true, then T1 must be equal /// to T2 naturally. template<class T1, class T2> inline T1* blur_gaussian_2d( T2* array, int rn, int cn, float sigma, int kernel_size=0, bool in_place=false ) { T1* out = NULL; if( in_place ) out = (T1*)array; else out = type_cast<T1,T2>(array,rn*cn); if( kernel_size == 0 ) kernel_size = (int)(3*sigma); if( kernel_size%2 == 0 ) kernel_size++; // kernel size must be odd if( kernel_size < 3 ) kernel_size= 3; // kernel size cannot be smaller than 3 float* kernel = new float[kernel_size]; gaussian_1d(kernel, kernel_size, sigma, 0); // !! apply the filter separately convolve_sym( out, rn, cn, kernel, kernel_size ); // conv_horizontal( out, rn, cn, kernel, kernel_size); // conv_vertical ( out, rn, cn, kernel, kernel_size); deallocate(kernel); return out; } /// inserts a portion of the source to the destination. template<class Td, class Ts> void insert( Td* dst, int dcn, int dymin, int dymax, int dxmin, int dxmax, Ts* src, int scn, int symin=-1, int symax=-1, int sxmin=-1, int sxmax=-1 ) { int xsz = dxmax - dxmin; int ysz = dymax - dymin; if( symin == -1 && symax == -1 && sxmin == -1 && sxmax == -1 ) { sxmin = 0; symin = 0; sxmax = scn; symax = ysz; } if( ysz != symax - symin ) error("insert: intervals must match"); if( xsz != sxmax - sxmin ) error("insert: intervals must match"); for( int y=0; y<ysz; y++ ) { for( int x=0; x<xsz; x++ ) { dst[ (dymin+y)*dcn+(dxmin+x) ] = (Td)( src[ (symin+y)*scn+(sxmin+x) ] ); } } } /// swaps the values of y and x template<class T> inline void swap(T &y, T &x) { T tmp = x; x = y; y = tmp; } /// inverts a boolean array: 1->0 & 0->1. inline bool* invert( bool* data, int sz, bool in_place=true) { bool* out=NULL; if( in_place ) out = data; else out = new bool[sz]; for(int i=0; i<sz; i++) out[i] = !data[i]; return out; } /// extracts a square patch of patch_width x patch_width from a the /// image around the point ry,rx ; /// returns true if all the pixels are within the image and false /// if some of the pixels are outside the image. template<class T1, class T2> bool extract_patch( T1* dst, T1* src, int h, int w, T2 ry, T2 rx, int patch_width ) { float w_2 = patch_width/2; float x,y; float yy, xx; bool out_of_image = true; int index=0; for( y=0; y<patch_width; y++ ) { for( x=0; x<patch_width; x++ ) { yy = ry + y - w_2; xx = rx + x - w_2; if( is_outside( xx, 0, w, yy, 0, h ) ) { dst[index] = 0; out_of_image = false; } else { dst[ index ] = (T1)bilinear_interpolation( src, w, xx, yy ); } index++; } } return out_of_image; } /// extracts a square patch of patch_width x patch_width from a /// rotated image around the point ry,rx ; rotation_angle is in /// radians. returns true if all the pixels are within the image /// and false if some of the pixels are outside the image. template<class T1, class T2, class T3> bool extract_rotated_patch( T1* dst, T1* src, int h, int w, T2 ry, T2 rx, int patch_width, T3 rotation_angle ) { int w_2 = patch_width/2; float kos = cos( rotation_angle ); float zin = sin( rotation_angle ); int yp, xp; float yu, xu; float y, x; int index = 0; bool out_of_image = true; for( yp=0; yp<patch_width; yp++ ) { for( xp=0; xp<patch_width; xp++ ) { xu = xp-w_2; yu = yp-w_2; x = kos * xu - zin * yu + rx; y = zin * xu + kos * yu + ry; if( is_inside( x, 0, w, y, 0, h ) ) { dst[ index ] = (T1)bilinear_interpolation(src, w, x, y); } else { dst[ index ] = 0; out_of_image = false; } index++; } } return out_of_image; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T* extract( T* src, int xmin, int xmax, int ymin, int ymax, int matw) { int xsz = xmax - xmin; int ysz = ymax - ymin; T* dst = new T[ysz*xsz]; int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy*xsz+xx] = src[y*matw+x]; xx++; } yy++; } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T* crop( T* src, int h, int w, int center_y, int center_x, int patch_rad) { int pw = 2*patch_rad+1; int psz = pw*pw; T* dst = new T[psz]; initialize( dst, psz, 0); int yy, xx; for( yy = -patch_rad; yy<=patch_rad; yy++ ) { if( yy + center_y < 0 || yy + center_y > h ) continue; for( xx = -patch_rad; xx<=patch_rad; xx++ ) { if( xx+center_x < 0 || xx+center_x > w ) continue; dst[ ( yy+patch_rad ) * pw + xx + patch_rad ] = src[ (yy+center_y)*w+xx+center_x ]; } } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should allocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> void extract( T* dst, T* src, int xmin, int xmax, int ymin, int ymax, int mw) { int xsz = xmax - xmin; int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy*xsz+xx] = src[y*mw+x]; xx++; } yy++; } } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should deallocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> T** extract( T** src, int xmin, int xmax, int ymin, int ymax) { int xsz = xmax - xmin; int ysz = ymax - ymin; T** dst = allocate<T>(ysz,xsz); int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy][xx] = src[y][x]; xx++; } yy++; } return dst; } /// extracts a portion of the matrix [ymin:ymax) & [xmin:xmax) /// and returns the result in the given pointer. /// note: you should allocate the dst memory yourself /// note: upper boundaries are not included in the output matrix template<class T> void extract( T** dst, T** src, int xmin, int xmax, int ymin, int ymax) { int yy=0; int xx=0; for( int y=ymin; y<ymax; y++ ) { xx=0; for( int x=xmin; x<xmax; x++ ) { dst[yy][xx] = src[y][x]; xx++; } yy++; } } /// rounds a number: if real part is bigger than 0,5 rounds up else down template<class T> inline T round( T x ) { T fx = floor(x); if( x-fx > 0.5 ) return fx+1; else return fx; } /// rounds an array of numbers: if real part is bigger than 0,5 /// rounds up else down. template<class T> inline T* round( T* x, int sz, bool in_place = false ) { T* out; if( in_place ) out = x; else out = allocate<T>(sz); for( int i=0; i<sz; i++ ) { out[i] = round(x[i]); } return out; } // /// filters the image with a filter. // float* filter_2d(float* &im, int r, int c, float* filter, int fr, int fc, bool in_place=false); /// r & c is the size of the image and filter has fr, fc size. it /// supports in place filtering. it uses simple for loops and does /// not employs a fast convolution implementation. beware: it is /// not equal to convolution - it does not invert the filter. template<class T> T* filter_2d(T* &im, int r, int c, T* filter, int fr, int fc, bool in_place) { int y,x; int yy,xx; int ya,xa; int yc, yac; int fr_half = fr/2; int fc_half = fc/2; int sz = r*c; T* out = allocate<T>(sz); initialize(out, sz, 0); T sum; int findex=0; for( y=0; y<r; y++ ) { ya = y - fr_half-1; yc = y*c; for( x=0; x<c; x++ ) { sum = 0; xa = x-fc_half-1; findex=0; for( yy=0; yy<fr; yy++ ) { ya++; if( is_outside(ya, 0, r) ) { findex += fc; continue; } yac = ya*c; for( xx=0; xx<fc; xx++ ) { xa++; if( is_outside(xa,0,c) ) { findex++; continue; } sum += im[yac+xa]*filter[findex++]; } xa -= fc; } ya -= fr; out[yc++] = sum; } } if( in_place ) { delete []im; im = out; } return out; } /// returns an array filled with ones. template<class T> inline T* ones (int r) { T* data = allocate<T>(r); for( int i=0; i<r; i++ ) data[i] = 1; return data; } /// returns an array filled with zeroes. template<class T> inline T* zeros(int r) { T* data = allocate<T>(r); memset( data, 0, sizeof(T)*r ); return data; } /// computes the square of a number and returns it. template<class T> inline T square(T a) { return a*a; } /// computes the square of an array. if in_place is enabled, the /// result is returned in the array arr. template<class T> inline T* square(T* arr, int sz, bool in_place=false) { T* out; if( in_place ) out = arr; else out = allocate<T>(sz); for( int i=0; i<sz; i++ ) out[i] = arr[i]*arr[i]; return out; } /// computes the p power of a number and returns it. template<class T1, class T2> inline T1 power(T1 a, T2 p) { return (T1)pow(a,p); } /// computes the p power of an array. if in_place is enabled, the /// result is returned in the array arr. template<class T1, class T2> inline T1* power(T1* arr, int sz, T2 p, bool in_place=false) { T1* out; if( in_place ) out = arr; else out = allocate<T1>(sz); for( int i=0; i<sz; i++ ) out[i] = power(arr[i],p); return out; } /// returns the theta component of a point in the range -PI to PI. template<class T> inline float angle(T x, T y) { return atan2( (float)y, (float)x ); } /// returns the theta component of a point array in the range -PI to PI. template<class T> inline float* angle(T* x, T* y, int lsz) { float* ang = allocate<float>(lsz); for( int k=0; k<lsz; k++ ) { ang[k] = angle<T>(x[k],y[k]); } return ang; } /// returns the radial component of a point. template<class T> inline T magnitude(T x, T y) { return sqrt(x*x+y*y); } /// computes the radial component of a 2D array and returns the /// result in a REAL array. the x&y coordinates are given in /// separate 1D arrays together with their size. template<class T> inline T* magnitude(T* arrx, T* arry, int lsz) { T* mag = allocate<T>(lsz); for( int k=0; k<lsz; k++ ) { mag[k] = sqrt( arrx[k]*arrx[k] + arry[k]*arry[k] ); } return mag; } /// Converts the given cartesian coordinates of a point to polar /// ones. template<class T> inline void cartesian2polar(T x, T y, float &r, float &th) { r = magnitude(x,y); th = angle(x,y); } /// Converts the given polar coordinates of a point to cartesian /// ones. template<class T1, class T2> inline void polar2cartesian(T1 r, T1 t, T2 &y, T2 &x) { x = (T2)( r * cos( t ) ); y = (T2)( r * sin( t ) ); } /// returns an interval list that starts at "st" and ends at "en" /// having "level_no" levels. The list has entries like : /// [ s1 e1 ; /// s2 e2 ; /// .... /// sn en ] -> s(i+1) = e(i) /// the function uses upto 4 point precisions if not specified template<class T> inline T** interval( T st, T en, int levels, int prec=4) { T** interval_list = allocate<T>(levels, 2); float step = ((float)(en-st))/levels; for( int i=0; i<levels; i++ ) { interval_list[i][0] = i*step+st; interval_list[i][1] = i*step+st+step; } return interval_list; } /// computes the gradient of an image and returns the result in /// pointers to REAL. template <class T> inline void gradient(T* im, int h, int w, T* dy, T* dx) { assert( dx != NULL ); assert( dy != NULL ); for( int y=0; y<h; y++ ) { int yw = y*w; for( int x=0; x<w; x++ ) { int ind = yw+x; // dx if( x>0 && x<w-1 ) dx[ind] = ((T)im[ind+1]-(T)im[ind-1])/2.0; if( x==0 ) dx[ind] = ((T)im[ind+1]-(T)im[ind]); if( x==w-1 ) dx[ind] = ((T)im[ind ]-(T)im[ind-1]); //dy if( y>0 && y<h-1 ) dy[ind] = ((T)im[ind+w]-(T)im[ind-w])/2.0; if( y==0 ) dy[ind] = ((T)im[ind+w]-(T)im[ind]); if( y==h-1 ) dy[ind] = ((T)im[ind] -(T)im[ind-w]); } } } template<class T> inline T is_positive( T number ) { if( number > 0 ) return number; else return (T)(0); } template<class T> inline T* layered_gradient( T* data, int h, int w, int layer_no=8 ) { int data_size = h * w; T* layers = zeros<T>(layer_no * data_size); // smooth the data matrix T* bdata = blur_gaussian_2d<T,T>( data, h, w, 0.5, 5, false); T *dx = new T[data_size]; T *dy = new T[data_size]; gradient(bdata, h, w, dy, dx); deallocate( bdata ); #if defined(WITH_OPENMP) #pragma omp parallel for #endif for( int l=0; l<layer_no; l++ ) { float angle = 2*l*pi()/layer_no; float kos = cos( angle ); float zin = sin( angle ); T* layer_l = layers + l*data_size; for( int index=0; index<data_size; index++ ) { float value = kos * dx[ index ] + zin * dy[ index ]; if( value > 0 ) layer_l[index] = value; else layer_l[index] = 0; } } deallocate(dy); deallocate(dx); return layers; } /// be careful, 'data' is destroyed afterwards template<class T> inline void layered_gradient( T* data, int h, int w, int layer_no, T* layers, T* workspace=0, int lwork=0 ) { int data_size = h * w; assert(layers!=NULL); memset(layers,0,sizeof(T)*data_size*layer_no); bool empty=false; T* work=NULL; if( lwork < 3*data_size ) { work = new T[3*data_size]; empty=true; } // // smooth the data matrix // T* bdata = blur_gaussian_2d<T,T>( data, h, w, 0.5, 5, false); float kernel[5]; gaussian_1d(kernel, 5, 0.5, 0); memcpy( work, data, sizeof(T)*data_size); convolve_sym( work, h, w, kernel, 5 ); T *dx = work+data_size; T *dy = work+2*data_size; gradient( work, h, w, dy, dx ); #if defined(WITH_OPENMP) #pragma omp parallel for #endif for( int l=0; l<layer_no; l++ ) { float angle = 2*l*pi()/layer_no; float kos = cos( angle ); float zin = sin( angle ); T* layer_l = layers + l*data_size; for( int index=0; index<data_size; index++ ) { float value = kos * dx[ index ] + zin * dy[ index ]; if( value > 0 ) layer_l[index] = value; else layer_l[index] = 0; } } if( empty ) delete []work; } /// computes the bilinearly interpolated value of the point (x,y). template<class T1, class T2> inline float bilinear_interpolation(T1* arr, int w, T2 x, T2 y) { int mnx = (int)floor( x ); int mny = (int)floor( y ); int mxx = (int) ceil( x ); int mxy = (int) ceil( y ); double alfa = mxx - x; double beta = mxy - y; if( alfa < 0.001 ) alfa = 0; if( beta < 0.001 ) beta = 0; int mnyw = mny * w; int mxyw = mxy * w; if( alfa < 0.001 ) return float(beta * arr[mnyw+mxx] + (1-beta) * arr[mxyw+mxx]); if( alfa > 0.999 ) return float(beta * arr[mnyw+mnx] + (1-beta) * arr[mxyw+mnx]); if( beta < 0.001 ) return float(alfa * arr[mxyw+mnx] + (1-alfa) * arr[mxyw+mxx]); if( beta > 0.999 ) return float(alfa * arr[mnyw+mnx] + (1-alfa) * arr[mnyw+mxx]); return float( beta*(alfa * arr[mnyw+mnx] + (1-alfa)*arr[mnyw+mxx] ) +(1-beta)*(alfa * arr[mxyw+mnx] + (1-alfa)*arr[mxyw+mxx] ) ); } /// divides the elements of the array with "norm". function /// supports in-place operations in which case the result is casted /// to the input type; default is non-in-place. template<class T1, class T2> inline T2* normalize(T1* data, int sz, T2 norm, bool in_place=false) { assert( norm != 0.0 ); float inv_norm = 1.0/norm; if( in_place ) { for( int i=0; i<sz; i++ ) { data[i] = (T1)(data[i]*inv_norm); } return NULL; } else { T2* new_data = allocate<T2>(sz); for( int i=0; i<sz; i++ ) { new_data[i] = (T2)(data[i]*inv_norm); } return new_data; } } template<typename T> inline void diff( const T* a, const T* b, const int sz, T* a_m_b) { for( int k=0; k<sz; k++ ) a_m_b[k] = a[k] - b[k]; } /// computes the difference of two arrays and returns the resulting /// array. function supports in place operation, and returns the /// result in the "a" array if in place is enabled. template<class T> inline T* diff( T* a, const T* b, const int sz, bool in_place=false) { T* d=NULL; if( in_place ) d = a; else d = allocate<T>(sz); for( int k=0; k<sz; k++ ) { d[k] = a[k]-b[k]; } return d; } /// computes the absolute difference of two arrays and returns the /// resulting array : d = |a-b|. function supports in place /// operation, and returns the result in the "a" array if in place /// is enabled. template<class T> inline T* absdiff( T* a, T* b, int sz, bool in_place=false) { T* d=NULL; if( in_place ) d = a; else d = allocate<T>(sz); for( int k=0; k<sz; k++ ) { d[k] = (T)fabs(a[k]-b[k]); } return d; } /// computes the absolute difference of two matrices and returns /// the resulting matrix : d = |a-b|. function supports in place /// operation, and returns the result in the "a" matrix if in place /// is enabled. template<class T> inline T** absdiff( T** a, T** b, int ysz, int xsz, bool in_place=false) { T** d=NULL; if( in_place ) d = a; else d = allocate<T>(ysz,xsz); for( int y=0; y<ysz; y++ ) { for( int x=0; x<xsz; x++ ) { d[y][x] = fabs(a[y][x]-b[y][x]); } } return d; } /// computes the l1norm of an array: sum_i( |a(i)| ) template<class T> inline T l1norm( T* a, int sz) { T norm=0; for( int k=0; k<sz; k++ ) norm += abs( a[k] ); } /// computes the l1norm of the difference of two arrays: sum_i( a(i)-b(i) ) template<class T> inline T l1norm( T* a, T* b, int sz) { T norm=0; for( int k=0; k<sz; k++ ) norm += abs(a[k]-b[k]); return norm; } /// computes the l2norm of an array: [ sum_i( [a(i)]^2 ) ]^0.5 template<class T> inline float l2norm( T* a, int sz) { float norm=0; for( int k=0; k<sz; k++ ) norm += a[k]*a[k]; return sqrt(norm); } /// computes the l2norm of the difference of two arrays: [ sum_i( [a(i)-b(i)]^2 ) ]^0.5 template<class T1, class T2> inline float l2norm( T1* a, T2* b, int sz) { float norm=0; for( int i=0; i<sz; i++ ) { norm += square( (float)a[i] - (float)b[i] ); } norm = sqrt( norm ); return norm; } template<class T> inline float l2norm( T y0, T x0, T y1, T x1 ) { float d0 = x0 - x1; float d1 = y0 - y1; return sqrt( d0*d0 + d1*d1 ); } /// computes the l2 norm of the difference of two arrays by /// weighting regions of them. if reg is set to -1 (or not /// specified) each difference is weighted. if reg is not -1, /// arrays are assumed to be composed of sz/reg segments and the /// weighting is applied to these segments. reg must be a integer /// multiple of sz. template<class T1, class T2> inline float weighted_l2_norm(T1* a, T1* b, int sz, T2* w=NULL, int reg=-1) { if( w == NULL ) error("weight array is NULL. use more efficient l2norm instead"); int wsz; if( reg == -1 ) wsz = sz; else wsz = reg; int rsz = sz / reg; if( rsz*reg != reg ) error("reg must be an integer multiple of array size sz"); int k; float norm=0; float sub_norm=0; for( k=0; k<wsz; k++ ) { sub_norm = l2norm( a+k*rsz, b+k*rsz, rsz ); norm += w[k] * sub_norm; } return norm; } template<class T1, class T2> inline float mean_absolute_difference( T1* arr1, T2* arr2, int size) { float mad_score=0; for( int i=0; i<size; i++ ) { mad_score += fabs( (float)arr1[i] - (float)arr2[i] ); } return mad_score/size; } /// adds a constant number to every number in the array; template<class T1, class T2> inline T1* add(T1* arr, int sz, T2 num, bool in_place=false) { T1* out; if( in_place ) out = arr; else out = allocate<T1>(sz); for( int i=0; i<sz; i++ ) { out[i] = arr[i] + (T1)num; } return out; } /// adds a constant number to every number in the matrix; template<class T1, class T2> inline T1** add(T1** arr, int ysz, int xsz, T2 num, bool in_place=false) { T1** out; if( in_place ) out = arr; else out = allocate<T1>(ysz,xsz); for( int y=0; y<ysz; y++ ) for( int x=0; x<xsz; x++ ) { out[y][x] = arr[y][x] + (T1)num; } return out; } /// subtracts a constant number from every element in the array; template<class T1, class T2> inline T1* subt(T1* arr, int sz, T2 num, bool in_place=false) { T1* out = add(arr,sz,-num,in_place); return out; } /// subtracts a constant number from every element in the matrix; template<class T1, class T2> inline T1** subt(T1** arr, int ysz, int xsz, T2 num, bool in_place=false) { T1* out = add(arr,ysz,xsz,-num,in_place); return out; } /// divides the elements of the array with num template<class T1, class T2> inline void divide(T1* arr, int sz, T2 num ) { float inv_num = 1.0 / num; for( int i=0; i<sz; i++ ) { arr[i] = (T1)(arr[i]*inv_num); } } /// thresholds the data. template<class T> inline T* threshold(T* data, int sz, T threshold) { if(sz == 0) return NULL; T* result = allocate<T>(sz); for(int i=0; i<sz; i++) { if( data[i] > threshold ) result[i] = 1; else result[i] = 0; } return result; } /// returns the sign of a point. template<class T> inline int sign(T num) { if( num < 0.0 ) return -1; if( num == 0.0 ) return 0; if( num > 0.0 ) return 1; } /// returns the sign array of an array. template<class T> inline int* sign(T* arr, int sz) { int* out = allocate<int>(sz); for( int k=0; k<sz; k++ ) { out[k] = sign( arr[k] ); } return out; } template<class T> inline int compare( const void* a, const void* b ) { return (int)(*(T*)a - *(T*)b); } /// sorts the data array "data". template<class T> inline T* quick_sort( T* data, int dsz, bool in_place=true) { T* out=NULL; if( in_place ) out = data; else out = clone(data, dsz); std::qsort( out, dsz, sizeof(T), compare<T> ); return out; } template<class T> inline T median(T* data, int dsz) { T* tmp = quick_sort(data, dsz, false); T med=0; if( dsz%2 == 1 ) med = tmp[ dsz/2 ]; else med = (tmp[ dsz/2 ] + tmp[ dsz/2 - 1 ] ) /2; deallocate(tmp); return med; } /// computes the median of the array: destroys the contents of the data array. template<typename T> inline void median( T* data, int sz, T &medval ) { std::qsort(data, sz, sizeof(T), compare<T> ); if( sz%2 == 1 ) medval = data[sz/2]; else medval = (data[sz/2]+data[sz/2-1])/2; } template<typename T> inline void smooth_median( T* data, int h, int w, int msz, T* out ) { int wsz=(2*msz+1)*(2*msz+1); const static int max_buffer_size = 441; assert( wsz < max_buffer_size ); T buffer[max_buffer_size]; for( int y=0; y<h; y++ ) { for( int x=0; x<w; x++ ) { int cnt = 0; for( int r=-msz; r<=msz; r++ ) { int yy = y+r; if( yy >= h ) yy = h-1; if( yy < 0 ) yy = 0; for( int c=-msz; c<=msz; c++ ) { int xx=x+c; if( xx >= w ) xx = w-1; if( xx < 0 ) xx = 0; buffer[cnt++] = data[yy*w+xx]; } } median( buffer, wsz, out[y*w+x] ); } } } /// multiplies two arrays element by element. /// the result is in the first array's type template<class T1, class T2> inline T1* times( T1* arr1, T2* arr2, int w) { T1* out = allocate<T1>(w); for( int i=0; i<w; i++ ) out[i] = (T1)(arr1[i]*arr2[i]); return out; } /// multiplies two matrices element by element. /// the result is in the first matrix's type template<class T1, class T2> inline T1** times( T1** mat1, T2** mat2, int h, int w) { T1** out = allocate<T1*>(h); for( int i=0; i<h; i++ ) out[i] = times( mat1[i], mat2[i], w ); return out; } /// convert a ** data to a * data in row-first order. /// it uses memcpy, therefore, works for built-in types. template<class T> inline T* arrayize(T** data, int xsz, int ysz) { T* out = allocate<T>(xsz*ysz); for( int i=0; i<ysz; i++ ) memcpy(out[i*xsz],data[i],sizeof(T)*xsz); return out; } /// inplace shifting: accepts negative shifts template<class T> T* shift_array(T* arr, int size, int shift) { // if shift = 0 -> you can return now if( shift == 0 ) return arr; T* temp_array = allocate<T>(size); // if negative -> compansate if( shift < 0 ) shift += size; // copy the first portion memcpy(temp_array, arr+shift, sizeof(T)*(size-shift) ); // copy the rest memcpy(temp_array+size-shift, arr, sizeof(T)*shift ); memcpy(arr,temp_array,size); deallocate(temp_array); return arr; } /// shifts the contents of the array in segmented regions /// i.e: shifts the contents by "shift" in a segment /// size = n*segment, n = integer template<class T> T* segmented_shift_array(T* &arr, int size, int segment, int shift) { int segment_step = size / segment; if( shift == 0 ) return arr; for( int s=0; s<size; s += segment_step ) { shift_array(arr+s, segment_step, shift); } return arr; } /// counts the number of times the value val occurs in data[] template<class T> inline int count( T* data, int sz, T val) { int counter = 0; for(int i=0; i<sz; i++) { if( data[i] == val ) counter++; } return counter; } template<class T1, class T2> inline void set(T1* data, int sz, T2 val) { for( int k=0; k<sz; k++ ) data[k]=(T1)val; } template<class T1, class T2> inline void set(T1** data, int rsz, int csz, T2 val) { for( int r=0; r<rsz; r++ ) for( int c=0; c<csz; c++ ) data[r][c]=(T1)val; } /// rotates x1 y1 by theta (in radians) template<class T1, class T2> inline void rotate( T1 y1, T1 x1, T2& y2, T2& x2, float theta, T1 ty, T1 tx ) { float kos = cos( theta ); float zin = sin( theta ); x2 = (T2)( x1*kos - y1*zin ); y2 = (T2)( x1*zin + y1*kos ); return; } /// rotates the image with respect to ry, rx. template<class T> inline T* rotate( T* imge, int h, int w, float theta, float ry=0, float rx=0 ) { float kos = cos(theta); float zin = sin(theta); int x, y; T* rimge = allocate<T>(h*w); initialize(rimge, h*w, 0); float ty, tx; float ny, nx; for( y=0; y<h; y++ ) { for( x=0; x<w; x++ ) { tx = x - rx; ty = y - ry; nx = ( tx * kos - ty * zin + rx ); ny = ( tx * zin + ty * kos + ry ); if( is_inside( nx, 0, w-1, ny, 0, h-1 ) ) rimge[y*w+x] = (T)bilinear_interpolation(imge, w, nx, ny); } } return rimge; } /// stretches the image to minI=0 -- maxI=255 range template<class T> inline T* stretch(T* image, int sz, T val, bool in_place=false) { // find the min intensity in roi T min_inten=INT_MAX; T max_inten=INT_MIN; for( int k=0; k<sz; k++ ) { if( image[k] <= val ) continue; if( image[k] < min_inten ) min_inten = image[k]; if( image[k] > max_inten ) max_inten = image[k]; } float s = 255.0f/(float)(max_inten-min_inten); T* output = NULL; if( in_place ) output = image; else output = zeros<T>(sz); for( int k=0; k<sz; k++ ) { if( image[k] > val ) output[k] = (T)((image[k]-min_inten) * s); else output[k] = image[k]; } return output; } /// returns the number of digits of a number. inline int digit_number(int num) { if( num == 0 ) return 1; int counter = 0; while( num != 0 ) { num /= 10; counter++; } return counter; } /// returns the value of a sigmoid spanning miny-maxy with 'rate' /// and x-symmetry axis sym_axis. /// miny-maxy : the minimum and maximum interval for the y axis. /// rate : the rate at which the sigmoid reaches maxy from miny. /// sym_axis : symmetry axis in the x axis. sig(sx-d)+sig(sx+d) = maxy: /// sum of the y values from the symmetry point makes maxy. inline float sigmoid(float x, float miny, float maxy, float rate, float sym_axis) { float xp = exp(rate*(x-sym_axis)); return (maxy - miny) * xp / ( xp + 1 ) + miny; } /// returns the "and" of two boolean arrays. inline bool* and_array( bool* a, bool* b, int sz) { bool* c = allocate<bool>(sz); for( int i=0; i<sz; i++ ) c[i] = a[i] & b[i]; return c; } /// returns the "or" of two boolean arrays. inline bool* or_array( bool* a, bool* b, int sz) { bool* c = allocate<bool>(sz); for( int i=0; i<sz; i++ ) c[i] = a[i] | b[i]; return c; } /// finds the n local-modes: locals -> return indices, workspace[sz] template<typename T> inline void find_n_local_min(const T* arr, const int sz, int* locals, const int n, T* workspace ) { int min_count=0; for( int i=0; i<sz; i++ ) workspace[i] = -1; for( int i=0; i<n; i++ ) locals[i] = -1; T prev=INT_MAX; T next=INT_MAX; for( int i=0; i<sz; i++ ) { if( i > 0 ) prev = arr[i-1]; else prev = INT_MAX; if( i < sz-1 ) next = arr[i+1]; else next = INT_MAX; if( (arr[i] < prev) && (arr[i] < next) ) { workspace[min_count] = i; min_count++; } } // cout<<"mins\n"; // for( int i=0; i<min_count; i++ ) // { // cout<<workspace[i]<<" "; // if( workspace[i] != -1 ) cout<<arr[(int)workspace[i]]<<endl; // else cout<<-1<<endl; // } // cout<<endl; bool inserted=false; int fn=1; locals[0] = workspace[0]; for( int j=1; j<min_count; j++ ) { inserted=false; if( workspace[j] == -1 ) break; for( int k=0; k<fn; k++ ) { if( arr[ (int)workspace[j] ] <= arr[ locals[k] ] ) { shift_array_right( locals, n, k ); locals[k] = workspace[j]; if( fn < n ) fn++; inserted=true; break; } } if( !inserted && (fn < n) ) { locals[fn] = workspace[j]; fn++; } } for( int i=fn; i<n; i++ ) locals[i]=-1; // cout<<"locals\n"; // for( int i=0; i<n; i++ ) // { // cout<<locals[i]<<" "; // if( locals[i] != -1 ) cout<<arr[locals[i]]<<endl; // else cout<<-1<<endl; // } // cout<<endl; } } #endif
GB_binop__remainder_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__remainder_fp32) // A.*B function (eWiseMult): GB (_AemultB_08__remainder_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__remainder_fp32) // A.*B function (eWiseMult): GB (_AemultB_04__remainder_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__remainder_fp32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__remainder_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__remainder_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__remainder_fp32) // C=scalar+B GB (_bind1st__remainder_fp32) // C=scalar+B' GB (_bind1st_tran__remainder_fp32) // C=A+scalar GB (_bind2nd__remainder_fp32) // C=A'+scalar GB (_bind2nd_tran__remainder_fp32) // C type: float // A type: float // A pattern? 0 // B type: float // B pattern? 0 // BinaryOp: cij = remainderf (aij, bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = remainderf (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_REMAINDER || GxB_NO_FP32 || GxB_NO_REMAINDER_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__remainder_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__remainder_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__remainder_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #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 float *restrict Cx = (float *) 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 float *restrict Cx = (float *) 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__remainder_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; float alpha_scalar ; float beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((float *) alpha_scalar_in)) ; beta_scalar = (*((float *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__remainder_fp32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__remainder_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__remainder_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__remainder_fp32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__remainder_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = remainderf (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__remainder_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = remainderf (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) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = remainderf (x, aij) ; \ } GrB_Info GB (_bind1st_tran__remainder_fp32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = remainderf (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__remainder_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ccsd_t.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <complex.h> #include "config.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" typedef struct { void *cache[6]; short a; short b; short c; short _padding; } CacheJob; /* * 4 * w + w.transpose(1,2,0) + w.transpose(2,0,1) * - 2 * w.transpose(2,1,0) - 2 * w.transpose(0,2,1) * - 2 * w.transpose(1,0,2) */ static void add_and_permute(double *out, double *w, double *v, int n) { int nn = n * n; int nnn = nn * n; int i, j, k; for (i = 0; i < nnn; i++) { v[i] += w[i]; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { out[i*nn+j*n+k] = v[i*nn+j*n+k] * 4 + v[j*nn+k*n+i] + v[k*nn+i*n+j] - v[k*nn+j*n+i] * 2 - v[i*nn+k*n+j] * 2 - v[j*nn+i*n+k] * 2; } } } } /* * t2T = t2.transpose(2,3,1,0) * ov = vv_op[:,nocc:] * oo = vv_op[:,:nocc] * w = numpy.einsum('if,fjk->ijk', ov, t2T[c]) * w-= numpy.einsum('ijm,mk->ijk', vooo[a], t2T[c,b]) * v = numpy.einsum('ij,k->ijk', oo, t1T[c]*.5) * v+= numpy.einsum('ij,k->ijk', t2T[b,a], fov[:,c]*.5) * v+= w */ static void get_wv(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1Thalf, double *t2T, int nocc, int nvir, int a, int b, int c, int *idx) { const double D0 = 0; const double D1 = 1; const double DN1 =-1; const char TRANS_N = 'N'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double *pt2T; dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &D1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); dgemm_(&TRANS_N, &TRANS_N, &nocc, &noo, &nocc, &DN1, t2T+c*nvoo+b*noo, &nocc, vooo+a*nooo, &nocc, &D1, cache, &nocc); pt2T = t2T + b * nvoo + a * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { w[idx[n]] += cache[n]; v[idx[n]] +=(vv_op[i*nmo+j] * t1Thalf[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } static void sym_wv(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1Thalf, double *t2T, int nocc, int nvir, int a, int b, int c, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, int *idx) { const double D0 = 0; const double D1 = 1; const char TRANS_N = 'N'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int a_irrep = orbsym[nocc+a]; int b_irrep = orbsym[nocc+b]; int c_irrep = orbsym[nocc+c]; int ab_irrep = a_irrep ^ b_irrep; int bc_irrep = c_irrep ^ b_irrep; int i, j, k, n; int fr, f0, f1, df, mr, m0, m1, dm, mk0; int ir, i0, i1, di, kr, k0, k1, dk, jr; int ijr, ij0, ij1, dij, jkr, jk0, jk1, djk; double *pt2T; /* symmetry adapted * w = numpy.einsum('if,fjk->ijk', ov, t2T[c]) */ pt2T = t2T + c * nvoo; for (ir = 0; ir < nirrep; ir++) { i0 = o_ir_loc[ir]; i1 = o_ir_loc[ir+1]; di = i1 - i0; if (di > 0) { fr = ir ^ ab_irrep; f0 = v_ir_loc[fr]; f1 = v_ir_loc[fr+1]; df = f1 - f0; if (df > 0) { jkr = fr ^ c_irrep; jk0 = oo_ir_loc[jkr]; jk1 = oo_ir_loc[jkr+1]; djk = jk1 - jk0; if (djk > 0) { dgemm_(&TRANS_N, &TRANS_N, &djk, &di, &df, &D1, pt2T+f0*noo+jk0, &noo, vv_op+i0*nmo+nocc+f0, &nmo, &D0, cache, &djk); for (n = 0, i = o_ir_loc[ir]; i < o_ir_loc[ir+1]; i++) { for (jr = 0; jr < nirrep; jr++) { kr = jkr ^ jr; for (j = o_ir_loc[jr]; j < o_ir_loc[jr+1]; j++) { for (k = o_ir_loc[kr]; k < o_ir_loc[kr+1]; k++, n++) { w[idx[i*noo+j*nocc+k]] += cache[n]; } } } } } } } } /* symmetry adapted * w-= numpy.einsum('ijm,mk->ijk', eris_vooo[a], t2T[c,b]) */ pt2T = t2T + c * nvoo + b * noo; vooo += a * nooo; mk0 = oo_ir_loc[bc_irrep]; for (mr = 0; mr < nirrep; mr++) { m0 = o_ir_loc[mr]; m1 = o_ir_loc[mr+1]; dm = m1 - m0; if (dm > 0) { kr = mr ^ bc_irrep; k0 = o_ir_loc[kr]; k1 = o_ir_loc[kr+1]; dk = k1 - k0; if (dk > 0) { ijr = mr ^ a_irrep; ij0 = oo_ir_loc[ijr]; ij1 = oo_ir_loc[ijr+1]; dij = ij1 - ij0; if (dij > 0) { dgemm_(&TRANS_N, &TRANS_N, &dk, &dij, &dm, &D1, pt2T+mk0, &dk, vooo+ij0*nocc+m0, &nocc, &D0, cache, &dk); for (n = 0, ir = 0; ir < nirrep; ir++) { jr = ijr ^ ir; for (i = o_ir_loc[ir]; i < o_ir_loc[ir+1]; i++) { for (j = o_ir_loc[jr]; j < o_ir_loc[jr+1]; j++) { for (k = o_ir_loc[kr]; k < o_ir_loc[kr+1]; k++, n++) { w[idx[i*noo+j*nocc+k]] -= cache[n]; } } } } } mk0 += dm * dk; } } } pt2T = t2T + b * nvoo + a * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { v[idx[n]] +=(vv_op[i*nmo+j] * t1Thalf[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } double _ccsd_t_get_energy(double *w, double *v, double *mo_energy, int nocc, int a, int b, int c, double fac) { int i, j, k, n; double abc = mo_energy[nocc+a] + mo_energy[nocc+b] + mo_energy[nocc+c]; double et = 0; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { et += fac * w[n] * v[n] / (mo_energy[i] + mo_energy[j] + mo_energy[k] - abc); } } } return et; } static double contract6(int nocc, int nvir, int a, int b, int c, double *mo_energy, double *t1T, double *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double *fvo, double *vooo, double *cache1, void **cache, int *permute_idx) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double *v0 = cache1; double *w0 = v0 + nooo; double *z0 = w0 + nooo; double *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } if (nirrep == 1) { get_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, idx0); get_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, idx1); get_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, idx2); get_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, idx3); get_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, idx4); get_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, idx5); } else { sym_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx0); sym_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx1); sym_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx2); sym_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx3); sym_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx4); sym_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, idx5); } add_and_permute(z0, w0, v0, nocc); double et; if (a == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } size_t _ccsd_t_gen_jobs(CacheJob *jobs, int nocc, int nvir, int a0, int a1, int b0, int b1, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b, size_t stride) { size_t nov = nocc * (nocc+nvir) * stride; int da = a1 - a0; int db = b1 - b0; size_t m, a, b, c; if (b1 <= a0) { m = 0; for (a = a0; a < a1; a++) { for (b = b0; b < b1; b++) { for (c = 0; c < b0; c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; jobs[m].cache[0] = cache_row_a + nov*(a1*(a-a0)+b ); jobs[m].cache[1] = cache_row_a + nov*(a1*(a-a0)+c ); jobs[m].cache[2] = cache_col_a + nov*(da*(b) +a-a0); jobs[m].cache[3] = cache_row_b + nov*(b1*(b-b0)+c ); jobs[m].cache[4] = cache_col_a + nov*(da*(c) +a-a0); jobs[m].cache[5] = cache_col_b + nov*(db*(c) +b-b0); } for (c = b0; c <= b; c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; jobs[m].cache[0] = cache_row_a + nov*(a1*(a-a0)+b ); jobs[m].cache[1] = cache_row_a + nov*(a1*(a-a0)+c ); jobs[m].cache[2] = cache_col_a + nov*(da*(b) +a-a0); jobs[m].cache[3] = cache_row_b + nov*(b1*(b-b0)+c ); jobs[m].cache[4] = cache_col_a + nov*(da*(c) +a-a0); jobs[m].cache[5] = cache_row_b + nov*(b1*(c-b0)+b ); } } } } else { m = 0; for (a = a0; a < a1; a++) { for (b = a0; b <= a; b++) { for (c = 0; c < a0; c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; jobs[m].cache[0] = cache_row_a + nov*(a1*(a-a0)+b); jobs[m].cache[1] = cache_row_a + nov*(a1*(a-a0)+c); jobs[m].cache[2] = cache_row_a + nov*(a1*(b-a0)+a); jobs[m].cache[3] = cache_row_a + nov*(a1*(b-a0)+c); jobs[m].cache[4] = cache_col_a + nov*(da*(c)+a-a0); jobs[m].cache[5] = cache_col_a + nov*(da*(c)+b-a0); } for (c = a0; c <= b; c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; jobs[m].cache[0] = cache_row_a + nov*(a1*(a-a0)+b); jobs[m].cache[1] = cache_row_a + nov*(a1*(a-a0)+c); jobs[m].cache[2] = cache_row_a + nov*(a1*(b-a0)+a); jobs[m].cache[3] = cache_row_a + nov*(a1*(b-a0)+c); jobs[m].cache[4] = cache_row_a + nov*(a1*(c-a0)+a); jobs[m].cache[5] = cache_row_a + nov*(a1*(c-a0)+b); } } } } return m; } void _make_permute_indices(int *idx, int n) { const int nn = n * n; const int nnn = nn * n; int *idx0 = idx; int *idx1 = idx0 + nnn; int *idx2 = idx1 + nnn; int *idx3 = idx2 + nnn; int *idx4 = idx3 + nnn; int *idx5 = idx4 + nnn; int i, j, k, m; for (m = 0, i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++, m++) { idx0[m] = i * nn + j * n + k; idx1[m] = i * nn + k * n + j; idx2[m] = j * nn + i * n + k; idx3[m] = k * nn + i * n + j; idx4[m] = j * nn + k * n + i; idx5[m] = k * nn + j * n + i; } } } } void CCsd_t_contract(double *e_tot, double *mo_energy, double *t1T, double *t2T, double *vooo, double *fvo, int nocc, int nvir, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double)); int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvo, jobs, e_tot, permute_idx) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (nocc*nocc*nocc*3+2)); double *t1Thalf = malloc(sizeof(double) * nvir*nocc * 2); double *fvohalf = t1Thalf + nvir*nocc; for (k = 0; k < nvir*nocc; k++) { t1Thalf[k] = t1T[k] * .5; fvohalf[k] = fvo[k] * .5; } double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += contract6(nocc, nvir, a, b, c, mo_energy, t1Thalf, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx); } free(t1Thalf); free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); } /* * Complex version of all functions */ static void zadd_and_permute(double complex *out, double complex *w, double complex *v, int n) { int nn = n * n; int nnn = nn * n; int i, j, k; for (i = 0; i < nnn; i++) { v[i] += w[i]; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { out[i*nn+j*n+k] = v[i*nn+j*n+k] * 4 + v[j*nn+k*n+i] + v[k*nn+i*n+j] - v[k*nn+j*n+i] * 2 - v[i*nn+k*n+j] * 2 - v[j*nn+i*n+k] * 2; } } } } static void zget_wv(double complex *w, double complex *v, double complex *cache, double complex *fvohalf, double complex *vooo, double complex *vv_op, double complex *t1Thalf, double complex *t2T, int nocc, int nvir, int a, int b, int c, int *idx) { const double complex D0 = 0; const double complex D1 = 1; const double complex DN1 =-1; const char TRANS_N = 'N'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double complex *pt2T; zgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &D1, t2T+c*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); zgemm_(&TRANS_N, &TRANS_N, &nocc, &noo, &nocc, &DN1, t2T+c*nvoo+b*noo, &nocc, vooo+a*nooo, &nocc, &D1, cache, &nocc); pt2T = t2T + b * nvoo + a * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { w[idx[n]] += cache[n]; v[idx[n]] +=(vv_op[i*nmo+j] * t1Thalf[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } double _ccsd_t_zget_energy(double complex *w, double complex *v, double *mo_energy, int nocc, int a, int b, int c, double fac) { int i, j, k, n; double abc = mo_energy[nocc+a] + mo_energy[nocc+b] + mo_energy[nocc+c]; double et = 0; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { et += fac / (mo_energy[i] + mo_energy[j] + mo_energy[k] - abc) * w[n] * conj(v[n]); } } } return et; } static double complex zcontract6(int nocc, int nvir, int a, int b, int c, double *mo_energy, double complex *t1T, double complex *t2T, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, double complex *fvo, double complex *vooo, double complex *cache1, void **cache, int *permute_idx) { int nooo = nocc * nocc * nocc; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double complex *v0 = cache1; double complex *w0 = v0 + nooo; double complex *z0 = w0 + nooo; double complex *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } zget_wv(w0, v0, wtmp, fvo, vooo, cache[0], t1T, t2T, nocc, nvir, a, b, c, idx0); zget_wv(w0, v0, wtmp, fvo, vooo, cache[1], t1T, t2T, nocc, nvir, a, c, b, idx1); zget_wv(w0, v0, wtmp, fvo, vooo, cache[2], t1T, t2T, nocc, nvir, b, a, c, idx2); zget_wv(w0, v0, wtmp, fvo, vooo, cache[3], t1T, t2T, nocc, nvir, b, c, a, idx3); zget_wv(w0, v0, wtmp, fvo, vooo, cache[4], t1T, t2T, nocc, nvir, c, a, b, idx4); zget_wv(w0, v0, wtmp, fvo, vooo, cache[5], t1T, t2T, nocc, nvir, c, b, a, idx5); zadd_and_permute(z0, w0, v0, nocc); double complex et; if (a == c) { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_zget_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } void CCsd_t_zcontract(double complex *e_tot, double *mo_energy, double complex *t1T, double complex *t2T, double complex *vooo, double complex *fvo, int nocc, int nvir, int a0, int a1, int b0, int b1, int nirrep, int *o_ir_loc, int *v_ir_loc, int *oo_ir_loc, int *orbsym, void *cache_row_a, void *cache_col_a, void *cache_row_b, void *cache_col_b) { int da = a1 - a0; int db = b1 - b0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*b1); size_t njobs = _ccsd_t_gen_jobs(jobs, nocc, nvir, a0, a1, b0, b1, cache_row_a, cache_col_a, cache_row_b, cache_col_b, sizeof(double complex)); int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, t2T, nirrep, o_ir_loc, \ v_ir_loc, oo_ir_loc, orbsym, vooo, fvo, jobs, e_tot, permute_idx) { int a, b, c; size_t k; double complex *cache1 = malloc(sizeof(double complex) * (nocc*nocc*nocc*3+2)); double complex *t1Thalf = malloc(sizeof(double complex) * nvir*nocc * 2); double complex *fvohalf = t1Thalf + nvir*nocc; for (k = 0; k < nvir*nocc; k++) { t1Thalf[k] = t1T[k] * .5; fvohalf[k] = fvo[k] * .5; } double complex e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += zcontract6(nocc, nvir, a, b, c, mo_energy, t1Thalf, t2T, nirrep, o_ir_loc, v_ir_loc, oo_ir_loc, orbsym, fvohalf, vooo, cache1, jobs[k].cache, permute_idx); } free(t1Thalf); free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); } /***************************************************************************** * * mpi4pyscf * *****************************************************************************/ static void MPICCget_wv(double *w, double *v, double *cache, double *fvohalf, double *vooo, double *vv_op, double *t1Thalf, double *t2T_a, double *t2T_c, int nocc, int nvir, int a, int b, int c, int a0, int b0, int c0, int *idx) { const double D0 = 0; const double D1 = 1; const double DN1 = -1; const char TRANS_N = 'N'; const int nmo = nocc + nvir; const int noo = nocc * nocc; const size_t nooo = nocc * noo; const size_t nvoo = nvir * noo; int i, j, k, n; double *pt2T; dgemm_(&TRANS_N, &TRANS_N, &noo, &nocc, &nvir, &D1, t2T_c+(c-c0)*nvoo, &noo, vv_op+nocc, &nmo, &D0, cache, &noo); dgemm_(&TRANS_N, &TRANS_N, &nocc, &noo, &nocc, &DN1, t2T_c+(c-c0)*nvoo+b*noo, &nocc, vooo+(a-a0)*nooo, &nocc, &D1, cache, &nocc); pt2T = t2T_a + (a-a0) * nvoo + b * noo; for (n = 0, i = 0; i < nocc; i++) { for (j = 0; j < nocc; j++) { for (k = 0; k < nocc; k++, n++) { w[idx[n]] += cache[n]; v[idx[n]] +=(vv_op[i*nmo+j] * t1Thalf[c*nocc+k] + pt2T[i*nocc+j] * fvohalf[c*nocc+k]); } } } } static double MPICCcontract6(int nocc, int nvir, int a, int b, int c, double *mo_energy, double *t1T, double *fvo, int *slices, double **data_ptrs, double *cache1, int *permute_idx) { const int a0 = slices[0]; const int a1 = slices[1]; const int b0 = slices[2]; const int b1 = slices[3]; const int c0 = slices[4]; const int c1 = slices[5]; const int da = a1 - a0; const int db = b1 - b0; const int dc = c1 - c0; const int nooo = nocc * nocc * nocc; const int nmo = nocc + nvir; const size_t nop = nocc * nmo; int *idx0 = permute_idx; int *idx1 = idx0 + nooo; int *idx2 = idx1 + nooo; int *idx3 = idx2 + nooo; int *idx4 = idx3 + nooo; int *idx5 = idx4 + nooo; double *vvop_ab = data_ptrs[0] + ((a-a0)*db+b-b0) * nop; double *vvop_ac = data_ptrs[1] + ((a-a0)*dc+c-c0) * nop; double *vvop_ba = data_ptrs[2] + ((b-b0)*da+a-a0) * nop; double *vvop_bc = data_ptrs[3] + ((b-b0)*dc+c-c0) * nop; double *vvop_ca = data_ptrs[4] + ((c-c0)*da+a-a0) * nop; double *vvop_cb = data_ptrs[5] + ((c-c0)*db+b-b0) * nop; double *vooo_a = data_ptrs[6]; double *vooo_b = data_ptrs[7]; double *vooo_c = data_ptrs[8]; double *t2T_a = data_ptrs[9 ]; double *t2T_b = data_ptrs[10]; double *t2T_c = data_ptrs[11]; double *v0 = cache1; double *w0 = v0 + nooo; double *z0 = w0 + nooo; double *wtmp = z0; int i; for (i = 0; i < nooo; i++) { w0[i] = 0; v0[i] = 0; } MPICCget_wv(w0, v0, wtmp, fvo, vooo_a, vvop_ab, t1T, t2T_a, t2T_c, nocc, nvir, a, b, c, a0, b0, c0, idx0); MPICCget_wv(w0, v0, wtmp, fvo, vooo_a, vvop_ac, t1T, t2T_a, t2T_b, nocc, nvir, a, c, b, a0, c0, b0, idx1); MPICCget_wv(w0, v0, wtmp, fvo, vooo_b, vvop_ba, t1T, t2T_b, t2T_c, nocc, nvir, b, a, c, b0, a0, c0, idx2); MPICCget_wv(w0, v0, wtmp, fvo, vooo_b, vvop_bc, t1T, t2T_b, t2T_a, nocc, nvir, b, c, a, b0, c0, a0, idx3); MPICCget_wv(w0, v0, wtmp, fvo, vooo_c, vvop_ca, t1T, t2T_c, t2T_b, nocc, nvir, c, a, b, c0, a0, b0, idx4); MPICCget_wv(w0, v0, wtmp, fvo, vooo_c, vvop_cb, t1T, t2T_c, t2T_a, nocc, nvir, c, b, a, c0, b0, a0, idx5); add_and_permute(z0, w0, v0, nocc); double et; if (a == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1./6); } else if (a == b || b == c) { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, .5); } else { et = _ccsd_t_get_energy(w0, z0, mo_energy, nocc, a, b, c, 1.); } return et; } size_t _MPICCsd_t_gen_jobs(CacheJob *jobs, int nocc, int nvir, int *slices, double **data_ptrs) { const int a0 = slices[0]; const int a1 = slices[1]; const int b0 = slices[2]; const int b1 = slices[3]; const int c0 = slices[4]; const int c1 = slices[5]; size_t m, a, b, c; m = 0; for (a = a0; a < a1; a++) { for (b = b0; b < MIN(b1, a+1); b++) { for (c = c0; c < MIN(c1, b+1); c++, m++) { jobs[m].a = a; jobs[m].b = b; jobs[m].c = c; } } } return m; } void MPICCsd_t_contract(double *e_tot, double *mo_energy, double *t1T, double *fvo, int nocc, int nvir, int *slices, double **data_ptrs) { const int a0 = slices[0]; const int a1 = slices[1]; const int b0 = slices[2]; const int b1 = slices[3]; const int c0 = slices[4]; const int c1 = slices[5]; int da = a1 - a0; int db = b1 - b0; int dc = c1 - c0; CacheJob *jobs = malloc(sizeof(CacheJob) * da*db*dc); size_t njobs = _MPICCsd_t_gen_jobs(jobs, nocc, nvir, slices, data_ptrs); int *permute_idx = malloc(sizeof(int) * nocc*nocc*nocc * 6); _make_permute_indices(permute_idx, nocc); #pragma omp parallel default(none) \ shared(njobs, nocc, nvir, mo_energy, t1T, fvo, jobs, e_tot, slices, \ data_ptrs, permute_idx) { int a, b, c; size_t k; double *cache1 = malloc(sizeof(double) * (nocc*nocc*nocc*3+2)); double *t1Thalf = malloc(sizeof(double) * nvir*nocc * 2); double *fvohalf = t1Thalf + nvir*nocc; for (k = 0; k < nvir*nocc; k++) { t1Thalf[k] = t1T[k] * .5; fvohalf[k] = fvo[k] * .5; } double e = 0; #pragma omp for schedule (dynamic, 4) for (k = 0; k < njobs; k++) { a = jobs[k].a; b = jobs[k].b; c = jobs[k].c; e += MPICCcontract6(nocc, nvir, a, b, c, mo_energy, t1Thalf, fvohalf, slices, data_ptrs, cache1, permute_idx); } free(t1Thalf); free(cache1); #pragma omp critical *e_tot += e; } free(permute_idx); }
GB_binop__iseq_fc32.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__iseq_fc32 // A.*B function (eWiseMult): GB_AemultB__iseq_fc32 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__iseq_fc32 // C+=b function (dense accum): GB_Cdense_accumb__iseq_fc32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__iseq_fc32 // C=scalar+B GB_bind1st__iseq_fc32 // C=scalar+B' GB_bind1st_tran__iseq_fc32 // C=A+scalar GB_bind2nd__iseq_fc32 // C=A'+scalar GB_bind2nd_tran__iseq_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // B,b type: GxB_FC32_t // BinaryOp: cij = GB_FC32_iseq (aij, bij) #define GB_ATYPE \ GxB_FC32_t #define GB_BTYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_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) \ GxB_FC32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC32_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) \ z = GB_FC32_iseq (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_ISEQ || GxB_NO_FC32 || GxB_NO_ISEQ_FC32) //------------------------------------------------------------------------------ // 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__iseq_fc32 ( 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_fc32 ( 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__iseq_fc32 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC32_t GxB_FC32_t bwork = (*((GxB_FC32_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 GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_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 GxB_FC32_t *GB_RESTRICT Cx = (GxB_FC32_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__iseq_fc32 ( 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__iseq_fc32 ( 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__iseq_fc32 ( 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 GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t x = (*((GxB_FC32_t *) x_input)) ; GxB_FC32_t *Bx = (GxB_FC32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t bij = Bx [p] ; Cx [p] = GB_FC32_iseq (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_fc32 ( 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 ; GxB_FC32_t *Cx = (GxB_FC32_t *) Cx_output ; GxB_FC32_t *Ax = (GxB_FC32_t *) Ax_input ; GxB_FC32_t y = (*((GxB_FC32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; Cx [p] = GB_FC32_iseq (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) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_iseq (x, aij) ; \ } GrB_Info GB_bind1st_tran__iseq_fc32 ( 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 \ GxB_FC32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC32_t x = (*((const GxB_FC32_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC32_t } //------------------------------------------------------------------------------ // 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) \ { \ GxB_FC32_t aij = Ax [pA] ; \ Cx [pC] = GB_FC32_iseq (aij, y) ; \ } GrB_Info GB_bind2nd_tran__iseq_fc32 ( 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 GxB_FC32_t y = (*((const GxB_FC32_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
elemwise_binary_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. */ /*! * Copyright (c) 2016 by Contributors * \file elemwise_binary_op.h * \brief Function definition of elementwise binary operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #include <mxnet/operator_util.h> #include <mxnet/op_attr_types.h> #include <vector> #include <string> #include <utility> #include <typeinfo> #include <algorithm> #include "../mxnet_op.h" #include "../mshadow_op.h" #include "../../engine/openmp.h" #include "elemwise_unary_op.h" #include "../../common/utils.h" #include "./init_op.h" #include "../operator_common.h" namespace mxnet { namespace op { /*! Gather binary operator functions into ElemwiseBinaryOp class */ class ElemwiseBinaryOp : public OpBase { public: /*! \brief For sparse, assume missing rvalue is 0 */ template<typename OP, int Req> struct MissingRValueOp { typedef OP Operation; template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(lhs[i], DType(0))); } }; /*! \brief For sparse, assume missing lvalue is 0 */ template<typename OP, int Req> struct MissingLValueOp { typedef OP Operation; template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *rhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(DType(0), rhs[i])); } }; private: /*! * \brief CSR operation requires temp space */ enum ResourceRequestType { kTempSpace }; /*! * \brief Fill contiguous dense output rows with value computed from 0 lhs and 0 rhs input * CPU-Only version */ template<typename DType, typename OP, typename xpu> static inline size_t FillDense(mshadow::Stream<xpu> *s, const size_t idx_l, const size_t idx_r, const OpReqType req, mshadow::Tensor<xpu, 2, DType> *out, const size_t iter_out) { const int index_out_min = static_cast<int>(std::min(idx_l, idx_r)); if (static_cast<size_t>(index_out_min) > iter_out) { const DType zero_input_val = OP::Map(DType(0), DType(0)); #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (int i = static_cast<int>(iter_out); i < index_out_min; ++i) { Fill<false>(s, (*out)[i], req, zero_input_val); } } return static_cast<size_t>(index_out_min); // MSVC wants OMP loops to always use 'int' } static inline bool IsSameArray(const NDArray& a1, const NDArray& a2) { return a1.var() == a2.var(); } public: /*! \brief Minimum of three */ static MSHADOW_XINLINE size_t minthree(const size_t a, const size_t b, const size_t c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } private: template<typename LOP, typename ROP> static void BackwardUseNone_(const nnvm::NodeAttrs &attrs, mshadow::Stream<cpu>* s, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { using namespace mxnet_op; const int size = static_cast<int>((outputs[0].Size() + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes); const DType *ograd_dptr = inputs[0].dptr<DType>(); if (std::is_same<LOP, mshadow_op::identity>::value && req[0] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[0].dptr<DType>()); } else if (req[0] != kNullOp) { DType *lgrad_dptr = outputs[0].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { Kernel<mxnet_op::op_with_req<LOP, Req>, cpu>::Launch(s, size, lgrad_dptr, ograd_dptr); }); } if (std::is_same<ROP, mshadow_op::identity>::value && req[1] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[1].dptr<DType>()); } else if (req[1] != kNullOp) { DType *rgrad_dptr = outputs[1].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { Kernel<mxnet_op::op_with_req<ROP, Req>, cpu>::Launch(s, size, rgrad_dptr, ograd_dptr); }); } }); } template<typename LOP, typename ROP> static void BackwardUseIn_(const nnvm::NodeAttrs &attrs, mshadow::Stream<cpu>* s, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DCHECK_EQ(outputs.size(), 2U); DCHECK_EQ(inputs.size(), 3U); const DType *ograd_dptr = inputs[0].dptr<DType>(); const DType *lhs_dptr = inputs[1].dptr<DType>(); const DType *rhs_dptr = inputs[2].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { const int size = static_cast<int>( (outputs[0].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * lgrad_dptr = outputs[0].dptr<DType>(); mxnet_op::Kernel< mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<LOP>, Req>, cpu>::Launch( s, size, lgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr); }); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { const int size = static_cast<int>( (outputs[1].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * rgrad_dptr = outputs[1].dptr<DType>(); mxnet_op::Kernel< mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<ROP>, Req>, cpu>::Launch( s, size, rgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr); }); }); } template< typename xpu, typename LOP, typename ROP, bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false, typename BackupCompute> static inline void RspRspOpBackward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs, BackupCompute backup_compute) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); // lhs grad if (req[0] != kNullOp) { // RspRspOp can handle dense outputs so long as OP(0, 0) == 0 RspRspOp<LOP>( s, attrs, ctx, inputs[1], inputs[2], req[0], outputs[0], false, false, false, false); // lhs in-place RspRspOp<op::mshadow_op::mul>( s, attrs, ctx, outputs[0], inputs[0], req[0], outputs[0], false, false, true, false); } // rhs grad if (req[1] != kNullOp) { RspRspOp<ROP>( s, attrs, ctx, inputs[1], inputs[2], req[1], outputs[1], false, false, false, false); // rhs in-place RspRspOp<op::mshadow_op::mul>( s, attrs, ctx, inputs[0], outputs[1], req[1], outputs[1], false, false, true, false); } } template<typename xpu, typename LOP, typename ROP> static inline void DnsCsrCsrOpBackward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { const bool supported_ops = std::is_same<mshadow_op::right, LOP>::value && std::is_same<mshadow_op::left, ROP>::value; CHECK(supported_ops) << "Only backward for mul is supported (LOP should be right, ROP should be left)"; const NDArray& out_grad = inputs[0]; const NDArray& lhs_in = inputs[1]; const NDArray& rhs_in = inputs[2]; const NDArray& lhs_grad = outputs[0]; const NDArray& rhs_grad = outputs[1]; const bool reverse = (outputs[0].storage_type() == kCSRStorage); if (reverse) { DnsCsrCsrOp<xpu, mshadow_op::mul>(attrs, ctx, out_grad, rhs_in, req[0], lhs_grad, false); Compute<xpu, mshadow_op::mul>(attrs, ctx, {out_grad.data(), lhs_in.data()}, {req[1]}, {rhs_grad.data()}); } else { DnsCsrCsrOp<xpu, mshadow_op::mul>(attrs, ctx, out_grad, lhs_in, req[1], rhs_grad, false); Compute<xpu, mshadow_op::mul>(attrs, ctx, {out_grad.data(), rhs_in.data()}, {req[0]}, {lhs_grad.data()}); } } public: /*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */ template<typename OP> static void RspRspOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, bool lhs_may_be_dense, bool rhs_may_be_dense, bool allow_inplace, bool scatter); /*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */ template<typename OP> static void RspRspOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, bool lhs_may_be_dense, bool rhs_may_be_dense, bool allow_inplace, bool scatter); /*! \brief CSR -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void CsrCsrOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output); /*! \brief CSR -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void CsrCsrOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void DnsCsrDnsOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void DnsCsrDnsOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename xpu, typename OP> static void DnsCsrCsrOp(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- RSP binary operator for non-canonical NDArray */ template<typename xpu, typename OP> static void DnsRspDnsOp(mshadow::Stream<xpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); public: /*! * \brief Rsp-op-Rsp operation which produces a dense result * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool SparseSparseWithDenseResult(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs); /*! * \brief Allow one of the binary inputs to be dense and still produce a sparse output. * Typically used for sparse * dense = sparse. * Note: for csr, it dispatches to fallback other than csr, csr -> csr * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool PreferSparseStorageType(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { using namespace common; CHECK_EQ(in_attrs->size(), 2U) << " in operator " << attrs.name; CHECK_EQ(out_attrs->size(), 1U) << " in operator " << attrs.name; const auto& lhs_stype = in_attrs->at(0); const auto& rhs_stype = in_attrs->at(1); auto& out_stype = out_attrs->at(0); bool dispatched = false; const bool invalid_ctx = dev_mask != mshadow::cpu::kDevMask; const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback : DispatchMode::kFComputeEx; if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) { // dns, dns -> dns dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } if (!dispatched && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) { // rsp, rsp -> rsp dispatched = storage_type_assign(&out_stype, kRowSparseStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ContainsOnlyStorage(*in_attrs, kCSRStorage)) { // csr, csr -> csr dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage))) { // rsp, dns -> rsp // dns, rsp -> rsp dispatched = storage_type_assign(&out_stype, kRowSparseStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage))) { // csr, dns -> csr // dns, csr -> csr dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched) { dispatched = dispatch_fallback(out_attrs, dispatch_mode); } return dispatched; } /*! * \brief Allow one of the inputs to be dense and produce a dense output, * for rsp inputs only support when both inputs are rsp type. * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ template<bool cpu_only, bool rsp, bool csr> static bool PreferDenseStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { using namespace common; CHECK_EQ(in_attrs->size(), 2); CHECK_EQ(out_attrs->size(), 1); const auto lhs_stype = (*in_attrs)[0]; const auto rhs_stype = (*in_attrs)[1]; bool dispatched = false; const bool invalid_ctx = cpu_only && dev_mask != mshadow::cpu::kDevMask; const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback : DispatchMode::kFComputeEx; if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) { // dns, dns ... -> dns dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } if (!dispatched && rsp && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) { // rsp, rsp, ... -> rsp dispatched = storage_type_assign(out_attrs, kRowSparseStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched && csr && ContainsOnlyStorage(*in_attrs, kCSRStorage)) { // csr, csr, ... -> csr dispatched = storage_type_assign(out_attrs, kCSRStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage) || (lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage))) { // dense, csr -> dense / csr, dense -> dense dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage) || (lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage))) { // dense, rsp -> dense / rsp, dense -> dense dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched) { dispatch_fallback(out_attrs, dispatch_mode); } return true; } /*! * \brief Backward pass computing input gradient using forward inputs * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool BackwardUseInStorageType(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs); template<typename xpu, typename OP> static void ComputeInt(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } 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) { using namespace mxnet_op; if (req[0] == kNullOp) return; mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); if (outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "Operator " << attrs.op->name << " does not support boolean type"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void ComputeWithBool(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void ComputeLogic(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<bool>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } 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) { using namespace common; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] == kNullOp) return; const auto lhs_stype = inputs[0].storage_type(); const auto rhs_stype = inputs[1].storage_type(); const auto out_stype = outputs[0].storage_type(); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); if ((ContainsOnlyStorage(inputs, kRowSparseStorage)) && (out_stype == kRowSparseStorage || out_stype == kDefaultStorage)) { // rsp, rsp -> rsp // rsp, rsp -> dns RspRspOp<OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], false, false, false, false); } else if (ContainsOnlyStorage(inputs, kCSRStorage) && out_stype == kCSRStorage) { // csr, csr -> csr CsrCsrOp<OP>(s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0]); } else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) && out_stype == kDefaultStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kCSRStorage); DnsCsrDnsOp<OP>(s, attrs, ctx, dns, csr, req[0], outputs[0], reverse); } else if (((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) && out_stype == kDefaultStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kRowSparseStorage); const NDArray& rsp = (reverse)? inputs[0] : inputs[1]; DnsRspDnsOp<xpu, OP>(s, attrs, ctx, dns, rsp, req[0], outputs[0], reverse); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } /*! \brief ComputeEx allowing dense lvalue and/or rvalue */ template<typename xpu, typename OP, bool lhs_may_be_dense, bool rhs_may_be_dense> static void ComputeDnsLRValueEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] == kNullOp) return; const auto lhs_stype = inputs[0].storage_type(); const auto rhs_stype = inputs[1].storage_type(); const auto out_stype = outputs[0].storage_type(); if ((out_stype == kRowSparseStorage || out_stype == kDefaultStorage) && ((lhs_stype == kRowSparseStorage && rhs_stype == kRowSparseStorage) || (lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) && lhs_may_be_dense && rhs_may_be_dense) { // rsp, rsp -> rsp // rsp, rsp -> dns // rsp, dns -> rsp // dns, rsp -> rsp // More than once dense not allowed (this will be checked in RspRspOp): // rsp, dns -> dns <-- NOT ALLOWED // dns, rsp -> dns <-- NOT ALLOWED mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); RspRspOp<OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], lhs_may_be_dense, rhs_may_be_dense, false, false); } else if (lhs_stype == kCSRStorage && rhs_stype == kCSRStorage) { ComputeEx<xpu, OP>(attrs, ctx, inputs, req, outputs); } else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) && out_stype == kCSRStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kCSRStorage); DnsCsrCsrOp<xpu, OP>(attrs, ctx, dns, csr, req[0], outputs[0], reverse); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNone(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); BackwardUseNone_<LOP, ROP>(attrs, s, inputs, req, outputs); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNoneEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { CHECK_EQ(inputs.size(), 1U); // output grad CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad const auto in_stype = inputs[0].storage_type(); const auto lhs_stype = outputs[0].storage_type(); const auto rhs_stype = outputs[1].storage_type(); // lhs grad if (req[0] != kNullOp) { if (in_stype == lhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { CHECK_EQ(outputs[0].storage_type(), in_stype); // rsp -> rsp, _. op requires 0-input returns 0-output DCHECK_LT(std::fabs(static_cast<float>(LOP::Map(0))), 1e-5f); UnaryOp::ComputeEx<xpu, LOP>(attrs, ctx, inputs, req, {outputs[0]}); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } // rhs grad if (req[1] != kNullOp) { if (in_stype == rhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { CHECK_EQ(outputs[0].storage_type(), in_stype); // rsp -> _, rsp. op requires 0-input returns 0-output DCHECK_LT(std::fabs(static_cast<float>(ROP::Map(0))), 1e-5f); UnaryOp::ComputeEx<xpu, ROP>(attrs, ctx, inputs, req, {outputs[1]}); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseIn(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); BackwardUseIn_<LOP, ROP>(attrs, s, inputs, req, outputs); } template< typename xpu, typename LOP, typename ROP, bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false> static inline void BackwardUseInEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace common; CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad const auto out_grad_stype = inputs[0].storage_type(); const auto lhs_grad_stype = outputs[0].storage_type(); const auto rhs_grad_stype = outputs[1].storage_type(); if (ContainsOnlyStorage(inputs, kRowSparseStorage) && (lhs_grad_stype == kDefaultStorage || lhs_grad_stype == kRowSparseStorage) && (rhs_grad_stype == kDefaultStorage || rhs_grad_stype == kRowSparseStorage)) { // rsp, rsp, rsp -> [dns, rsp], [dns, rsp] RspRspOpBackward<xpu, LOP, ROP, in0_ok_dense, in1_ok_dense, in2_ok_dense>( attrs, ctx, inputs, req, outputs, BackwardUseIn<xpu, LOP, ROP>); } if (((lhs_grad_stype == kDefaultStorage && rhs_grad_stype == kCSRStorage) || (lhs_grad_stype == kCSRStorage && rhs_grad_stype == kDefaultStorage)) && out_grad_stype == kDefaultStorage) { // dns, csr, dns -> [csr, dns] / csr, dns, dns -> [dns, csr] DnsCsrCsrOpBackward<xpu, LOP, ROP>(attrs, ctx, inputs, req, outputs); } } }; // class ElemwiseBinaryOp /*! \brief Binary launch */ #define MXNET_OPERATOR_REGISTER_BINARY(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(2) \ .set_num_outputs(1) \ .set_attr<nnvm::FListInputNames>("FListInputNames", \ [](const NodeAttrs& attrs) { \ return std::vector<std::string>{"lhs", "rhs"}; \ }) \ .set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<2, 1>) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>) \ .set_attr<mxnet::alm::FChangeLayout>("FChangeLayout", ElemwiseChangeLayout) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; \ }) \ .add_argument("lhs", "NDArray-or-Symbol", "first input") \ .add_argument("rhs", "NDArray-or-Symbol", "second input") /*! \brief Binary launch, with FComputeEx for csr and rsp available */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseStorageType<2, 1, true, true, true>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) /*! \brief Binary launch, with FComputeEx for csr and rsp available. when inputs contain both sparse and dense, sparse output is preferred. */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PS(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::PreferSparseStorageType) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) /*! \brief Binary launch, dense result * FInferStorageType attr is not set using this macro. * By default DefaultStorageType is used. */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::SparseSparseWithDenseResult) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) /*! \brief Binary launch, with FComputeEx for prefer dense */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PD(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::PreferDenseStorageType<true, true, true>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) #if MXNET_USE_CUDA struct ElemwiseBinaryRTCCompute { std::string OP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct ElemwiseBinaryRTCBwdUseNone { std::string LOP; std::string ROP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct ElemwiseBinaryRTCBwdUseIn { std::string LOP; std::string ROP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; #endif } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
dlascl.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @generated from /home/luszczek/workspace/plasma/bitbucket/plasma/compute/zlascl.c, normal z -> d, Fri Sep 28 17:38:08 2018 * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include <math.h> /******************************************************************************/ int plasma_dlascl(plasma_enum_t uplo, double cfrom, double cto, int m, int n, double *pA, int lda) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((uplo != PlasmaGeneral) && (uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); return -1; } if (cfrom == 0.0 || isnan(cfrom)) { plasma_error("illegal value of cfrom"); return -2; } if (isnan(cto)) { plasma_error("illegal value of cto"); return -3; } if (m < 0) { plasma_error("illegal value of m"); return -4; } if (n < 0) { plasma_error("illegal value of n"); return -5; } if (lda < imax(1, m)) { plasma_error("illegal value of lda"); return -7; } // quick return if (imin(n, m) == 0) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_lascl(plasma, PlasmaRealDouble, m, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; int retval; retval = plasma_desc_general_create(PlasmaRealDouble, nb, nb, m, n, 0, 0, m, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_general_desc_create() failed"); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_dge2desc(pA, lda, A, &sequence, &request); // Call tile async function. plasma_omp_dlascl(uplo, cfrom, cto, A, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_ddesc2ge(A, pA, lda, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); // Return status. int status = sequence.status; return status; } /******************************************************************************/ void plasma_omp_dlascl(plasma_enum_t uplo, double cfrom, double cto, plasma_desc_t A, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((uplo != PlasmaGeneral) && (uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (cfrom == 0.0 || isnan(cfrom)) { plasma_error("illegal value of cfrom"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (isnan(cto)) { plasma_error("illegal value of cto"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_error("invalid A"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (imin(A.m, A.n) == 0) return; // Call the parallel function. plasma_pdlascl(uplo, cfrom, cto, A, sequence, request); }
matrix_low_level.h
/*************************************************************************** * include/stxxl/bits/containers/matrix_low_level.h * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2010-2011 Raoul Steffen <R-Steffen@gmx.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #ifndef STXXL_CONTAINERS_MATRIX_LOW_LEVEL_HEADER #define STXXL_CONTAINERS_MATRIX_LOW_LEVEL_HEADER #ifndef STXXL_BLAS #define STXXL_BLAS 0 #endif #include <complex> #include <stxxl/bits/common/types.h> #include <stxxl/bits/parallel.h> STXXL_BEGIN_NAMESPACE //! \addtogroup matrix //! \{ namespace matrix_local { // forward declaration template <typename ValueType, unsigned BlockSideLength> struct matrix_operations; // generic declaration template <unsigned BlockSideLength, bool transposed> struct switch_major_index; // row-major specialization template <unsigned BlockSideLength> struct switch_major_index<BlockSideLength, false> { inline switch_major_index(const int_type row, const int_type col) : i(row * BlockSideLength + col) { } inline operator int_type& () { return i; } private: int_type i; }; //column-major specialization template <unsigned BlockSideLength> struct switch_major_index<BlockSideLength, true> { inline switch_major_index(const int_type row, const int_type col) : i(row + col * BlockSideLength) { } inline operator int_type& () { return i; } private: int_type i; }; //! c = a [op] b; for arbitrary entries template <typename ValueType, unsigned BlockSideLength, bool a_transposed, bool b_transposed, class Op> struct low_level_matrix_binary_ass_op { low_level_matrix_binary_ass_op(ValueType* c, const ValueType* a, const ValueType* b, Op op = Op()) { if (a) if (b) #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type row = 0; row < int_type(BlockSideLength); ++row) for (int_type col = 0; col < int_type(BlockSideLength); ++col) op(c[switch_major_index < BlockSideLength, false > (row, col)], a[switch_major_index < BlockSideLength, a_transposed > (row, col)], b[switch_major_index < BlockSideLength, b_transposed > (row, col)]); else #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type row = 0; row < int_type(BlockSideLength); ++row) for (int_type col = 0; col < int_type(BlockSideLength); ++col) op(c[switch_major_index < BlockSideLength, false > (row, col)], a[switch_major_index < BlockSideLength, a_transposed > (row, col)], 0); else { assert(b /* do not add nothing to nothing */); #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type row = 0; row < int_type(BlockSideLength); ++row) for (int_type col = 0; col < int_type(BlockSideLength); ++col) op(c[switch_major_index < BlockSideLength, false > (row, col)], 0, b[switch_major_index < BlockSideLength, b_transposed > (row, col)]); } } }; //! c [op]= a; for arbitrary entries template <typename ValueType, unsigned BlockSideLength, bool a_transposed, class Op> struct low_level_matrix_unary_ass_op { low_level_matrix_unary_ass_op(ValueType* c, const ValueType* a, Op op = Op()) { if (a) #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type row = 0; row < int_type(BlockSideLength); ++row) for (int_type col = 0; col < int_type(BlockSideLength); ++col) op(c[switch_major_index < BlockSideLength, false > (row, col)], a[switch_major_index < BlockSideLength, a_transposed > (row, col)]); } }; //! c =[op] a; for arbitrary entries template <typename ValueType, unsigned BlockSideLength, bool a_transposed, class Op> struct low_level_matrix_unary_op { low_level_matrix_unary_op(ValueType* c, const ValueType* a, Op op = Op()) { assert(a); #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type row = 0; row < int_type(BlockSideLength); ++row) for (int_type col = 0; col < int_type(BlockSideLength); ++col) c[switch_major_index < BlockSideLength, false > (row, col)] = op(a[switch_major_index < BlockSideLength, a_transposed > (row, col)]); } }; //! multiplies matrices A and B, adds result to C, for arbitrary entries //! param pointer to blocks of A,B,C; elements in blocks have to be in row-major /* designated usage as: * void * low_level_matrix_multiply_and_add(const double * a, bool a_in_col_major, const double * b, bool b_in_col_major, double * c, const bool c_in_col_major) */ template <typename ValueType, unsigned BlockSideLength> struct low_level_matrix_multiply_and_add { low_level_matrix_multiply_and_add(const ValueType* a, bool a_in_col_major, const ValueType* b, bool b_in_col_major, ValueType* c, const bool c_in_col_major) { if (c_in_col_major) { std::swap(a, b); bool a_cm = ! b_in_col_major; b_in_col_major = ! a_in_col_major; a_in_col_major = a_cm; } if (! a_in_col_major) { if (! b_in_col_major) { // => both row-major #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type i = 0; i < int_type(BlockSideLength); ++i) //OpenMP does not like unsigned iteration variables for (unsigned_type k = 0; k < BlockSideLength; ++k) for (unsigned_type j = 0; j < BlockSideLength; ++j) c[i * BlockSideLength + j] += a[i * BlockSideLength + k] * b[k * BlockSideLength + j]; } else { // => a row-major, b col-major #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type i = 0; i < int_type(BlockSideLength); ++i) //OpenMP does not like unsigned iteration variables for (unsigned_type j = 0; j < BlockSideLength; ++j) for (unsigned_type k = 0; k < BlockSideLength; ++k) c[i * BlockSideLength + j] += a[i * BlockSideLength + k] * b[k + j * BlockSideLength]; } } else { if (! b_in_col_major) { // => a col-major, b row-major #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type i = 0; i < int_type(BlockSideLength); ++i) //OpenMP does not like unsigned iteration variables for (unsigned_type k = 0; k < BlockSideLength; ++k) for (unsigned_type j = 0; j < BlockSideLength; ++j) c[i * BlockSideLength + j] += a[i + k * BlockSideLength] * b[k * BlockSideLength + j]; } else { // => both col-major #if STXXL_PARALLEL #pragma omp parallel for #endif for (int_type i = 0; i < int_type(BlockSideLength); ++i) //OpenMP does not like unsigned iteration variables for (unsigned_type k = 0; k < BlockSideLength; ++k) for (unsigned_type j = 0; j < BlockSideLength; ++j) c[i * BlockSideLength + j] += a[i + k * BlockSideLength] * b[k + j * BlockSideLength]; } } } }; #if STXXL_BLAS typedef int_type blas_int; typedef std::complex<double> blas_double_complex; typedef std::complex<float> blas_single_complex; // --- vector add (used as matrix-add) ----------------- extern "C" void daxpy_(const blas_int* n, const double* alpha, const double* x, const blas_int* incx, double* y, const blas_int* incy); extern "C" void saxpy_(const blas_int* n, const float* alpha, const float* x, const blas_int* incx, float* y, const blas_int* incy); extern "C" void zaxpy_(const blas_int* n, const blas_double_complex* alpha, const blas_double_complex* x, const blas_int* incx, blas_double_complex* y, const blas_int* incy); extern "C" void caxpy_(const blas_int* n, const blas_single_complex* alpha, const blas_single_complex* x, const blas_int* incx, blas_single_complex* y, const blas_int* incy); extern "C" void dcopy_(const blas_int* n, const double* x, const blas_int* incx, double* y, const blas_int* incy); extern "C" void scopy_(const blas_int* n, const float* x, const blas_int* incx, float* y, const blas_int* incy); extern "C" void zcopy_(const blas_int* n, const blas_double_complex* x, const blas_int* incx, blas_double_complex* y, const blas_int* incy); extern "C" void ccopy_(const blas_int* n, const blas_single_complex* x, const blas_int* incx, blas_single_complex* y, const blas_int* incy); //! c = a + b; for double entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<double, BlockSideLength, false, false, typename matrix_operations<double, BlockSideLength>::addition> { low_level_matrix_binary_ass_op(double* c, const double* a, const double* b, typename matrix_operations<double, BlockSideLength>::addition = typename matrix_operations<double, BlockSideLength>::addition()) { if (a) if (b) { low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, b); } else low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, b); } } }; //! c = a - b; for double entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<double, BlockSideLength, false, false, typename matrix_operations<double, BlockSideLength>::subtraction> { low_level_matrix_binary_ass_op(double* c, const double* a, const double* b, typename matrix_operations<double, BlockSideLength>::subtraction = typename matrix_operations<double, BlockSideLength>::subtraction()) { if (a) if (b) { low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::subtraction> (c, b); } else low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::subtraction> (c, b); } } }; //! c += a; for double entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> { low_level_matrix_unary_ass_op(double* c, const double* a, typename matrix_operations<double, BlockSideLength>::addition = typename matrix_operations<double, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const double one = 1.0; if (a) daxpy_(&size, &one, a, &int_one, c, &int_one); } }; //! c -= a; for double entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::subtraction> { low_level_matrix_unary_ass_op(double* c, const double* a, typename matrix_operations<double, BlockSideLength>::subtraction = typename matrix_operations<double, BlockSideLength>::subtraction()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const double minusone = -1.0; if (a) daxpy_(&size, &minusone, a, &int_one, c, &int_one); } }; //! c = a; for double entries template <unsigned BlockSideLength> struct low_level_matrix_unary_op<double, BlockSideLength, false, typename matrix_operations<double, BlockSideLength>::addition> { low_level_matrix_unary_op(double* c, const double* a, typename matrix_operations<double, BlockSideLength>::addition = typename matrix_operations<double, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; dcopy_(&size, a, &int_one, c, &int_one); } }; //! c = a + b; for float entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<float, BlockSideLength, false, false, typename matrix_operations<float, BlockSideLength>::addition> { low_level_matrix_binary_ass_op(float* c, const float* a, const float* b, typename matrix_operations<float, BlockSideLength>::addition = typename matrix_operations<float, BlockSideLength>::addition()) { if (a) if (b) { low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, b); } else low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, b); } } }; //! c = a - b; for float entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<float, BlockSideLength, false, false, typename matrix_operations<float, BlockSideLength>::subtraction> { low_level_matrix_binary_ass_op(float* c, const float* a, const float* b, typename matrix_operations<float, BlockSideLength>::subtraction = typename matrix_operations<float, BlockSideLength>::subtraction()) { if (a) if (b) { low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::subtraction> (c, b); } else low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::subtraction> (c, b); } } }; //! c += a; for float entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> { low_level_matrix_unary_ass_op(float* c, const float* a, typename matrix_operations<float, BlockSideLength>::addition = typename matrix_operations<float, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const float one = 1.0; if (a) saxpy_(&size, &one, a, &int_one, c, &int_one); } }; //! c -= a; for float entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::subtraction> { low_level_matrix_unary_ass_op(float* c, const float* a, typename matrix_operations<float, BlockSideLength>::subtraction = typename matrix_operations<float, BlockSideLength>::subtraction()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const float minusone = -1.0; if (a) saxpy_(&size, &minusone, a, &int_one, c, &int_one); } }; //! c = a; for float entries template <unsigned BlockSideLength> struct low_level_matrix_unary_op<float, BlockSideLength, false, typename matrix_operations<float, BlockSideLength>::addition> { low_level_matrix_unary_op(float* c, const float* a, typename matrix_operations<float, BlockSideLength>::addition = typename matrix_operations<float, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; scopy_(&size, a, &int_one, c, &int_one); } }; //! c = a + b; for blas_double_complex entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<blas_double_complex, BlockSideLength, false, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> { low_level_matrix_binary_ass_op(blas_double_complex* c, const blas_double_complex* a, const blas_double_complex* b, typename matrix_operations<blas_double_complex, BlockSideLength>::addition = typename matrix_operations<blas_double_complex, BlockSideLength>::addition()) { if (a) if (b) { low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, b); } else low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, b); } } }; //! c = a - b; for blas_double_complex entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<blas_double_complex, BlockSideLength, false, false, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction> { low_level_matrix_binary_ass_op(blas_double_complex* c, const blas_double_complex* a, const blas_double_complex* b, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction = typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction()) { if (a) if (b) { low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction> (c, b); } else low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction> (c, b); } } }; //! c += a; for blas_double_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> { low_level_matrix_unary_ass_op(blas_double_complex* c, const blas_double_complex* a, typename matrix_operations<blas_double_complex, BlockSideLength>::addition = typename matrix_operations<blas_double_complex, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const blas_double_complex one = 1.0; if (a) zaxpy_(&size, &one, a, &int_one, c, &int_one); } }; //! c -= a; for blas_double_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction> { low_level_matrix_unary_ass_op(blas_double_complex* c, const blas_double_complex* a, typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction = typename matrix_operations<blas_double_complex, BlockSideLength>::subtraction()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const blas_double_complex minusone = -1.0; if (a) zaxpy_(&size, &minusone, a, &int_one, c, &int_one); } }; //! c = a; for blas_double_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_op<blas_double_complex, BlockSideLength, false, typename matrix_operations<blas_double_complex, BlockSideLength>::addition> { low_level_matrix_unary_op(blas_double_complex* c, const blas_double_complex* a, typename matrix_operations<blas_double_complex, BlockSideLength>::addition = typename matrix_operations<blas_double_complex, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; zcopy_(&size, a, &int_one, c, &int_one); } }; //! c = a + b; for blas_single_complex entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<blas_single_complex, BlockSideLength, false, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> { low_level_matrix_binary_ass_op(blas_single_complex* c, const blas_single_complex* a, const blas_single_complex* b, typename matrix_operations<blas_single_complex, BlockSideLength>::addition = typename matrix_operations<blas_single_complex, BlockSideLength>::addition()) { if (a) if (b) { low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, b); } else low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, b); } } }; //! c = a - b; for blas_single_complex entries template <unsigned BlockSideLength> struct low_level_matrix_binary_ass_op<blas_single_complex, BlockSideLength, false, false, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction> { low_level_matrix_binary_ass_op(blas_single_complex* c, const blas_single_complex* a, const blas_single_complex* b, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction = typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction()) { if (a) if (b) { low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, a); low_level_matrix_unary_ass_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction> (c, b); } else low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> (c, a); else { assert(b /* do not add nothing to nothing */); low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction> (c, b); } } }; //! c += a; for blas_single_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> { low_level_matrix_unary_ass_op(blas_single_complex* c, const blas_single_complex* a, typename matrix_operations<blas_single_complex, BlockSideLength>::addition = typename matrix_operations<blas_single_complex, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const blas_single_complex one = 1.0; if (a) caxpy_(&size, &one, a, &int_one, c, &int_one); } }; //! c -= a; for blas_single_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_ass_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction> { low_level_matrix_unary_ass_op(blas_single_complex* c, const blas_single_complex* a, typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction = typename matrix_operations<blas_single_complex, BlockSideLength>::subtraction()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; const blas_single_complex minusone = -1.0; if (a) caxpy_(&size, &minusone, a, &int_one, c, &int_one); } }; //! c = a; for blas_single_complex entries template <unsigned BlockSideLength> struct low_level_matrix_unary_op<blas_single_complex, BlockSideLength, false, typename matrix_operations<blas_single_complex, BlockSideLength>::addition> { low_level_matrix_unary_op(blas_single_complex* c, const blas_single_complex* a, typename matrix_operations<blas_single_complex, BlockSideLength>::addition = typename matrix_operations<blas_single_complex, BlockSideLength>::addition()) { const blas_int size = BlockSideLength * BlockSideLength; const blas_int int_one = 1; ccopy_(&size, a, &int_one, c, &int_one); } }; // --- matrix-matrix multiplication --------------- extern "C" void dgemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const double* alpha, const double* a, const blas_int* lda, const double* b, const blas_int* ldb, const double* beta, double* c, const blas_int* ldc); extern "C" void sgemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const float* alpha, const float* a, const blas_int* lda, const float* b, const blas_int* ldb, const float* beta, float* c, const blas_int* ldc); extern "C" void zgemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const blas_double_complex* alpha, const blas_double_complex* a, const blas_int* lda, const blas_double_complex* b, const blas_int* ldb, const blas_double_complex* beta, blas_double_complex* c, const blas_int* ldc); extern "C" void cgemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const blas_single_complex* alpha, const blas_single_complex* a, const blas_int* lda, const blas_single_complex* b, const blas_int* ldb, const blas_single_complex* beta, blas_single_complex* c, const blas_int* ldc); template <typename ValueType> void gemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const ValueType* alpha, const ValueType* a, const blas_int* lda, const ValueType* b, const blas_int* ldb, const ValueType* beta, ValueType* c, const blas_int* ldc); //! calculates c = alpha * a * b + beta * c //! \tparam ValueType type of elements //! \param n height of a and c //! \param l width of a and height of b //! \param m width of b and c //! \param a_in_col_major if a is stored in column-major rather than row-major //! \param b_in_col_major if b is stored in column-major rather than row-major //! \param c_in_col_major if c is stored in column-major rather than row-major template <typename ValueType> void gemm_wrapper(const blas_int n, const blas_int l, const blas_int m, const ValueType alpha, const bool a_in_col_major, const ValueType* a, const bool b_in_col_major, const ValueType* b, const ValueType beta, const bool c_in_col_major, ValueType* c) { const blas_int& stride_in_a = a_in_col_major ? n : l; const blas_int& stride_in_b = b_in_col_major ? l : m; const blas_int& stride_in_c = c_in_col_major ? n : m; const char transa = a_in_col_major xor c_in_col_major ? 'T' : 'N'; const char transb = b_in_col_major xor c_in_col_major ? 'T' : 'N'; if (c_in_col_major) // blas expects matrices in column-major unless specified via transa rsp. transb gemm_(&transa, &transb, &n, &m, &l, &alpha, a, &stride_in_a, b, &stride_in_b, &beta, c, &stride_in_c); else // blas expects matrices in column-major, so we calculate c^T = alpha * b^T * a^T + beta * c^T gemm_(&transb, &transa, &m, &n, &l, &alpha, b, &stride_in_b, a, &stride_in_a, &beta, c, &stride_in_c); } template <> void gemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const double* alpha, const double* a, const blas_int* lda, const double* b, const blas_int* ldb, const double* beta, double* c, const blas_int* ldc) { dgemm_(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } template <> void gemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const float* alpha, const float* a, const blas_int* lda, const float* b, const blas_int* ldb, const float* beta, float* c, const blas_int* ldc) { sgemm_(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } template <> void gemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const blas_double_complex* alpha, const blas_double_complex* a, const blas_int* lda, const blas_double_complex* b, const blas_int* ldb, const blas_double_complex* beta, blas_double_complex* c, const blas_int* ldc) { zgemm_(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } template <> void gemm_(const char* transa, const char* transb, const blas_int* m, const blas_int* n, const blas_int* k, const blas_single_complex* alpha, const blas_single_complex* a, const blas_int* lda, const blas_single_complex* b, const blas_int* ldb, const blas_single_complex* beta, blas_single_complex* c, const blas_int* ldc) { cgemm_(transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); } //! multiplies matrices A and B, adds result to C, for double entries template <unsigned BlockSideLength> struct low_level_matrix_multiply_and_add<double, BlockSideLength> { low_level_matrix_multiply_and_add(const double* a, bool a_in_col_major, const double* b, bool b_in_col_major, double* c, const bool c_in_col_major) { gemm_wrapper<double>(BlockSideLength, BlockSideLength, BlockSideLength, 1.0, a_in_col_major, a, /**/ b_in_col_major, b, 1.0, c_in_col_major, c); } }; //! multiplies matrices A and B, adds result to C, for float entries template <unsigned BlockSideLength> struct low_level_matrix_multiply_and_add<float, BlockSideLength> { low_level_matrix_multiply_and_add(const float* a, bool a_in_col_major, const float* b, bool b_in_col_major, float* c, const bool c_in_col_major) { gemm_wrapper<float>(BlockSideLength, BlockSideLength, BlockSideLength, 1.0, a_in_col_major, a, /**/ b_in_col_major, b, 1.0, c_in_col_major, c); } }; //! multiplies matrices A and B, adds result to C, for complex<float> entries template <unsigned BlockSideLength> struct low_level_matrix_multiply_and_add<blas_single_complex, BlockSideLength> { low_level_matrix_multiply_and_add(const blas_single_complex* a, bool a_in_col_major, const blas_single_complex* b, bool b_in_col_major, blas_single_complex* c, const bool c_in_col_major) { gemm_wrapper<blas_single_complex>(BlockSideLength, BlockSideLength, BlockSideLength, 1.0, a_in_col_major, a, /**/ b_in_col_major, b, 1.0, c_in_col_major, c); } }; //! multiplies matrices A and B, adds result to C, for complex<double> entries template <unsigned BlockSideLength> struct low_level_matrix_multiply_and_add<blas_double_complex, BlockSideLength> { low_level_matrix_multiply_and_add(const blas_double_complex* a, bool a_in_col_major, const blas_double_complex* b, bool b_in_col_major, blas_double_complex* c, const bool c_in_col_major) { gemm_wrapper<blas_double_complex>(BlockSideLength, BlockSideLength, BlockSideLength, 1.0, a_in_col_major, a, /**/ b_in_col_major, b, 1.0, c_in_col_major, c); } }; #endif } // namespace matrix_local //! \} STXXL_END_NAMESPACE #endif // !STXXL_CONTAINERS_MATRIX_LOW_LEVEL_HEADER
mixed_tentusscher_myo_epi_2004_S1_15.c
// Scenario 1 - Mixed-Model TenTusscher 2004 (Myocardium + Epicardium) // (AP + max:dvdt) #include <stdio.h> #include "mixed_tentusscher_myo_epi_2004_S1_15.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.5947213128563,0.00128280499974890,0.780358835699496,0.780221511728293,0.000174134035873362,0.485365577210685,0.00293476383879643,0.999998356711186,1.92498350501348e-08,1.88440562227888e-05,0.999771869331078,1.00650785537824,0.999977589106241,5.87636528842966e-05,0.588270003699565,9.12980854435061,140.402413298159}; 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.5931143418548,0.000234305879325739,0.000153733035636004,0.000521570747646260,0.278749841477854,0.152665673487231,0.188787297178472,3.91040967347224,0.0200695067032522,2.72218041991663,1099.67975070177,0.000551753358592525,0.133204533378619,0.0132111010630101,0.00494272025642177,6.68557857945522e-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; }
openmp.c
// Copyright 2020 ETH Zurich and University of Bologna. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include "dm.h" #include "encoding.h" #include "eu.h" #include "omp.h" #include "printf.h" #include "snrt.h" #define AXPY_N 64 #define NUMTHREADS 8 // Test output printf #define tprintf(...) printf(__VA_ARGS__) // #define tprintf(...) while (0) // Trace printf for debugging // #define ttprintf(...) printf(__VA_ARGS__) #define ttprintf(...) while (0) volatile static uint32_t sum = 0; unsigned __attribute__((noinline)) static_schedule(void) { static double *data_x, *data_y, data_a; data_x = snrt_l1alloc(sizeof(double) * AXPY_N); data_y = snrt_l1alloc(sizeof(double) * AXPY_N); // Init data data_a = 10.0; for (unsigned i = 0; i < AXPY_N; i++) { data_x[i] = (double)(i); data_y[i] = (double)(i + 1); } // compute #pragma omp parallel firstprivate(data_a, data_x, data_y) { // DM, rep, bound, stride, data __builtin_ssr_setup_1d_r(0, 0, AXPY_N / NUMTHREADS - 1, sizeof(double), &data_x[AXPY_N / 8 * omp_get_thread_num()]); __builtin_ssr_setup_1d_r(1, 0, AXPY_N / NUMTHREADS - 1, sizeof(double), &data_y[AXPY_N / 8 * omp_get_thread_num()]); __builtin_ssr_setup_1d_w(2, 0, AXPY_N / NUMTHREADS - 1, sizeof(double), &data_y[AXPY_N / 8 * omp_get_thread_num()]); __builtin_ssr_enable(); #pragma omp for schedule(static) for (unsigned i = 0; i < AXPY_N; i++) { // data_y[i] = data_a * data_x[i] + data_y[i]; // data_y[i] = data_a * __builtin_ssr_pop(0) + __builtin_ssr_pop(1); __builtin_ssr_push( 2, data_a * __builtin_ssr_pop(0) + __builtin_ssr_pop(1)); } __builtin_ssr_disable(); } // check data unsigned errs = 0; double gold; for (unsigned i = 0; i < AXPY_N; i++) { gold = 10.0 * (double)(i) + (double)(i + 1); if ((gold - data_y[i]) * (gold - data_y[i]) > 0.01) errs++; } if (errs) tprintf("Error [static_schedule]: %d mismatches\n", errs); return errs ? 1 : 0; } unsigned __attribute__((noinline)) paralell_section(void) { unsigned tx = read_csr(minstret); static volatile uint32_t sum = 0; // the following code is executed by all harts #pragma omp parallel { tx = read_csr(minstret) - tx; __atomic_add_fetch(&sum, 10, __ATOMIC_RELAXED); } return sum != 8 * 10; } #define DATASIZE 4 * 1024 #define TILESIZE (DATASIZE / 4) #define NTHREADS 8 #include "data.h" unsigned __attribute__((noinline)) double_buffering(void) { static double *bufx, *bufy, *x, *y; static double a; bufx = snrt_l1alloc(sizeof(double) * 2 * TILESIZE); bufy = snrt_l1alloc(sizeof(double) * 2 * TILESIZE); x = axpy_4096_x; y = axpy_4096_y; a = axpy_4096_a; #pragma omp parallel firstprivate(bufx, bufy, x, y, a) { int tile; int thread_id = omp_get_thread_num(); // first copy-in if (thread_id == 0) { ttprintf("copy-in t: %d\n", 0); dm_memcpy_async((void *)bufx, (void *)x, sizeof(double) * TILESIZE); dm_memcpy_async((void *)bufy, (void *)y, sizeof(double) * TILESIZE); dm_wait(); } #pragma omp barrier for (tile = 0; tile < DATASIZE; tile += TILESIZE) { // copy if (thread_id == 0) { // copy-out if (tile > 0) { ttprintf("copy-out t: %d\n", tile); dm_memcpy_async( (void *)&x[tile - TILESIZE], (void *)&bufx[TILESIZE * ((tile / TILESIZE + 1) % 2)], sizeof(double) * TILESIZE); } // copy-in if (tile < DATASIZE - TILESIZE) { ttprintf("copy-in t: %d\n", tile); dm_memcpy_async( (void *)&bufx[TILESIZE * ((tile / TILESIZE + 1) % 2)], (void *)&x[tile + TILESIZE], sizeof(double) * TILESIZE); dm_memcpy_async( (void *)&bufy[TILESIZE * ((tile / TILESIZE + 1) % 2)], (void *)&y[tile + TILESIZE], sizeof(double) * TILESIZE); } dm_start(); } // compute // if (thread_id == 0) // for (int i = 0; i < TILESIZE; ++i) // tprintf(" %3d x %3.2f y %3.2f\n", i, // bufx[TILESIZE * ((tile / TILESIZE) % 2) + i], // bufy[TILESIZE * ((tile / TILESIZE) % 2) + i]); __builtin_ssr_setup_1d_r(0, 0, TILESIZE / NTHREADS - 1, sizeof(double), &bufx[TILESIZE * ((tile / TILESIZE) % 2) + thread_id * TILESIZE / NTHREADS]); __builtin_ssr_setup_1d_r(1, 0, TILESIZE / NTHREADS - 1, sizeof(double), &bufy[TILESIZE * ((tile / TILESIZE) % 2) + thread_id * TILESIZE / NTHREADS]); __builtin_ssr_setup_1d_w(2, 0, TILESIZE / NTHREADS - 1, sizeof(double), &bufx[TILESIZE * ((tile / TILESIZE) % 2) + thread_id * TILESIZE / NTHREADS]); __builtin_ssr_enable(); asm volatile( // Computation "frep.o %[ldec], 1, 0, 0b0000 \n" "fmadd.d ft2, %[a], ft0, ft1 \n" ::[a] "fr"(a), [ ldec ] "r"(TILESIZE / NTHREADS - 1) : "memory", "ft0", "ft1", "ft2"); __builtin_ssr_barrier(2); __builtin_ssr_disable(); // copy barrier if (thread_id == 0) dm_wait(); #pragma omp barrier } // last copy-out if (thread_id == 0) { dm_memcpy_async( (void *)&x[tile - TILESIZE], (void *)&bufx[TILESIZE * ((tile / TILESIZE + 1) % 2)], sizeof(double) * TILESIZE); dm_wait(); } } // Verify result // double mse = 0.0, gold; // for (int i = 0; i < DATASIZE; ++i) { // gold = axpy_4096_g[i]; // mse += (gold - x[i]) * (gold - x[i]); // } // mse = mse * 1.0 * (1.0 / (double)(DATASIZE)); // tprintf("mse = %f\n", mse); // if (mse > 0.0001) return 1; return 0; } int main() { unsigned core_idx = snrt_cluster_core_idx(); unsigned core_num = snrt_cluster_core_num(); unsigned err = 0; __snrt_omp_bootstrap(core_idx); tprintf("Static schedule test\n"); err |= static_schedule() << 0; OMP_PROF(omp_print_prof()); tprintf("Launch overhead test\n"); err |= paralell_section() << 1; OMP_PROF(omp_print_prof()); tprintf("Double buffering test\n"); err |= double_buffering() << 2; OMP_PROF(omp_print_prof()); // exit __snrt_omp_destroy(core_idx); return err; }
a.18.1.c
/* { dg-do run } */ #include <omp.h> #include <stdio.h> extern void abort (void); #define NUMBER_OF_THREADS 4 int synch[NUMBER_OF_THREADS]; int work[NUMBER_OF_THREADS]; int result[NUMBER_OF_THREADS]; int fn1 (int i) { return i * 2; } int fn2 (int a, int b) { return a + b; } int main () { int i, iam, neighbor; omp_set_num_threads (NUMBER_OF_THREADS); #pragma omp parallel private(iam,neighbor) shared(work,synch) { iam = omp_get_thread_num (); synch[iam] = 0; #pragma omp barrier /*Do computation into my portion of work array */ work[iam] = fn1 (iam); /* Announce that I am done with my work. The first flush * ensures that my work is made visible before synch. * The second flush ensures that synch is made visible. */ #pragma omp flush(work,synch) synch[iam] = 1; #pragma omp flush(synch) /* Wait for neighbor. The first flush ensures that synch is read * from memory, rather than from the temporary view of memory. * The second flush ensures that work is read from memory, and * is done so after the while loop exits. */ neighbor = (iam > 0 ? iam : omp_get_num_threads ()) - 1; while (synch[neighbor] == 0) { #pragma omp flush(synch) } #pragma omp flush(work,synch) /* Read neighbor's values of work array */ result[iam] = fn2 (work[neighbor], work[iam]); } /* output result here */ for (i = 0; i < NUMBER_OF_THREADS; i++) { neighbor = (i > 0 ? i : NUMBER_OF_THREADS) - 1; if (result[i] != i * 2 + neighbor * 2) abort (); } return 0; }
coordinate_transformation_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: // // #ifndef KRATOS_COORDINATE_TRANSFORMATION_UTILITIES_H #define KRATOS_COORDINATE_TRANSFORMATION_UTILITIES_H // system includes // external includes #include "boost/numeric/ublas/matrix_proxy.hpp" // kratos includes #include "includes/define.h" #include "includes/node.h" #include "containers/variable.h" #include "geometries/geometry.h" namespace Kratos { ///@addtogroup KratosCore ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// A utility to rotate the local contributions of certain nodes to the system matrix, which is required to apply slip conditions in arbitrary directions. template<class TLocalMatrixType, class TLocalVectorType, class TValueType> class CoordinateTransformationUtils { public: ///@name Type Definitions ///@{ /// Pointer definition of CoordinateTransformationUtils KRATOS_CLASS_POINTER_DEFINITION(CoordinateTransformationUtils); typedef Node<3> NodeType; typedef Geometry< Node<3> > GeometryType; // typedef boost::numeric::ublas::matrix_row<TLocalMatrixType> LocalRowType; // // typedef boost::numeric::ublas::matrix_range<TLocalMatrixType> MatrixBlockType; ///@} ///@name Life Cycle ///@{ /// Constructor. /** @param DomainSize Number of space dimensions (2 or 3) * @param NumRowsPerNode Number of matrix or vector rows associated to each node. Velocity DOFs are assumed to be the first mDomainSize rows in each block of rows. * @param rSelectionFlag All nodes where the flag given by this argument is set to true will be transformed to a rotated coordinate system. */ CoordinateTransformationUtils(const unsigned int DomainSize, const unsigned int NumRowsPerNode, const Kratos::Flags& rSelectionFlag = SLIP): mDomainSize(DomainSize), mBlockSize(NumRowsPerNode), mrFlag(rSelectionFlag) {} /// Destructor. virtual ~CoordinateTransformationUtils() {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Calculates rotation operator for given point * * This metod calculates rotation matrix for a given point. Nodal NORMAL variable should be * assigned properly since rotation is calculated based on it. * * @param rRotationMatrix Output rotation matrix * @param rThisPoint Current node */ virtual void CalculateRotationOperatorPure( TLocalMatrixType& rRotationMatrix, const GeometryType::PointType& rThisPoint) const { KRATOS_TRY if (mDomainSize == 2) { BoundedMatrix<double, 2, 2> local_matrix; this->LocalRotationOperatorPure(local_matrix, rThisPoint); if (rRotationMatrix.size1() != 2 || rRotationMatrix.size2() != 2) { rRotationMatrix.resize(2, 2, false); } noalias(rRotationMatrix) = local_matrix; } else if (mDomainSize == 3) { BoundedMatrix<double, 3, 3> local_matrix; this->LocalRotationOperatorPure(local_matrix, rThisPoint); if (rRotationMatrix.size1() != 3 || rRotationMatrix.size2() != 3) { rRotationMatrix.resize(3, 3, false); } noalias(rRotationMatrix) = local_matrix; } else { KRATOS_ERROR << "Unsupported domain size [ mDomainSize = " << mDomainSize << " ].\n"; } KRATOS_CATCH(""); } /** * @brief Calculates rotation nodal matrix shape sensitivities * * This method calculates shape sensitivities of rotation matrix for given node. * Nodal NORMAL(historical data container) and NORMAL_SHAPE_SENSITIVITY(non-historical data contaienr) variables * should be properly initialized. * * NORMAL_SHAPE_SENSITIVITY matrix should be properly sized and initialized with proper shape sensitivity values * rows: number_of_nodes contributing to NORMAL * DOMAIN_SIZE, columns: DOMAIN_SIZE * * @param rRotationMatrixShapeDerivative Output shape sensitivities matrix w.r.t. NodeIndex and DerivativeIndex * @param DerivativeNodeIndex NodeIndex for which shape sensitivity matrix is computed * @param DerivativeDirectionIndex Direction index of the node for which shape sensitivity matrix is computed * @param rThisPoint Current node where rotation matrix shape sensitivities are required */ virtual void CalculateRotationOperatorPureShapeSensitivities( TLocalMatrixType& rRotationMatrixShapeDerivative, const std::size_t DerivativeNodeIndex, const std::size_t DerivativeDirectionIndex, const GeometryType::PointType& rThisPoint) const { KRATOS_TRY if (mDomainSize == 2) { BoundedMatrix<double, 2, 2> local_matrix; this->CalculateRotationOperatorPureShapeSensitivities( local_matrix, DerivativeNodeIndex, DerivativeDirectionIndex, rThisPoint); if (rRotationMatrixShapeDerivative.size1() != 2 || rRotationMatrixShapeDerivative.size2() != 2) { rRotationMatrixShapeDerivative.resize(2, 2, false); } noalias(rRotationMatrixShapeDerivative) = local_matrix; } else if (mDomainSize == 3) { BoundedMatrix<double, 3, 3> local_matrix; this->CalculateRotationOperatorPureShapeSensitivities( local_matrix, DerivativeNodeIndex, DerivativeDirectionIndex, rThisPoint); if (rRotationMatrixShapeDerivative.size1() != 3 || rRotationMatrixShapeDerivative.size2() != 3) { rRotationMatrixShapeDerivative.resize(3, 3, false); } noalias(rRotationMatrixShapeDerivative) = local_matrix; } else { KRATOS_ERROR << "Unsupported domain size [ mDomainSize = " << mDomainSize << " ].\n"; } KRATOS_CATCH(""); } /** * @brief Calculate 2d rotation nodal matrix shape sensitivities * * This method calculates shape sensitivities of 2D rotation matrix for given node. * Nodal NORMAL(historical data container) and NORMAL_SHAPE_SENSITIVITY(non-historical data contaienr) variables * should be properly initialized. * * NORMAL_SHAPE_SENSITIVITY matrix should be properly sized and initialized with proper shape sensitivity values * rows: (number_of_neighbour_nodes + 1) * 2 * cols: 2 * * @param rOutput Output shape sensitivities matrix w.r.t. NodeIndex and DerivativeIndex * @param DerivativeNodeIndex NodeIndex for which shape sensitivity matrix is computed * @param DerivativeDirectionIndex Direction index of the node for which shape sensitivity matrix is computed * @param rThisPoint Current node where rotation matrix shape sensitivities are required */ virtual void CalculateRotationOperatorPureShapeSensitivities( BoundedMatrix<double, 2, 2>& rOutput, const std::size_t DerivativeNodeIndex, const std::size_t DerivativeDirectionIndex, const GeometryType::PointType& rThisPoint) const { KRATOS_TRY KRATOS_ERROR_IF(!rThisPoint.SolutionStepsDataHas(NORMAL)) << "NORMAL is not found in node at " << rThisPoint.Coordinates() << "."; KRATOS_ERROR_IF(!rThisPoint.Has(NORMAL_SHAPE_DERIVATIVE)) << "NORMAL_SHAPE_DERIVATIVE is not found in node at " << rThisPoint.Coordinates() << "."; const array_1d<double, 3>& r_nodal_normal = rThisPoint.FastGetSolutionStepValue(NORMAL); const double nodal_normal_magnitude = norm_2(r_nodal_normal); KRATOS_ERROR_IF(nodal_normal_magnitude == 0.0) << "NORMAL at node " << rThisPoint.Coordinates() << " is not properly initialized."; const Matrix& r_sensitivity_values = rThisPoint.GetValue(NORMAL_SHAPE_DERIVATIVE); KRATOS_DEBUG_ERROR_IF(r_sensitivity_values.size2() != 2) << "NORMAL_SHAPE_DERIVATIVE is not properly initialized at node " << rThisPoint.Coordinates() << " to calculate 2D rotation operator shape sensitivities. [ required number of columns = 2, available number of columns = " << r_sensitivity_values.size2() << " ]."; const std::size_t require_rows = (DerivativeNodeIndex + 1) * 2; KRATOS_DEBUG_ERROR_IF(r_sensitivity_values.size1() < require_rows) << "NORMAL_SHAPE_DERIVATIVE is not properly initialized at node " << rThisPoint.Coordinates() << " to calculate 2D rotation operator shape sensitivities. [ required number of rows >= " << require_rows << ", available number of rows = " << r_sensitivity_values.size1() << " ]."; const Vector& r_nodal_normal_derivatives = row(r_sensitivity_values, DerivativeNodeIndex * 2 + DerivativeDirectionIndex); rOutput(0, 0) = r_nodal_normal_derivatives[0] / nodal_normal_magnitude; rOutput(0, 1) = r_nodal_normal_derivatives[1] / nodal_normal_magnitude; rOutput(1, 0) = -r_nodal_normal_derivatives[1] / nodal_normal_magnitude; rOutput(1, 1) = r_nodal_normal_derivatives[0] / nodal_normal_magnitude; const double nodal_normal_magnitude_derivative = (r_nodal_normal[0] * r_nodal_normal_derivatives[0] + r_nodal_normal[1] * r_nodal_normal_derivatives[1]) / nodal_normal_magnitude; const double coeff = nodal_normal_magnitude_derivative / (std::pow(nodal_normal_magnitude, 2)); rOutput(0, 0) -= r_nodal_normal[0] * coeff; rOutput(0, 1) -= r_nodal_normal[1] * coeff; rOutput(1, 0) -= -r_nodal_normal[1] * coeff; rOutput(1, 1) -= r_nodal_normal[0] * coeff; KRATOS_CATCH(""); } /** * @brief Calculate 3d rotation nodal matrix shape sensitivities * * This method calculates shape sensitivities of 3D rotation matrix for given node. * Nodal NORMAL(historical data container) and NORMAL_SHAPE_SENSITIVITY(non-historical data contaienr) variables * should be properly initialized. * * NORMAL_SHAPE_SENSITIVITY matrix should be properly sized and initialized with proper shape sensitivity values * rows: (number_of_neighbour_nodes + 1) * 3 * cols: 3 * * @param rOutput Output shape sensitivities matrix w.r.t. NodeIndex and DerivativeIndex * @param DerivativeNodeIndex NodeIndex for which shape sensitivity matrix is computed * @param DerivativeDirectionIndex Direction index of the node for which shape sensitivity matrix is computed * @param rThisPoint Current node where rotation matrix shape sensitivities are required */ virtual void CalculateRotationOperatorPureShapeSensitivities( BoundedMatrix<double, 3, 3>& rOutput, const std::size_t DerivativeNodeIndex, const std::size_t DerivativeDirectionIndex, const GeometryType::PointType& rThisPoint) const { KRATOS_TRY KRATOS_ERROR_IF(!rThisPoint.SolutionStepsDataHas(NORMAL)) << "NORMAL is not found in node at " << rThisPoint.Coordinates() << "."; KRATOS_ERROR_IF(!rThisPoint.Has(NORMAL_SHAPE_DERIVATIVE)) << "NORMAL_SHAPE_DERIVATIVE is not found in node at " << rThisPoint.Coordinates() << "."; const array_1d<double, 3>& r_nodal_normal = rThisPoint.FastGetSolutionStepValue(NORMAL); const double nodal_normal_magnitude = norm_2(r_nodal_normal); KRATOS_ERROR_IF(nodal_normal_magnitude == 0.0) << "NORMAL at node " << rThisPoint.Coordinates() << " is not properly initialized."; const Matrix& r_sensitivity_values = rThisPoint.GetValue(NORMAL_SHAPE_DERIVATIVE); KRATOS_DEBUG_ERROR_IF(r_sensitivity_values.size2() != 3) << "NORMAL_SHAPE_DERIVATIVE is not properly initialized at node " << rThisPoint.Coordinates() << " to calculate 3D rotation operator shape sensitivities. [ required number of columns = 3, available number of columns = " << r_sensitivity_values.size2() << " ]."; const std::size_t require_rows = (DerivativeNodeIndex + 1) * 3; KRATOS_DEBUG_ERROR_IF(r_sensitivity_values.size1() < require_rows) << "NORMAL_SHAPE_DERIVATIVE is not properly initialized at node " << rThisPoint.Coordinates() << " to calculate 3D rotation operator shape sensitivities. [ required number of rows >= " << require_rows << ", available number of rows = " << r_sensitivity_values.size1() << " ]."; const Vector& r_nodal_normal_derivative = row(r_sensitivity_values, DerivativeNodeIndex * 3 + DerivativeDirectionIndex); const double nodal_normal_magnitude_derivative = VectorNormDerivative(nodal_normal_magnitude, r_nodal_normal, r_nodal_normal_derivative); const array_1d<double, 3>& unit_normal = r_nodal_normal / nodal_normal_magnitude; const array_1d<double, 3>& unit_normal_derivative = UnitVectorDerivative(nodal_normal_magnitude, nodal_normal_magnitude_derivative, r_nodal_normal, r_nodal_normal_derivative); rOutput(0, 0) = unit_normal_derivative[0]; rOutput(0, 1) = unit_normal_derivative[1]; rOutput(0, 2) = unit_normal_derivative[2]; array_1d<double, 3> rT1(0.0); rT1[0] = 1.0; double dot = unit_normal[0]; double dot_derivative = unit_normal_derivative[0]; if (std::abs(dot) > 0.99) { rT1[0] = 0.0; rT1[1] = 1.0; dot = unit_normal[1]; dot_derivative = unit_normal_derivative[1]; } // calculate rT1 noalias(rT1) -= unit_normal * dot; const double rT1_norm = norm_2(rT1); const array_1d<double, 3>& unit_rT1 = rT1 / rT1_norm; // calculate rT1 derivative const array_1d<double, 3>& rT1_derivative = (unit_normal_derivative * dot + unit_normal * dot_derivative) * -1.0; // calculate rT1 norm derivative const double rT1_norm_derivative = VectorNormDerivative(rT1_norm, rT1, rT1_derivative); const array_1d<double, 3>& unit_rT1_derivative = UnitVectorDerivative(rT1_norm, rT1_norm_derivative, rT1, rT1_derivative); rOutput(1, 0) = unit_rT1_derivative[0]; rOutput(1, 1) = unit_rT1_derivative[1]; rOutput(1, 2) = unit_rT1_derivative[2]; rOutput(2, 0) = unit_normal_derivative[1] * unit_rT1[2] + unit_normal[1] * unit_rT1_derivative[2] - unit_normal_derivative[2] * unit_rT1[1] - unit_normal[2] * unit_rT1_derivative[1]; rOutput(2, 1) = unit_normal_derivative[2] * unit_rT1[0] + unit_normal[2] * unit_rT1_derivative[0] - unit_normal_derivative[0] * unit_rT1[2] - unit_normal[0] * unit_rT1_derivative[2]; rOutput(2, 2) = unit_normal_derivative[0] * unit_rT1[1] + unit_normal[0] * unit_rT1_derivative[1] - unit_normal_derivative[1] * unit_rT1[0] - unit_normal[1] * unit_rT1_derivative[0]; KRATOS_CATCH(""); } /// Rotate the local system contributions so that they are oriented with each node's normal. /** @param rLocalMatrix Local system matrix @param rLocalVector Local RHS vector @param rGeometry A reference to the element's (or condition's) geometry */ virtual void Rotate(TLocalMatrixType& rLocalMatrix, TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { if(mBlockSize != mDomainSize) //Monolithic case { if(mDomainSize == 2) RotateAux<2,3>(rLocalMatrix,rLocalVector,rGeometry); if(mDomainSize == 3) RotateAux<3,4>(rLocalMatrix,rLocalVector,rGeometry); } else //fractional step case { if(mDomainSize == 2) RotateAuxPure<2>(rLocalMatrix,rLocalVector,rGeometry); if(mDomainSize == 3) RotateAuxPure<3>(rLocalMatrix,rLocalVector,rGeometry); } } /// RHS only version of Rotate virtual void Rotate(TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { //const unsigned int LocalSize = rLocalVector.size(); // We expect this to work both with elements (4 nodes) and conditions (3 nodes) unsigned int Index = 0; if (rLocalVector.size() > 0) { if(mBlockSize != mDomainSize) //Monolithic case { for(unsigned int j = 0; j < rGeometry.PointsNumber(); ++j) { if( this->IsSlip(rGeometry[j]) ) { if(mDomainSize == 3) { array_1d<double,4> aux,aux1; BoundedMatrix<double,4,4> rRot; LocalRotationOperator3D<4>(rRot,rGeometry[j]); for(unsigned int k=0; k<4; k++) aux[k] = rLocalVector[j*mBlockSize+k]; noalias(aux1) = prod(rRot,aux); for(unsigned int k=0; k<4; k++) rLocalVector[j*mBlockSize+k] = aux1[k]; } else { array_1d<double,3> aux,aux1; BoundedMatrix<double,3,3> rRot; LocalRotationOperator2D<3>(rRot,rGeometry[j]); for(unsigned int k=0; k<3; k++) { aux[k] = rLocalVector[j*mBlockSize+k]; } noalias(aux1) = prod(rRot,aux); for(unsigned int k=0; k<3; k++) rLocalVector[j*mBlockSize+k] = aux1[k]; } } Index += mBlockSize; } } else //fractional step case { for(unsigned int j = 0; j < rGeometry.PointsNumber(); ++j) { if( this->IsSlip(rGeometry[j]) ) { if(mDomainSize == 3) { array_1d<double,3> aux,aux1; BoundedMatrix<double,3,3> rRot; LocalRotationOperatorPure(rRot,rGeometry[j]); for(unsigned int k=0; k<3; k++) aux[k] = rLocalVector[j*mBlockSize+k]; noalias(aux1) = prod(rRot,aux); for(unsigned int k=0; k<3; k++) rLocalVector[j*mBlockSize+k] = aux1[k]; } else { array_1d<double,2> aux,aux1; BoundedMatrix<double,2,2> rRot; LocalRotationOperatorPure(rRot,rGeometry[j]); for(unsigned int k=0; k<2; k++) aux[k] = rLocalVector[j*mBlockSize+k]; noalias(aux1) = prod(rRot,aux); for(unsigned int k=0; k<2; k++) rLocalVector[j*mBlockSize+k] = aux1[k]; } } Index += mBlockSize; } } } } /// Apply slip boundary conditions to the rotated local contributions. /** This function takes the local system contributions rotated so each node's velocities are expressed using a base oriented with its normal and imposes that the normal velocity is equal to the mesh velocity in the normal direction. */ virtual void ApplySlipCondition(TLocalMatrixType& rLocalMatrix, TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { const unsigned int LocalSize = rLocalVector.size(); // We expect this to work both with elements (4 nodes) and conditions (3 nodes) if (LocalSize > 0) { for(unsigned int itNode = 0; itNode < rGeometry.PointsNumber(); ++itNode) { if( this->IsSlip(rGeometry[itNode])) { // We fix the first dof (normal velocity) for each rotated block unsigned int j = itNode * mBlockSize; //const double k = rLocalMatrix(j,j)+rLocalMatrix(j,j+1)+rLocalMatrix(j,j+2); // If the mesh is moving, we must impose v_normal = vmesh_normal array_1d<double,3> VMesh = rGeometry[itNode].FastGetSolutionStepValue(MESH_VELOCITY); VMesh -= rGeometry[itNode].FastGetSolutionStepValue(VELOCITY); array_1d<double,3> rN = rGeometry[itNode].FastGetSolutionStepValue(NORMAL); this->Normalize(rN); for( unsigned int i = 0; i < j; ++i)// Skip term (i,i) { rLocalMatrix(i,j) = 0.0; rLocalMatrix(j,i) = 0.0; } for( unsigned int i = j+1; i < LocalSize; ++i) { rLocalMatrix(i,j) = 0.0; rLocalMatrix(j,i) = 0.0; } rLocalVector(j) = inner_prod(rN,VMesh); rLocalMatrix(j,j) = 1.0; } } } } /// RHS only version of ApplySlipCondition virtual void ApplySlipCondition(TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { if (rLocalVector.size() > 0) { for(unsigned int itNode = 0; itNode < rGeometry.PointsNumber(); ++itNode) { if( this->IsSlip(rGeometry[itNode]) ) { // We fix the first dof (normal velocity) for each rotated block unsigned int j = itNode * mBlockSize; // If the mesh is moving, we must impose v_normal = vmesh_normal array_1d<double,3> VMesh = rGeometry[itNode].FastGetSolutionStepValue(MESH_VELOCITY); VMesh -= rGeometry[itNode].FastGetSolutionStepValue(VELOCITY); array_1d<double,3> rN = rGeometry[itNode].FastGetSolutionStepValue(NORMAL); this->Normalize(rN); rLocalVector[j] = inner_prod(rN,VMesh); } } } } /// Transform nodal velocities to the rotated coordinates (aligned with each node's normal) virtual void RotateVelocities(ModelPart& rModelPart) const { TLocalVectorType Vel(mDomainSize); TLocalVectorType Tmp(mDomainSize); ModelPart::NodeIterator it_begin = rModelPart.NodesBegin(); #pragma omp parallel for firstprivate(Vel,Tmp) for(int iii=0; iii<static_cast<int>(rModelPart.Nodes().size()); iii++) { ModelPart::NodeIterator itNode = it_begin+iii; if( this->IsSlip(*itNode) ) { //this->RotationOperator<TLocalMatrixType>(Rotation,); if(mDomainSize == 3) { BoundedMatrix<double,3,3> rRot; LocalRotationOperatorPure(rRot,*itNode); array_1d<double,3>& rVelocity = itNode->FastGetSolutionStepValue(VELOCITY); for(unsigned int i = 0; i < 3; i++) Vel[i] = rVelocity[i]; noalias(Tmp) = prod(rRot,Vel); for(unsigned int i = 0; i < 3; i++) rVelocity[i] = Tmp[i]; } else { BoundedMatrix<double,2,2> rRot; LocalRotationOperatorPure(rRot,*itNode); array_1d<double,3>& rVelocity = itNode->FastGetSolutionStepValue(VELOCITY); for(unsigned int i = 0; i < 2; i++) Vel[i] = rVelocity[i]; noalias(Tmp) = prod(rRot,Vel); for(unsigned int i = 0; i < 2; i++) rVelocity[i] = Tmp[i]; } } } } /// Transform nodal velocities from the rotated system to the original one virtual void RecoverVelocities(ModelPart& rModelPart) const { TLocalVectorType Vel(mDomainSize); TLocalVectorType Tmp(mDomainSize); ModelPart::NodeIterator it_begin = rModelPart.NodesBegin(); #pragma omp parallel for firstprivate(Vel,Tmp) for(int iii=0; iii<static_cast<int>(rModelPart.Nodes().size()); iii++) { ModelPart::NodeIterator itNode = it_begin+iii; if( this->IsSlip(*itNode) ) { if(mDomainSize == 3) { BoundedMatrix<double,3,3> rRot; LocalRotationOperatorPure(rRot,*itNode); array_1d<double,3>& rVelocity = itNode->FastGetSolutionStepValue(VELOCITY); for(unsigned int i = 0; i < 3; i++) Vel[i] = rVelocity[i]; noalias(Tmp) = prod(trans(rRot),Vel); for(unsigned int i = 0; i < 3; i++) rVelocity[i] = Tmp[i]; } else { BoundedMatrix<double,2,2> rRot; LocalRotationOperatorPure(rRot,*itNode); array_1d<double,3>& rVelocity = itNode->FastGetSolutionStepValue(VELOCITY); for(unsigned int i = 0; i < 2; i++) Vel[i] = rVelocity[i]; noalias(Tmp) = prod(trans(rRot),Vel); for(unsigned int i = 0; i < 2; i++) rVelocity[i] = Tmp[i]; } } } } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { std::stringstream buffer; buffer << "CoordinateTransformationUtils"; return buffer.str(); } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << "CoordinateTransformationUtils"; } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const {} ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ template<unsigned int TDim, unsigned int TBlockSize, unsigned int TSkip = 0> void RotateAux(TLocalMatrixType& rLocalMatrix, TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { const unsigned int LocalSize = rLocalVector.size(); unsigned int Index = 0; int rotations_needed = 0; const unsigned int NumBlocks = LocalSize / TBlockSize; DenseVector<bool> NeedRotation( NumBlocks, false); std::vector< BoundedMatrix<double,TBlockSize,TBlockSize> > rRot(NumBlocks); for(unsigned int j = 0; j < NumBlocks; ++j) { if( this->IsSlip(rGeometry[j]) ) { NeedRotation[j] = true; rotations_needed++; if (TDim == 2) LocalRotationOperator2D<TBlockSize,TSkip>(rRot[j],rGeometry[j]); else LocalRotationOperator3D<TBlockSize,TSkip>(rRot[j],rGeometry[j]); } Index += TBlockSize; } if(rotations_needed > 0) { BoundedMatrix<double,TBlockSize,TBlockSize> mat_block, tmp; array_1d<double,TBlockSize> aux, aux1; for(unsigned int i=0; i<NumBlocks; i++) { if(NeedRotation[i] == true) { for(unsigned int j=0; j<NumBlocks; j++) { if(NeedRotation[j] == true) { ReadBlockMatrix<TBlockSize>(mat_block, rLocalMatrix, i*TBlockSize, j*TBlockSize); noalias(tmp) = prod(mat_block,trans(rRot[j])); noalias(mat_block) = prod(rRot[i],tmp); WriteBlockMatrix<TBlockSize>(mat_block, rLocalMatrix, i*TBlockSize, j*TBlockSize); } else { ReadBlockMatrix<TBlockSize>(mat_block, rLocalMatrix, i*TBlockSize, j*TBlockSize); noalias(tmp) = prod(rRot[i],mat_block); WriteBlockMatrix<TBlockSize>(tmp, rLocalMatrix, i*TBlockSize, j*TBlockSize); } } for(unsigned int k=0; k<TBlockSize; k++) aux[k] = rLocalVector[i*TBlockSize+k]; noalias(aux1) = prod(rRot[i],aux); for(unsigned int k=0; k<TBlockSize; k++) rLocalVector[i*TBlockSize+k] = aux1[k]; } else { for(unsigned int j=0; j<NumBlocks; j++) { if(NeedRotation[j] == true) { ReadBlockMatrix<TBlockSize>(mat_block, rLocalMatrix, i*TBlockSize, j*TBlockSize); noalias(tmp) = prod(mat_block,trans(rRot[j])); WriteBlockMatrix<TBlockSize>(tmp, rLocalMatrix, i*TBlockSize, j*TBlockSize); } } } } } } //to be used when there is only velocity (no additional pressure or other var block) template<unsigned int TDim> void RotateAuxPure(TLocalMatrixType& rLocalMatrix, TLocalVectorType& rLocalVector, GeometryType& rGeometry) const { const unsigned int LocalSize = rLocalVector.size(); unsigned int Index = 0; int rotations_needed = 0; const unsigned int NumBlocks = LocalSize / mBlockSize; DenseVector<bool> NeedRotation( NumBlocks, false); std::vector< BoundedMatrix<double,TDim,TDim> > rRot(NumBlocks); for(unsigned int j = 0; j < NumBlocks; ++j) { if( this->IsSlip(rGeometry[j]) ) { NeedRotation[j] = true; rotations_needed++; LocalRotationOperatorPure(rRot[j],rGeometry[j]); } Index += mBlockSize; } if(rotations_needed > 0) { BoundedMatrix<double,TDim,TDim> mat_block, tmp; array_1d<double,TDim> aux, aux1; for(unsigned int i=0; i<NumBlocks; i++) { if(NeedRotation[i] == true) { for(unsigned int j=0; j<NumBlocks; j++) { if(NeedRotation[j] == true) { ReadBlockMatrix<TDim>(mat_block, rLocalMatrix, i*mBlockSize, j*mBlockSize); noalias(tmp) = prod(mat_block,trans(rRot[j])); noalias(mat_block) = prod(rRot[i],tmp); WriteBlockMatrix<TDim>(mat_block, rLocalMatrix, i*mBlockSize, j*mBlockSize); } else { ReadBlockMatrix<TDim>(mat_block, rLocalMatrix, i*mBlockSize, j*mBlockSize); noalias(tmp) = prod(rRot[i],mat_block); WriteBlockMatrix<TDim>(tmp, rLocalMatrix, i*mBlockSize, j*mBlockSize); } } for(unsigned int k=0; k<TDim; k++) aux[k] = rLocalVector[i*mBlockSize+k]; noalias(aux1) = prod(rRot[i],aux); for(unsigned int k=0; k<TDim; k++) rLocalVector[i*mBlockSize+k] = aux1[k]; } else { for(unsigned int j=0; j<NumBlocks; j++) { if(NeedRotation[j] == true) { ReadBlockMatrix<TDim>(mat_block, rLocalMatrix, i*mBlockSize, j*mBlockSize); noalias(tmp) = prod(mat_block,trans(rRot[j])); WriteBlockMatrix<TDim>(tmp, rLocalMatrix, i*mBlockSize, j*mBlockSize); } } } } } } template<unsigned int TBlockSize, unsigned int TSkip = 0> void LocalRotationOperator2D( BoundedMatrix<double,TBlockSize,TBlockSize>& rRot, GeometryType::PointType& rThisPoint) const { noalias(rRot) = IdentityMatrix(TBlockSize); // Get the normal evaluated at the node const array_1d<double,3>& rNormal = rThisPoint.FastGetSolutionStepValue(NORMAL); double aux = rNormal[0]*rNormal[0] + rNormal[1]*rNormal[1]; aux = sqrt(aux); rRot(TSkip ,TSkip ) = rNormal[0]/aux; rRot(TSkip ,TSkip+1) = rNormal[1]/aux; rRot(TSkip+1,TSkip ) = -rNormal[1]/aux; rRot(TSkip+1,TSkip+1) = rNormal[0]/aux; } template<unsigned int TBlockSize, unsigned int TSkip = 0> void LocalRotationOperator3D( BoundedMatrix<double,TBlockSize,TBlockSize>& rRot, GeometryType::PointType& rThisPoint) const { noalias(rRot) = IdentityMatrix(TBlockSize); // Get the normal evaluated at the node const array_1d<double,3>& rNormal = rThisPoint.FastGetSolutionStepValue(NORMAL); double aux = rNormal[0]*rNormal[0] + rNormal[1]*rNormal[1] + rNormal[2]*rNormal[2]; aux = sqrt(aux); rRot(TSkip,TSkip ) = rNormal[0]/aux; rRot(TSkip,TSkip+1) = rNormal[1]/aux; rRot(TSkip,TSkip+2) = rNormal[2]/aux; // Define the new coordinate system, where the first vector is aligned with the normal // To choose the remaining two vectors, we project the first component of the cartesian base to the tangent plane array_1d<double,3> rT1; rT1(0) = 1.0; rT1(1) = 0.0; rT1(2) = 0.0; double dot = rRot(TSkip,TSkip);//this->Dot(rN,rT1); // It is possible that the normal is aligned with (1,0,0), resulting in norm(rT1) = 0 // If this is the case, repeat the procedure using (0,1,0) if ( fabs(dot) > 0.99 ) { rT1(0) = 0.0; rT1(1) = 1.0; rT1(2) = 0.0; dot = rRot(TSkip,TSkip+1); //this->Dot(rN,rT1); } // calculate projection and normalize rT1[0] -= dot*rRot(TSkip,TSkip); rT1[1] -= dot*rRot(TSkip,TSkip+1); rT1[2] -= dot*rRot(TSkip,TSkip+2); this->Normalize(rT1); rRot(TSkip+1,TSkip ) = rT1[0]; rRot(TSkip+1,TSkip+1) = rT1[1]; rRot(TSkip+1,TSkip+2) = rT1[2]; // The third base component is choosen as N x T1, which is normalized by construction rRot(TSkip+2,TSkip ) = rRot(TSkip,TSkip+1)*rT1[2] - rRot(TSkip,TSkip+2)*rT1[1]; rRot(TSkip+2,TSkip+1) = rRot(TSkip,TSkip+2)*rT1[0] - rRot(TSkip,TSkip )*rT1[2]; rRot(TSkip+2,TSkip+2) = rRot(TSkip,TSkip )*rT1[1] - rRot(TSkip,TSkip+1)*rT1[0]; } void LocalRotationOperatorPure( BoundedMatrix<double,3,3>& rRot, const GeometryType::PointType& rThisPoint) const { // Get the normal evaluated at the node const array_1d<double,3>& rNormal = rThisPoint.FastGetSolutionStepValue(NORMAL); double aux = rNormal[0]*rNormal[0] + rNormal[1]*rNormal[1] + rNormal[2]*rNormal[2]; aux = sqrt(aux); rRot(0,0) = rNormal[0]/aux; rRot(0,1) = rNormal[1]/aux; rRot(0,2) = rNormal[2]/aux; // Define the new coordinate system, where the first vector is aligned with the normal // To choose the remaining two vectors, we project the first component of the cartesian base to the tangent plane array_1d<double,3> rT1; rT1(0) = 1.0; rT1(1) = 0.0; rT1(2) = 0.0; double dot = rRot(0,0);//this->Dot(rN,rT1); // It is possible that the normal is aligned with (1,0,0), resulting in norm(rT1) = 0 // If this is the case, repeat the procedure using (0,1,0) if ( fabs(dot) > 0.99 ) { rT1(0) = 0.0; rT1(1) = 1.0; rT1(2) = 0.0; dot = rRot(0,1); //this->Dot(rN,rT1); } // calculate projection and normalize rT1[0] -= dot*rRot(0,0); rT1[1] -= dot*rRot(0,1); rT1[2] -= dot*rRot(0,2); this->Normalize(rT1); rRot(1,0) = rT1[0]; rRot(1,1) = rT1[1]; rRot(1,2) = rT1[2]; // The third base component is choosen as N x T1, which is normalized by construction rRot(2,0) = rRot(0,1)*rT1[2] - rRot(0,2)*rT1[1]; rRot(2,1) = rRot(0,2)*rT1[0] - rRot(0,0)*rT1[2]; rRot(2,2) = rRot(0,0)*rT1[1] - rRot(0,1)*rT1[0]; } void LocalRotationOperatorPure( BoundedMatrix<double,2,2>& rRot, const GeometryType::PointType& rThisPoint) const { // Get the normal evaluated at the node const array_1d<double,3>& rNormal = rThisPoint.FastGetSolutionStepValue(NORMAL); double aux = rNormal[0]*rNormal[0] + rNormal[1]*rNormal[1]; aux = sqrt(aux); rRot(0,0) = rNormal[0]/aux; rRot(0,1) = rNormal[1]/aux; rRot(1,0) = -rNormal[1]/aux; rRot(1,1) = rNormal[0]/aux; } bool IsSlip(const Node<3>& rNode) const { return rNode.Is(mrFlag); } /// Normalize a vector. /** * @param rThis the vector * @return Original norm of the input vector */ template< class TVectorType > double Normalize(TVectorType& rThis) const { double Norm = 0; for(typename TVectorType::iterator iComponent = rThis.begin(); iComponent < rThis.end(); ++iComponent) Norm += (*iComponent)*(*iComponent); Norm = sqrt(Norm); for(typename TVectorType::iterator iComponent = rThis.begin(); iComponent < rThis.end(); ++iComponent) *iComponent /= Norm; return Norm; } ///@} ///@name Protected Access ///@{ unsigned int GetDomainSize() const { return mDomainSize; } unsigned int GetBlockSize() const { return mBlockSize; } ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ /// Number of spatial dimensions const unsigned int mDomainSize; /// Number of matrix or vector rows associated to each node. /** @note Velocity Dofs are assumed to be the first mDomainSize rows. */ const unsigned int mBlockSize; const Kratos::Flags& mrFlag; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ // /// Compute a rotation matrix to transform values from the cartesian base to one oriented with the node's normal // /** // * The normal is read from solution step data NORMAL. Use NormalCalculationUtils::CalculateOnSimplex to // * obtain and store the nodal normal from the normals of the model's conditons. // * @param rRot The rotation matrix (output) // * @param rThisPoint The point used to orient the new coordinate system. // * @see NormalCalculationUtils // */ // template<class TMatrixType> // void RotationOperator(TMatrixType& rRot, // GeometryType::PointType& rThisPoint) const // { // typedef boost::numeric::ublas::matrix_row<TMatrixType> ThisRowType; // // Get the normal evaluated at the node // const array_1d<double,3>& rNormal = rThisPoint.FastGetSolutionStepValue(NORMAL); // // if(mDomainSize == 3) // { // // Define the new coordinate system, where the first vector is aligned with the normal // ThisRowType rN(rRot,0); // for( unsigned int i = 0; i < 3; ++i) // rN[i] = rNormal[i]; // this->Normalize(rN); // // // To choose the remaining two vectors, we project the first component of the cartesian base to the tangent plane // ThisRowType rT1(rRot,1); // rT1(0) = 1.0; // rT1(1) = 0.0; // rT1(2) = 0.0; // // double dot = this->Dot(rN,rT1); // // // It is possible that the normal is aligned with (1,0,0), resulting in norm(rT1) = 0 // // If this is the case, repeat the procedure using (0,1,0) // if ( fabs(dot) > 0.99 ) // { // rT1(0) = 0.0; // rT1(1) = 1.0; // rT1(2) = 0.0; // // dot = this->Dot(rN,rT1); // } // // // calculate projection and normalize // rT1 -= dot * rN; // this->Normalize(rT1); // // // The third base component is choosen as N x T1, which is normalized by construction // ThisRowType rT2(rRot,2); // rT2(0) = rN(1)*rT1(2) - rN(2)*rT1(1); // rT2(1) = rN(2)*rT1(0) - rN(0)*rT1(2); // rT2(2) = rN(0)*rT1(1) - rN(1)*rT1(0); // } // else //if(mDomainSize == 2) // { // /* The basis for the new coordinate system is (normal,tangent) // Tangent vector is chosen (-normal_y, normal_x) so that the resulting base // is right-handed. // */ // ThisRowType rN(rRot,0); // ThisRowType rT(rRot,1); // // rN[0] = rNormal[0]; // rN[1] = rNormal[1]; // this->Normalize(rN); // rT[0] = -rN[1]; // rT[1] = rN[0]; // } // // } template< class TVectorType > double Dot(const TVectorType& rV1, const TVectorType& rV2) const { double dot = 0.0; for( typename TVectorType::const_iterator iV1 = rV1.begin(),iV2 = rV2.begin(); iV1 != rV1.end(); ++iV1, ++iV2) { dot += (*iV1) * (*iV2); } return dot; } inline double VectorNormDerivative( const double ValueNorm, const array_1d<double, 3>& rValue, const array_1d<double, 3>& rValueDerivative) const { return inner_prod(rValue, rValueDerivative) / ValueNorm; } inline array_1d<double, 3> UnitVectorDerivative( const double VectorNorm, const double VectorNormDerivative, const array_1d<double, 3>& rVector, const array_1d<double, 3>& rVectorDerivative) const { return (rVectorDerivative * VectorNorm - rVector * VectorNormDerivative) / std::pow(VectorNorm, 2); } /// Transform a local contribution from cartesian coordinates to rotated ones // void ApplyRotation(TLocalMatrixType& rMatrix, // const TLocalMatrixType& rRotation) const // { // // compute B = R*A*transpose(R) // const unsigned int LocalSize = rMatrix.size1(); // const unsigned int NumBlocks = LocalSize / mBlockSize; // //TLocalMatrixType Tmp = ZeroMatrix(LocalSize,LocalSize); // /* // for (unsigned int iBlock = 0; iBlock < NumBlocks; iBlock++) // { // for (unsigned int jBlock = 0; jBlock < NumBlocks; jBlock++) // { // for (unsigned int i = iBlock*mBlockSize; i < (iBlock+1)*mBlockSize; i++) // { // for(unsigned int j = jBlock*mBlockSize; j < (jBlock+1)*mBlockSize; j++) // { // double& tij = Tmp(i,j); // for(unsigned int k = iBlock*mBlockSize; k < (iBlock+1)*mBlockSize; k++) // { // for(unsigned int l = jBlock*mBlockSize; l < (jBlock+1)*mBlockSize; l++) // { // tij += rRotation(i,k)*rMatrix(k,l)*rRotation(j,l); // } // } // } // } // } // }*/ // // Matrix Tmp = prod(rMatrix,trans(rRotation)); // noalias(rMatrix) = prod(rRotation,Tmp); // // // noalias(rMatrix) = Tmp; // } //auxiliary functions template< unsigned int TBlockSize > void ReadBlockMatrix( BoundedMatrix<double,TBlockSize, TBlockSize>& block, const Matrix& origin, const unsigned int Ibegin, const unsigned int Jbegin) const { for(unsigned int i=0; i<TBlockSize; i++) { for(unsigned int j=0; j<TBlockSize; j++) { block(i,j) = origin(Ibegin+i, Jbegin+j); } } } template< unsigned int TBlockSize > void WriteBlockMatrix( const BoundedMatrix<double,TBlockSize, TBlockSize>& block, Matrix& destination, const unsigned int Ibegin, const unsigned int Jbegin) const { for(unsigned int i=0; i<TBlockSize; i++) { for(unsigned int j=0; j<TBlockSize; j++) { destination(Ibegin+i, Jbegin+j) = block(i,j); } } } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. CoordinateTransformationUtils& operator=(CoordinateTransformationUtils const& rOther) {} /// Copy constructor. CoordinateTransformationUtils(CoordinateTransformationUtils const& rOther) {} ///@} }; ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template<class TLocalMatrixType, class TLocalVectorType, class TValueType> inline std::istream& operator >>(std::istream& rIStream, CoordinateTransformationUtils<TLocalMatrixType, TLocalVectorType, TValueType>& rThis) { return rIStream; } /// output stream function template<class TLocalMatrixType, class TLocalVectorType, class TValueType> inline std::ostream& operator <<(std::ostream& rOStream, const CoordinateTransformationUtils<TLocalMatrixType, TLocalVectorType, TValueType>& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} ///@} addtogroup block } #endif // KRATOS_COORDINATE_TRANSFORMATION_UTILITIES_H
ten_tusscher_2004_epi_S2_17.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S2_17.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } //TODO: this should be called only once for the whole mesh, like in the GPU code SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5413847249581,0.00129749333274554,0.779049320216350,0.778898229736094,0.000175386577749891,0.484810494199284,0.00294593233512741,0.999998339142758,1.94217050104558e-08,1.89785399117775e-05,0.999772756079176,1.00727534190360,0.999997440785955,4.09273550037733e-05,0.410743063693995,10.9424848182514,138.731054625637}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; ///#ifdef EPI real Gks=0.245; ///#endif ///#ifdef ENDO /// real Gks=0.245; ///#endif ///#ifdef MCELL /// real Gks=0.062; ///#endif //Parameters for Ik1 real GK1=5.405; //Parameters for Ito //#ifdef EPI real Gto=0.294; //#endif // #ifdef ENDO // real Gto=0.073; //#endif //#ifdef MCELL // real Gto=0.294; ///#endif //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={14.6526831901002,0.000336603613824894,0.000142032316714142,0.000147797037794095,0.244877435259635,0.136552852378623,0.180909422982719,4.68260453463487,0.0136308755837635,1.00097696778612,1088.15434244063,0.000484016332794955,0.441709817218134,0.0199531034368028,0.00354996431590630,4.97623621373625e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; ///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; ///Ileak=0.00008f*(CaSR-Cai); Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; #ifdef EPI R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif #ifdef ENDO R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+28)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.; #endif #ifdef MCELL R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
colorspace.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO L OOO RRRR SSSSS PPPP AAA CCCC EEEEE % % C O O L O O R R SS P P A A C E % % C O O L O O RRRR SSS PPPP AAAAA C EEE % % C O O L O O R R SS P A A C E % % CCCC OOO LLLLL OOO R R SSSSS P A A CCCC EEEEE % % % % % % MagickCore Image Colorspace Methods % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1999-2009 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/property.h" #include "magick/cache.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/gem.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/string_.h" #include "magick/utility.h" /* Typedef declarations. */ typedef struct _TransformPacket { MagickRealType x, y, z; } TransformPacket; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R G B T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RGBTransformImage() converts the reference image from RGB to an alternate % colorspace. The transformation matrices are not the standard ones: the % weights are rescaled to normalized the range of the transformed values to % be [0..QuantumRange]. % % The format of the RGBTransformImage method is: % % MagickBooleanType RGBTransformImage(Image *image, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace to transform the image to. % */ static inline void ConvertRGBToXYZ(const Quantum red,const Quantum green, const Quantum blue,double *X,double *Y,double *Z) { double b, g, r; assert(X != (double *) NULL); assert(Y != (double *) NULL); assert(Z != (double *) NULL); r=QuantumScale*red; g=QuantumScale*green; b=QuantumScale*blue; *X=0.4124240*r+0.3575790*g+0.1804640*b; *Y=0.2126560*r+0.7151580*g+0.0721856*b; *Z=0.0193324*r+0.1191930*g+0.9504440*b; } static inline void ConvertXYZToLab(const double X,const double Y,const double Z, double *L,double *a,double *b) { double x, y, z; assert(L != (double *) NULL); assert(a != (double *) NULL); assert(b != (double *) NULL); x=X/0.9504559271; if (x > (216/24389.0)) x=pow(x,1.0/3.0); else x=(7.787*x)+(16.0/116.0); y=Y/1.00000; if (y > (216/24389.0)) y=pow(y,1.0/3.0); else y=(7.787*y)+(16.0/116.0); z=Z/1.0890577508; if (z > (216/24389.0)) z=pow(z,1.0/3.0); else z=(7.787*z)+(16.0/116.0); *L=0.5*((1.160*y)-0.160+1.0); *a=0.5*(5.000*(x-y)+1.0); *b=0.5*(2.000*(y-z)+1.0); } MagickExport MagickBooleanType RGBTransformImage(Image *image, const ColorspaceType colorspace) { #define RGBTransformImageTag "RGBTransform/Image" ExceptionInfo *exception; long progress, y; MagickBooleanType status, sync; PrimaryInfo primary_info; register long i; TransformPacket *x_map, *y_map, *z_map; ViewInfo *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(colorspace != RGBColorspace); assert(colorspace != TransparentColorspace); assert(colorspace != UndefinedColorspace); switch (image->colorspace) { case GRAYColorspace: case Rec601LumaColorspace: case Rec709LumaColorspace: case RGBColorspace: case TransparentColorspace: break; default: { (void) SetImageColorspace(image,image->colorspace); break; } } image->colorspace=colorspace; status=MagickTrue; progress=0; exception=(&image->exception); switch (colorspace) { case CMYColorspace: { /* Convert RGB to CMY colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { q->red=RoundToQuantum((MagickRealType) (QuantumRange-q->red)); q->green=RoundToQuantum((MagickRealType) (QuantumRange-q->green)); q->blue=RoundToQuantum((MagickRealType) (QuantumRange-q->blue)); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->type=image->matte == MagickFalse ? ColorSeparationType : ColorSeparationMatteType; return(status); } case CMYKColorspace: { MagickPixelPacket zero; /* Convert RGB to CMYK colorspace. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } GetMagickPixelPacket(image,&zero); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickPixelPacket pixel; register IndexPacket *indexes; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (long) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); ConvertRGBToCMYK(&pixel); SetPixelPacket(image,&pixel,q,indexes+x); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->type=image->matte == MagickFalse ? ColorSeparationType : ColorSeparationMatteType; return(status); } case HSBColorspace: { /* Transform image from RGB to HSB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double brightness, hue, saturation; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } hue=0.0; saturation=0.0; brightness=0.0; for (x=0; x < (long) image->columns; x++) { ConvertRGBToHSB(q->red,q->green,q->blue,&hue,&saturation,&brightness); q->red=RoundToQuantum((MagickRealType) QuantumRange*hue); q->green=RoundToQuantum((MagickRealType) QuantumRange*saturation); q->blue=RoundToQuantum((MagickRealType) QuantumRange*brightness); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } case HSLColorspace: { /* Transform image from RGB to HSL. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double hue, lightness, saturation; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } hue=0.0; saturation=0.0; lightness=0.0; for (x=0; x < (long) image->columns; x++) { ConvertRGBToHSL(q->red,q->green,q->blue,&hue,&saturation,&lightness); q->red=RoundToQuantum((MagickRealType) QuantumRange*hue); q->green=RoundToQuantum((MagickRealType) QuantumRange*saturation); q->blue=RoundToQuantum((MagickRealType) QuantumRange*lightness); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } case HWBColorspace: { /* Transform image from RGB to HWB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double blackness, hue, whiteness; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } hue=0.0; whiteness=0.0; blackness=0.0; for (x=0; x < (long) image->columns; x++) { ConvertRGBToHWB(q->red,q->green,q->blue,&hue,&whiteness,&blackness); q->red=RoundToQuantum((MagickRealType) QuantumRange*hue); q->green=RoundToQuantum((MagickRealType) QuantumRange*whiteness); q->blue=RoundToQuantum((MagickRealType) QuantumRange*blackness); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } case LabColorspace: { /* Transform image from RGB to Lab. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double a, b, L, X, Y, Z; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } L=0.0; a=0.0; b=0.0; X=0.0; Y=0.0; Z=0.0; for (x=0; x < (long) image->columns; x++) { ConvertRGBToXYZ(q->red,q->green,q->blue,&X,&Y,&Z); ConvertXYZToLab(X,Y,Z,&L,&a,&b); q->red=RoundToQuantum((MagickRealType) QuantumRange*L); q->green=RoundToQuantum((MagickRealType) QuantumRange*a); q->blue=RoundToQuantum((MagickRealType) QuantumRange*b); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); return(status); } case LogColorspace: { #define ReferenceBlack 95.0 #define ReferenceWhite 685.0 #define DisplayGamma (1.0/1.7) const char *value; double black, density, gamma, reference_black, reference_white; Quantum *logmap; /* Transform RGB to Log colorspace. */ density=2.03728; gamma=DisplayGamma; value=GetImageProperty(image,"gamma"); if (value != (const char *) NULL) gamma=1.0/atof(value) != 0.0 ? atof(value) : 1.0; reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black"); if (value != (const char *) NULL) reference_black=atof(value); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white"); if (value != (const char *) NULL) reference_white=atof(value); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)* 0.002/0.6); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) logmap[i]=ScaleMapToQuantum((MagickRealType) (MaxMap*(reference_white+ log10(black+((MagickRealType) i/MaxMap)*(1.0-black))/((gamma/density)* 0.002/0.6))/1024.0+0.5)); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=(long) image->columns; x != 0; x--) { q->red=logmap[ScaleQuantumToMap(q->red)]; q->green=logmap[ScaleQuantumToMap(q->green)]; q->blue=logmap[ScaleQuantumToMap(q->blue)]; q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) ResetMagickMemory(&primary_info,0,sizeof(primary_info)); switch (colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: I1 = 0.33333*R+0.33334*G+0.33333*B I2 = 0.50000*R+0.00000*G-0.50000*B I3 =-0.25000*R+0.50000*G-0.25000*B I and Q, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.33333f*(MagickRealType) i; y_map[i].x=0.33334f*(MagickRealType) i; z_map[i].x=0.33333f*(MagickRealType) i; x_map[i].y=0.50000f*(MagickRealType) i; y_map[i].y=0.00000f*(MagickRealType) i; z_map[i].y=(-0.50000f)*(MagickRealType) i; x_map[i].z=(-0.25000f)*(MagickRealType) i; y_map[i].z=0.50000f*(MagickRealType) i; z_map[i].z=(-0.25000f)*(MagickRealType) i; } break; } case Rec601LumaColorspace: case GRAYColorspace: { /* Initialize Rec601 luma tables: G = 0.29900*R+0.58700*G+0.11400*B */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.29900f*(MagickRealType) i; y_map[i].x=0.58700f*(MagickRealType) i; z_map[i].x=0.11400f*(MagickRealType) i; x_map[i].y=0.29900f*(MagickRealType) i; y_map[i].y=0.58700f*(MagickRealType) i; z_map[i].y=0.11400f*(MagickRealType) i; x_map[i].z=0.29900f*(MagickRealType) i; y_map[i].z=0.58700f*(MagickRealType) i; z_map[i].z=0.11400f*(MagickRealType) i; } image->type=GrayscaleType; break; } case Rec601YCbCrColorspace: case YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.601): Y = 0.299000*R+0.587000*G+0.114000*B Cb= -0.168736*R-0.331264*G+0.500000*B Cr= 0.500000*R-0.418688*G-0.081312*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.299000f*(MagickRealType) i; y_map[i].x=0.587000f*(MagickRealType) i; z_map[i].x=0.114000f*(MagickRealType) i; x_map[i].y=(-0.168730f)*(MagickRealType) i; y_map[i].y=(-0.331264f)*(MagickRealType) i; z_map[i].y=0.500000f*(MagickRealType) i; x_map[i].z=0.500000f*(MagickRealType) i; y_map[i].z=(-0.418688f)*(MagickRealType) i; z_map[i].z=(-0.081312f)*(MagickRealType) i; } break; } case Rec709LumaColorspace: { /* Initialize Rec709 luma tables: G = 0.21260*R+0.71520*G+0.07220*B */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.21260f*(MagickRealType) i; y_map[i].x=0.71520f*(MagickRealType) i; z_map[i].x=0.07220f*(MagickRealType) i; x_map[i].y=0.21260f*(MagickRealType) i; y_map[i].y=0.71520f*(MagickRealType) i; z_map[i].y=0.07220f*(MagickRealType) i; x_map[i].z=0.21260f*(MagickRealType) i; y_map[i].z=0.71520f*(MagickRealType) i; z_map[i].z=0.07220f*(MagickRealType) i; } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables (ITU-R BT.709): Y = 0.212600*R+0.715200*G+0.072200*B Cb= -0.114572*R-0.385428*G+0.500000*B Cr= 0.500000*R-0.454153*G-0.045847*B Cb and Cr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.212600f*(MagickRealType) i; y_map[i].x=0.715200f*(MagickRealType) i; z_map[i].x=0.072200f*(MagickRealType) i; x_map[i].y=(-0.114572f)*(MagickRealType) i; y_map[i].y=(-0.385428f)*(MagickRealType) i; z_map[i].y=0.500000f*(MagickRealType) i; x_map[i].z=0.500000f*(MagickRealType) i; y_map[i].z=(-0.454153f)*(MagickRealType) i; z_map[i].z=(-0.045847f)*(MagickRealType) i; } break; } case sRGBColorspace: { /* Linear RGB to nonlinear sRGB (http://www.w3.org/Graphics/Color/sRGB): R = 1.0*R+0.0*G+0.0*B G = 0.0*R+0.1*G+0.0*B B = 0.0*R+0.0*G+1.0*B */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { MagickRealType v; v=(MagickRealType) i/(MagickRealType) MaxMap; if (((MagickRealType) i/(MagickRealType) MaxMap) <= 0.03928f) v/=12.92f; else v=(MagickRealType) MaxMap*pow((((double) i/MaxMap)+0.055)/1.055,2.4); x_map[i].x=1.0f*v; y_map[i].x=0.0f*v; z_map[i].x=0.0f*v; x_map[i].y=0.0f*v; y_map[i].y=1.0f*v; z_map[i].y=0.0f*v; x_map[i].z=0.0f*v; y_map[i].z=0.0f*v; z_map[i].z=1.0f*v; } break; } case XYZColorspace: { /* Initialize CIE XYZ tables (ITU-R 709 RGB): X = 0.4124240*R+0.3575790*G+0.1804640*B Y = 0.2126560*R+0.7151580*G+0.0721856*B Z = 0.0193324*R+0.1191930*G+0.9504440*B */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.4124240f*(MagickRealType) i; y_map[i].x=0.3575790f*(MagickRealType) i; z_map[i].x=0.1804640f*(MagickRealType) i; x_map[i].y=0.2126560f*(MagickRealType) i; y_map[i].y=0.7151580f*(MagickRealType) i; z_map[i].y=0.0721856f*(MagickRealType) i; x_map[i].z=0.0193324f*(MagickRealType) i; y_map[i].z=0.1191930f*(MagickRealType) i; z_map[i].z=0.9504440f*(MagickRealType) i; } break; } case YCCColorspace: { /* Initialize YCC tables: Y = 0.29900*R+0.58700*G+0.11400*B C1= -0.29900*R-0.58700*G+0.88600*B C2= 0.70100*R-0.58700*G-0.11400*B YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ primary_info.y=(double) ScaleQuantumToMap(ScaleCharToQuantum(156)); primary_info.z=(double) ScaleQuantumToMap(ScaleCharToQuantum(137)); for (i=0; i <= (long) (0.018*MaxMap); i++) { x_map[i].x=0.003962014134275617f*(MagickRealType) i; y_map[i].x=0.007778268551236748f*(MagickRealType) i; z_map[i].x=0.001510600706713781f*(MagickRealType) i; x_map[i].y=(-0.002426619775463276f)*(MagickRealType) i; y_map[i].y=(-0.004763965913702149f)*(MagickRealType) i; z_map[i].y=0.007190585689165425f*(MagickRealType) i; x_map[i].z=0.006927257754597858f*(MagickRealType) i; y_map[i].z=(-0.005800713697502058f)*(MagickRealType) i; z_map[i].z=(-0.0011265440570958f)*(MagickRealType) i; } for ( ; i <= (long) MaxMap; i++) { x_map[i].x=0.2201118963486454*(1.099f*(MagickRealType) i-0.099f); y_map[i].x=0.4321260306242638*(1.099f*(MagickRealType) i-0.099f); z_map[i].x=0.08392226148409894*(1.099f*(MagickRealType) i-0.099f); x_map[i].y=(-0.1348122097479598)*(1.099f*(MagickRealType) i-0.099f); y_map[i].y=(-0.2646647729834528)*(1.099f*(MagickRealType) i-0.099f); z_map[i].y=0.3994769827314126*(1.099f*(MagickRealType) i-0.099f); x_map[i].z=0.3848476530332144*(1.099f*(MagickRealType) i-0.099f); y_map[i].z=(-0.3222618720834477)*(1.099f*(MagickRealType) i-0.099f); z_map[i].z=(-0.06258578094976668)*(1.099f*(MagickRealType) i-0.099f); } break; } case YIQColorspace: { /* Initialize YIQ tables: Y = 0.29900*R+0.58700*G+0.11400*B I = 0.59600*R-0.27400*G-0.32200*B Q = 0.21100*R-0.52300*G+0.31200*B I and Q, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.29900f*(MagickRealType) i; y_map[i].x=0.58700f*(MagickRealType) i; z_map[i].x=0.11400f*(MagickRealType) i; x_map[i].y=0.59600f*(MagickRealType) i; y_map[i].y=(-0.27400f)*(MagickRealType) i; z_map[i].y=(-0.32200f)*(MagickRealType) i; x_map[i].z=0.21100f*(MagickRealType) i; y_map[i].z=(-0.52300f)*(MagickRealType) i; z_map[i].z=0.31200f*(MagickRealType) i; } break; } case YPbPrColorspace: { /* Initialize YPbPr tables (ITU-R BT.601): Y = 0.299000*R+0.587000*G+0.114000*B Pb= -0.168736*R-0.331264*G+0.500000*B Pr= 0.500000*R-0.418688*G-0.081312*B Pb and Pr, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.299000f*(MagickRealType) i; y_map[i].x=0.587000f*(MagickRealType) i; z_map[i].x=0.114000f*(MagickRealType) i; x_map[i].y=(-0.168736f)*(MagickRealType) i; y_map[i].y=(-0.331264f)*(MagickRealType) i; z_map[i].y=0.500000f*(MagickRealType) i; x_map[i].z=0.500000f*(MagickRealType) i; y_map[i].z=(-0.418688f)*(MagickRealType) i; z_map[i].z=(-0.081312f)*(MagickRealType) i; } break; } case YUVColorspace: default: { /* Initialize YUV tables: Y = 0.29900*R+0.58700*G+0.11400*B U = -0.14740*R-0.28950*G+0.43690*B V = 0.61500*R-0.51500*G-0.10000*B U and V, normally -0.5 through 0.5, are normalized to the range 0 through QuantumRange. Note that U = 0.493*(B-Y), V = 0.877*(R-Y). */ primary_info.y=(double) (MaxMap+1.0)/2.0; primary_info.z=(double) (MaxMap+1.0)/2.0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=0.29900f*(MagickRealType) i; y_map[i].x=0.58700f*(MagickRealType) i; z_map[i].x=0.11400f*(MagickRealType) i; x_map[i].y=(-0.14740f)*(MagickRealType) i; y_map[i].y=(-0.28950f)*(MagickRealType) i; z_map[i].y=0.43690f*(MagickRealType) i; x_map[i].z=0.61500f*(MagickRealType) i; y_map[i].z=(-0.51500f)*(MagickRealType) i; z_map[i].z=(-0.10000f)*(MagickRealType) i; } break; } } /* Convert from RGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickPixelPacket pixel; register long x; register PixelPacket *q; register unsigned long blue, green, red; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { red=ScaleQuantumToMap(q->red); green=ScaleQuantumToMap(q->green); blue=ScaleQuantumToMap(q->blue); pixel.red=(x_map[red].x+y_map[green].x+z_map[blue].x)+ (MagickRealType) primary_info.x; pixel.green=(x_map[red].y+y_map[green].y+z_map[blue].y)+ (MagickRealType) primary_info.y; pixel.blue=(x_map[red].z+y_map[green].z+z_map[blue].z)+ (MagickRealType) primary_info.z; q->red=ScaleMapToQuantum(pixel.red); q->green=ScaleMapToQuantum(pixel.green); q->blue=ScaleMapToQuantum(pixel.blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical #endif proceed=SetImageProgress(image,RGBTransformImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { register unsigned long blue, green, red; /* Convert PseudoClass image. */ image_view=AcquireCacheView(image); for (i=0; i < (long) image->colors; i++) { MagickPixelPacket pixel; red=ScaleQuantumToMap(image->colormap[i].red); green=ScaleQuantumToMap(image->colormap[i].green); blue=ScaleQuantumToMap(image->colormap[i].blue); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x+primary_info.x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y+primary_info.y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z+primary_info.z; image->colormap[i].red=ScaleMapToQuantum(pixel.red); image->colormap[i].green=ScaleMapToQuantum(pixel.green); image->colormap[i].blue=ScaleMapToQuantum(pixel.blue); } image_view=DestroyCacheView(image_view); (void) SyncImage(image); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColorspace() sets the colorspace member of the Image structure. % % The format of the SetImageColorspace method is: % % MagickBooleanType SetImageColorspace(Image *image, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace. % */ MagickExport MagickBooleanType SetImageColorspace(Image *image, const ColorspaceType colorspace) { MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (colorspace == UndefinedColorspace) { image->colorspace=UndefinedColorspace; return(MagickTrue); } if (image->colorspace == colorspace) return(MagickTrue); if ((colorspace == RGBColorspace) || (colorspace == TransparentColorspace)) return(TransformRGBImage(image,image->colorspace)); status=MagickTrue; if ((image->colorspace != RGBColorspace) && (image->colorspace != TransparentColorspace) && (image->colorspace != GRAYColorspace)) status=TransformRGBImage(image,image->colorspace); if (RGBTransformImage(image,colorspace) == MagickFalse) status=MagickFalse; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + T r a n s f o r m R G B I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformRGBImage() converts the reference image from an alternate % colorspace to RGB. The transformation matrices are not the standard ones: % the weights are rescaled to normalize the range of the transformed values to % be [0..QuantumRange]. % % The format of the TransformRGBImage method is: % % MagickBooleanType TransformRGBImage(Image *image, % const ColorspaceType colorspace) % % A description of each parameter follows: % % o image: the image. % % o colorspace: the colorspace to transform the image to. % */ static inline void ConvertLabToXYZ(const double L,const double a,const double b, double *X,double *Y,double *Z) { double x, y, z; assert(X != (double *) NULL); assert(Y != (double *) NULL); assert(Z != (double *) NULL); y=((2.0*L-1.0)+0.160)/1.160; x=(2.0*a-1.0)/5.000+y; z=y-(2.0*b-1.0)/2.000; if ((x*x*x) > (216.0/24389.0)) x=x*x*x; else x=(x-16.0/116.0)/7.787; if ((y*y*y) > (216.0/24389.0)) y=y*y*y; else y=(y-16.0/116.0)/7.787; if ((z*z*z) > (216.0/24389.0)) z=z*z*z; else z=(z-16.0/116.0)/7.787; *X=0.9504559271*x; *Y=1.0000000000*y; *Z=1.0890577508*z; } static inline unsigned short RoundToYCC(const MagickRealType value) { if (value <= 0.0) return(0UL); if (value >= 350.0) return(350); return((unsigned short) (value+0.5)); } static inline void ConvertXYZToRGB(const double x,const double y,const double z, Quantum *red,Quantum *green,Quantum *blue) { double b, g, r; /* Convert XYZ to RGB colorspace. */ assert(red != (Quantum *) NULL); assert(green != (Quantum *) NULL); assert(blue != (Quantum *) NULL); r=3.2407100*x-1.5372600*y-0.4985710*z; g=(-0.9692580*x+1.8759900*y+0.0415557*z); b=0.0556352*x-0.2039960*y+1.0570700*z; *red=RoundToQuantum((MagickRealType) QuantumRange*r); *green=RoundToQuantum((MagickRealType) QuantumRange*g); *blue=RoundToQuantum((MagickRealType) QuantumRange*b); } static inline void ConvertCMYKToRGB(MagickPixelPacket *pixel) { pixel->red=(MagickRealType) QuantumRange-(QuantumScale*pixel->red* (QuantumRange-pixel->index)+pixel->index); pixel->green=(MagickRealType) QuantumRange-(QuantumScale*pixel->green* (QuantumRange-pixel->index)+pixel->index); pixel->blue=(MagickRealType) QuantumRange-(QuantumScale*pixel->blue* (QuantumRange-pixel->index)+pixel->index); } MagickExport MagickBooleanType TransformRGBImage(Image *image, const ColorspaceType colorspace) { #define D50X (0.9642) #define D50Y (1.0) #define D50Z (0.8249) #define TransformRGBImageTag "Transform/Image" #if !defined(MAGICKCORE_HDRI_SUPPORT) static const unsigned char YCCMap[351] = /* Photo CD information beyond 100% white, Gamma 2.2 */ { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 193, 194, 195, 196, 197, 198, 199, 200, 201, 201, 202, 203, 204, 205, 206, 207, 207, 208, 209, 210, 211, 211, 212, 213, 214, 215, 215, 216, 217, 218, 218, 219, 220, 221, 221, 222, 223, 224, 224, 225, 226, 226, 227, 228, 228, 229, 230, 230, 231, 232, 232, 233, 234, 234, 235, 236, 236, 237, 237, 238, 238, 239, 240, 240, 241, 241, 242, 242, 243, 243, 244, 244, 245, 245, 245, 246, 246, 247, 247, 247, 248, 248, 248, 249, 249, 249, 249, 250, 250, 250, 250, 251, 251, 251, 251, 251, 252, 252, 252, 252, 252, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 253, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 }; #endif ExceptionInfo *exception; long progress, y; MagickBooleanType status; register long i; TransformPacket *y_map, *x_map, *z_map; ViewInfo *image_view; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); switch (colorspace) { case GRAYColorspace: case Rec601LumaColorspace: case Rec709LumaColorspace: case RGBColorspace: case TransparentColorspace: case UndefinedColorspace: return(MagickTrue); default: break; } status=MagickTrue; progress=0; exception=(&image->exception); switch (colorspace) { case CMYColorspace: { /* Transform image from CMY to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { q->red=RoundToQuantum((MagickRealType) (QuantumRange-q->red)); q->green=RoundToQuantum((MagickRealType) (QuantumRange-q->green)); q->blue=RoundToQuantum((MagickRealType) (QuantumRange-q->blue)); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case CMYKColorspace: { MagickPixelPacket zero; /* Transform image from CMYK to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } GetMagickPixelPacket(image,&zero); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket pixel; register IndexPacket *indexes; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); pixel=zero; for (x=0; x < (long) image->columns; x++) { SetMagickPixelPacket(image,q,indexes+x,&pixel); ConvertCMYKToRGB(&pixel); SetPixelPacket(image,&pixel,q,indexes+x); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case HSBColorspace: { /* Transform image from HSB to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double brightness, hue, saturation; MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { hue=(double) (QuantumScale*q->red); saturation=(double) (QuantumScale*q->green); brightness=(double) (QuantumScale*q->blue); ConvertHSBToRGB(hue,saturation,brightness,&q->red,&q->green,&q->blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case HSLColorspace: { /* Transform image from HSL to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double hue, lightness, saturation; MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { hue=(double) (QuantumScale*q->red); saturation=(double) (QuantumScale*q->green); lightness=(double) (QuantumScale*q->blue); ConvertHSLToRGB(hue,saturation,lightness,&q->red,&q->green,&q->blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case HWBColorspace: { /* Transform image from HWB to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double blackness, hue, whiteness; MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { hue=(double) (QuantumScale*q->red); whiteness=(double) (QuantumScale*q->green); blackness=(double) (QuantumScale*q->blue); ConvertHWBToRGB(hue,whiteness,blackness,&q->red,&q->green,&q->blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case LabColorspace: { /* Transform image from Lab to RGB. */ if (image->storage_class == PseudoClass) { if (SyncImage(image) == MagickFalse) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); } image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { double a, b, L, X, Y, Z; MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } X=0.0; Y=0.0; Z=0.0; for (x=0; x < (long) image->columns; x++) { L=QuantumScale*q->red; a=QuantumScale*q->green; b=QuantumScale*q->blue; ConvertLabToXYZ(L,a,b,&X,&Y,&Z); ConvertXYZToRGB(X,Y,Z,&q->red,&q->green,&q->blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); image->colorspace=RGBColorspace; return(status); } case LogColorspace: { const char *value; double black, density, gamma, reference_black, reference_white; Quantum *logmap; /* Transform Log to RGB colorspace. */ density=2.03728; gamma=DisplayGamma; value=GetImageProperty(image,"gamma"); if (value != (const char *) NULL) gamma=1.0/atof(value) != 0.0 ? atof(value) : 1.0; reference_black=ReferenceBlack; value=GetImageProperty(image,"reference-black"); if (value != (const char *) NULL) reference_black=atof(value); reference_white=ReferenceWhite; value=GetImageProperty(image,"reference-white"); if (value != (const char *) NULL) reference_white=atof(value); logmap=(Quantum *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*logmap)); if (logmap == (Quantum *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); black=pow(10.0,(reference_black-reference_white)*(gamma/density)* 0.002/0.6); for (i=0; i <= (long) (reference_black*MaxMap/1024.0); i++) logmap[i]=(Quantum) 0; for ( ; i < (long) (reference_white*MaxMap/1024.0); i++) logmap[i]=RoundToQuantum((MagickRealType) QuantumRange/(1.0-black)* (pow(10.0,(1024.0*i/MaxMap-reference_white)* (gamma/density)*0.002/0.6)-black)); for ( ; i <= (long) MaxMap; i++) logmap[i]=(Quantum) QuantumRange; if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickBooleanType sync; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=(long) image->columns; x != 0; x--) { q->red=logmap[ScaleQuantumToMap(q->red)]; q->green=logmap[ScaleQuantumToMap(q->green)]; q->blue=logmap[ScaleQuantumToMap(q->blue)]; q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); logmap=(Quantum *) RelinquishMagickMemory(logmap); image->colorspace=RGBColorspace; return(status); } default: break; } /* Allocate the tables. */ x_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*x_map)); y_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*y_map)); z_map=(TransformPacket *) AcquireQuantumMemory((size_t) MaxMap+1UL, sizeof(*z_map)); if ((x_map == (TransformPacket *) NULL) || (y_map == (TransformPacket *) NULL) || (z_map == (TransformPacket *) NULL)) { if (z_map != (TransformPacket *) NULL) z_map=(TransformPacket *) RelinquishMagickMemory(z_map); if (y_map != (TransformPacket *) NULL) y_map=(TransformPacket *) RelinquishMagickMemory(y_map); if (x_map != (TransformPacket *) NULL) x_map=(TransformPacket *) RelinquishMagickMemory(x_map); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } switch (colorspace) { case OHTAColorspace: { /* Initialize OHTA tables: R = I1+1.00000*I2-0.66668*I3 G = I1+0.00000*I2+1.33333*I3 B = I1-1.00000*I2-0.66668*I3 I and Q, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.500000f*(2.000000*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].x=(-0.333340f)*(2.000000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=0.000000f; z_map[i].y=0.666665f*(2.000000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=(-0.500000f)*(2.000000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].z=(-0.333340f)*(2.000000f*(MagickRealType) i-(MagickRealType) MaxMap); } break; } case Rec601YCbCrColorspace: case YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.402000*Cr G = Y-0.344136*Cb-0.714136*Cr B = Y+1.772000*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.000000f; z_map[i].x=(1.402000f*0.500000f)*(2.000000f*(MagickRealType) i- (MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=(-0.344136f*0.500000f)*(2.000000f*(MagickRealType) i- (MagickRealType) MaxMap); z_map[i].y=(-0.714136f*0.500000f)*(2.000000f*(MagickRealType) i- (MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=(1.772000f*0.500000f)*(2.000000f*(MagickRealType) i- (MagickRealType) MaxMap); z_map[i].z=0.000000f; } break; } case Rec709YCbCrColorspace: { /* Initialize YCbCr tables: R = Y +1.574800*Cr G = Y-0.187324*Cb-0.468124*Cr B = Y+1.855600*Cb Cb and Cr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.000000f; z_map[i].x=(1.574800f*0.50000f)*(2.00000f*(MagickRealType) i- (MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=(-0.187324f*0.50000f)*(2.00000f*(MagickRealType) i- (MagickRealType) MaxMap); z_map[i].y=(-0.468124f*0.50000f)*(2.00000f*(MagickRealType) i- (MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=(1.855600f*0.50000f)*(2.00000f*(MagickRealType) i- (MagickRealType) MaxMap); z_map[i].z=0.00000f; } break; } case sRGBColorspace: { /* Nonlinear sRGB to linear RGB. R = 1.0*R+0.0*G+0.0*B G = 0.0*R+1.0*G+0.0*B B = 0.0*R+0.0*G+1.0*B */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=1.0f*(MagickRealType) i; y_map[i].x=0.0f*(MagickRealType) i; z_map[i].x=0.0f*(MagickRealType) i; x_map[i].y=0.0f*(MagickRealType) i; y_map[i].y=1.0f*(MagickRealType) i; z_map[i].y=0.0f*(MagickRealType) i; x_map[i].z=0.0f*(MagickRealType) i; y_map[i].z=0.0f*(MagickRealType) i; z_map[i].z=1.0f*(MagickRealType) i; } break; } case XYZColorspace: { /* Initialize CIE XYZ tables (ITU R-709 RGB): R = 3.2407100*X-1.5372600*Y-0.4985710*Z G = -0.9692580*X+1.8759900*Y+0.0415557*Z B = 0.0556352*X-0.2039960*Y+1.0570700*Z */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=3.2407100f*(MagickRealType) i; x_map[i].y=(-0.9692580f)*(MagickRealType) i; x_map[i].z=0.0556352f*(MagickRealType) i; y_map[i].x=(-1.5372600f)*(MagickRealType) i; y_map[i].y=1.8759900f*(MagickRealType) i; y_map[i].z=(-0.2039960f)*(MagickRealType) i; z_map[i].x=(-0.4985710f)*(MagickRealType) i; z_map[i].y=0.0415557f*(MagickRealType) i; z_map[i].z=1.0570700f*(MagickRealType) i; } break; } case YCCColorspace: { /* Initialize YCC tables: R = Y +1.340762*C2 G = Y-0.317038*C1-0.682243*C2 B = Y+1.632639*C1 YCC is scaled by 1.3584. C1 zero is 156 and C2 is at 137. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=1.3584000f*(MagickRealType) i; y_map[i].x=0.0000000f; z_map[i].x=1.8215000f*((MagickRealType) i-(MagickRealType) ScaleQuantumToMap(ScaleCharToQuantum(137))); x_map[i].y=1.3584000f*(MagickRealType) i; y_map[i].y=(-0.4302726f)*((MagickRealType) i-(MagickRealType) ScaleQuantumToMap(ScaleCharToQuantum(156))); z_map[i].y=(-0.9271435f)*((MagickRealType) i-(MagickRealType) ScaleQuantumToMap(ScaleCharToQuantum(137))); x_map[i].z=1.3584000f*(MagickRealType) i; y_map[i].z=2.2179000f*((MagickRealType) i-(MagickRealType) ScaleQuantumToMap(ScaleCharToQuantum(156))); z_map[i].z=0.0000000f; } break; } case YIQColorspace: { /* Initialize YIQ tables: R = Y+0.95620*I+0.62140*Q G = Y-0.27270*I-0.64680*Q B = Y-1.10370*I+1.70060*Q I and Q, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.47810f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].x=0.31070f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=(-0.13635f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].y=(-0.32340f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=(-0.55185f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].z=0.85030f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); } break; } case YPbPrColorspace: { /* Initialize YPbPr tables: R = Y +1.402000*C2 G = Y-0.344136*C1+0.714136*C2 B = Y+1.772000*C1 Pb and Pr, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.000000f; z_map[i].x=0.701000f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=(-0.172068f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].y=0.357068f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=0.88600f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].z=0.00000f; } break; } case YUVColorspace: default: { /* Initialize YUV tables: R = Y +1.13980*V G = Y-0.39380*U-0.58050*V B = Y+2.02790*U U and V, normally -0.5 through 0.5, must be normalized to the range 0 through QuantumRange. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) #endif for (i=0; i <= (long) MaxMap; i++) { x_map[i].x=(MagickRealType) i; y_map[i].x=0.00000f; z_map[i].x=0.56990f*(2.0000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].y=(MagickRealType) i; y_map[i].y=(-0.19690f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].y=(-0.29025f)*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); x_map[i].z=(MagickRealType) i; y_map[i].z=1.01395f*(2.00000f*(MagickRealType) i-(MagickRealType) MaxMap); z_map[i].z=0.00000f; } break; } } /* Convert to RGB. */ switch (image->storage_class) { case DirectClass: default: { /* Convert DirectClass image. */ image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (y=0; y < (long) image->rows; y++) { MagickBooleanType sync; MagickPixelPacket pixel; register long x; register PixelPacket *q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (long) image->columns; x++) { register unsigned long blue, green, red; red=ScaleQuantumToMap(q->red); green=ScaleQuantumToMap(q->green); blue=ScaleQuantumToMap(q->blue); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; switch (colorspace) { case YCCColorspace: { #if !defined(MAGICKCORE_HDRI_SUPPORT) pixel.red=(MagickRealType) ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.red)]); pixel.green=(MagickRealType) ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.green)]); pixel.blue=(MagickRealType) ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.blue)]); #endif break; } case sRGBColorspace: { if ((QuantumScale*pixel.red) <= 0.0031308) pixel.red*=12.92f; else pixel.red=(MagickRealType) QuantumRange*(1.055* pow(QuantumScale*pixel.red,(1.0/2.4))-0.055); if ((QuantumScale*pixel.green) <= 0.0031308) pixel.green*=12.92f; else pixel.green=(MagickRealType) QuantumRange*(1.055* pow(QuantumScale*pixel.green,(1.0/2.4))-0.055); if ((QuantumScale*pixel.blue) <= 0.0031308) pixel.blue*=12.92f; else pixel.blue=(MagickRealType) QuantumRange*(1.055* pow(QuantumScale*pixel.blue,(1.0/2.4))-0.055); break; } default: break; } q->red=ScaleMapToQuantum((MagickRealType) MaxMap*QuantumScale* pixel.red); q->green=ScaleMapToQuantum((MagickRealType) MaxMap*QuantumScale* pixel.green); q->blue=ScaleMapToQuantum((MagickRealType) MaxMap*QuantumScale* pixel.blue); q++; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical #endif proceed=SetImageProgress(image,TransformRGBImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); break; } case PseudoClass: { /* Convert PseudoClass image. */ image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(status) #endif for (i=0; i < (long) image->colors; i++) { MagickPixelPacket pixel; register unsigned long blue, green, red; red=ScaleQuantumToMap(image->colormap[i].red); green=ScaleQuantumToMap(image->colormap[i].green); blue=ScaleQuantumToMap(image->colormap[i].blue); pixel.red=x_map[red].x+y_map[green].x+z_map[blue].x; pixel.green=x_map[red].y+y_map[green].y+z_map[blue].y; pixel.blue=x_map[red].z+y_map[green].z+z_map[blue].z; switch (colorspace) { case YCCColorspace: { #if !defined(MAGICKCORE_HDRI_SUPPORT) image->colormap[i].red=ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.red)]); image->colormap[i].green=ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.green)]); image->colormap[i].blue=ScaleCharToQuantum(YCCMap[RoundToYCC( 255.0*QuantumScale*pixel.blue)]); #endif break; } case sRGBColorspace: { if ((QuantumScale*pixel.red) <= 0.0031308) pixel.red*=12.92f; else pixel.red=(MagickRealType) QuantumRange*(1.055*pow(QuantumScale* pixel.red,(1.0/2.4))-0.055); if ((QuantumScale*pixel.green) <= 0.0031308) pixel.green*=12.92f; else pixel.green=(MagickRealType) QuantumRange*(1.055*pow(QuantumScale* pixel.green,(1.0/2.4))-0.055); if ((QuantumScale*pixel.blue) <= 0.0031308) pixel.blue*=12.92f; else pixel.blue=(MagickRealType) QuantumRange*(1.055*pow(QuantumScale* pixel.blue,(1.0/2.4))-0.055); } default: { image->colormap[i].red=ScaleMapToQuantum((MagickRealType) MaxMap* QuantumScale*pixel.red); image->colormap[i].green=ScaleMapToQuantum((MagickRealType) MaxMap* QuantumScale*pixel.green); image->colormap[i].blue=ScaleMapToQuantum((MagickRealType) MaxMap* QuantumScale*pixel.blue); break; } } } image_view=DestroyCacheView(image_view); (void) SyncImage(image); break; } } /* Relinquish resources. */ z_map=(TransformPacket *) RelinquishMagickMemory(z_map); y_map=(TransformPacket *) RelinquishMagickMemory(y_map); x_map=(TransformPacket *) RelinquishMagickMemory(x_map); image->colorspace=RGBColorspace; return(MagickTrue); }
OpenMPClause.h
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- 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 // //===----------------------------------------------------------------------===// // /// \file /// This file defines OpenMP AST classes for clauses. /// There are clauses for executable directives, clauses for declarative /// directives and clauses which can be used in both kinds of directives. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H #define LLVM_CLANG_AST_OPENMPCLAUSE_H #include "clang/AST/ASTFwd.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/TrailingObjects.h" #include <cassert> #include <cstddef> #include <iterator> #include <utility> namespace clang { class ASTContext; //===----------------------------------------------------------------------===// // AST classes for clauses. //===----------------------------------------------------------------------===// /// This is a basic class for representing single OpenMP clause. class OMPClause { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Ending location of the clause. SourceLocation EndLoc; /// Kind of the clause. OpenMPClauseKind Kind; protected: OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc) : StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {} public: /// Returns the starting location of the clause. SourceLocation getBeginLoc() const { return StartLoc; } /// Returns the ending location of the clause. SourceLocation getEndLoc() const { return EndLoc; } /// Sets the starting location of the clause. void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// Sets the ending location of the clause. void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// Returns kind of OpenMP clause (private, shared, reduction, etc.). OpenMPClauseKind getClauseKind() const { return Kind; } bool isImplicit() const { return StartLoc.isInvalid(); } using child_iterator = StmtIterator; using const_child_iterator = ConstStmtIterator; using child_range = llvm::iterator_range<child_iterator>; using const_child_range = llvm::iterator_range<const_child_iterator>; child_range children(); const_child_range children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } /// Get the iterator range for the expressions used in the clauses. Used /// expressions include only the children that must be evaluated at the /// runtime before entering the construct. child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *) { return true; } }; /// Class that handles pre-initialization statement for some clauses, like /// 'shedule', 'firstprivate' etc. class OMPClauseWithPreInit { friend class OMPClauseReader; /// Pre-initialization statement for the clause. Stmt *PreInit = nullptr; /// Region that captures the associated stmt. OpenMPDirectiveKind CaptureRegion = llvm::omp::OMPD_unknown; protected: OMPClauseWithPreInit(const OMPClause *This) { assert(get(This) && "get is not tuned for pre-init."); } /// Set pre-initialization statement for the clause. void setPreInitStmt(Stmt *S, OpenMPDirectiveKind ThisRegion = llvm::omp::OMPD_unknown) { PreInit = S; CaptureRegion = ThisRegion; } public: /// Get pre-initialization statement for the clause. const Stmt *getPreInitStmt() const { return PreInit; } /// Get pre-initialization statement for the clause. Stmt *getPreInitStmt() { return PreInit; } /// Get capture region for the stmt in the clause. OpenMPDirectiveKind getCaptureRegion() const { return CaptureRegion; } static OMPClauseWithPreInit *get(OMPClause *C); static const OMPClauseWithPreInit *get(const OMPClause *C); }; /// Class that handles post-update expression for some clauses, like /// 'lastprivate', 'reduction' etc. class OMPClauseWithPostUpdate : public OMPClauseWithPreInit { friend class OMPClauseReader; /// Post-update expression for the clause. Expr *PostUpdate = nullptr; protected: OMPClauseWithPostUpdate(const OMPClause *This) : OMPClauseWithPreInit(This) { assert(get(This) && "get is not tuned for post-update."); } /// Set pre-initialization statement for the clause. void setPostUpdateExpr(Expr *S) { PostUpdate = S; } public: /// Get post-update expression for the clause. const Expr *getPostUpdateExpr() const { return PostUpdate; } /// Get post-update expression for the clause. Expr *getPostUpdateExpr() { return PostUpdate; } static OMPClauseWithPostUpdate *get(OMPClause *C); static const OMPClauseWithPostUpdate *get(const OMPClause *C); }; /// This structure contains most locations needed for by an OMPVarListClause. struct OMPVarListLocTy { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Location of '('. SourceLocation LParenLoc; /// Ending location of the clause. SourceLocation EndLoc; OMPVarListLocTy() = default; OMPVarListLocTy(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : StartLoc(StartLoc), LParenLoc(LParenLoc), EndLoc(EndLoc) {} }; /// This represents clauses with the list of variables like 'private', /// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the /// '#pragma omp ...' directives. template <class T> class OMPVarListClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of variables in the list. unsigned NumVars; protected: /// Build a clause with \a N variables /// /// \param K Kind of the clause. /// \param StartLoc Starting location of the clause (the clause keyword). /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {} /// Fetches list of variables associated with this clause. MutableArrayRef<Expr *> getVarRefs() { return MutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } /// Sets the list of variables for this clause. void setVarRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::copy(VL.begin(), VL.end(), static_cast<T *>(this)->template getTrailingObjects<Expr *>()); } public: using varlist_iterator = MutableArrayRef<Expr *>::iterator; using varlist_const_iterator = ArrayRef<const Expr *>::iterator; using varlist_range = llvm::iterator_range<varlist_iterator>; using varlist_const_range = llvm::iterator_range<varlist_const_iterator>; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_range varlists() { return varlist_range(varlist_begin(), varlist_end()); } varlist_const_range varlists() const { return varlist_const_range(varlist_begin(), varlist_end()); } varlist_iterator varlist_begin() { return getVarRefs().begin(); } varlist_iterator varlist_end() { return getVarRefs().end(); } varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); } varlist_const_iterator varlist_end() const { return getVarRefs().end(); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Fetches list of all variables in the clause. ArrayRef<const Expr *> getVarRefs() const { return llvm::makeArrayRef( static_cast<const T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } }; /// This represents 'allocator' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp allocate(a) allocator(omp_default_mem_alloc) /// \endcode /// In this example directive '#pragma omp allocate' has simple 'allocator' /// clause with the allocator 'omp_default_mem_alloc'. class OMPAllocatorClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression with the allocator. Stmt *Allocator = nullptr; /// Set allocator. void setAllocator(Expr *A) { Allocator = A; } public: /// Build 'allocator' clause with the given allocator. /// /// \param A Allocator. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAllocatorClause(Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_allocator, StartLoc, EndLoc), LParenLoc(LParenLoc), Allocator(A) {} /// Build an empty clause. OMPAllocatorClause() : OMPClause(llvm::omp::OMPC_allocator, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns allocator. Expr *getAllocator() const { return cast_or_null<Expr>(Allocator); } child_range children() { return child_range(&Allocator, &Allocator + 1); } const_child_range children() const { return const_child_range(&Allocator, &Allocator + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocator; } }; /// This represents clause 'allocate' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a) allocate(omp_default_mem_alloc :a) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// and clause 'allocate' for the variable 'a'. class OMPAllocateClause final : public OMPVarListClause<OMPAllocateClause>, private llvm::TrailingObjects<OMPAllocateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Allocator specified in the clause, or 'nullptr' if the default one is /// used. Expr *Allocator = nullptr; /// Position of the ':' delimiter in the clause; SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPAllocateClause(SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, StartLoc, LParenLoc, EndLoc, N), Allocator(Allocator), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPAllocateClause(unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } void setAllocator(Expr *A) { Allocator = A; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPAllocateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Returns the allocator expression or nullptr, if no allocator is specified. Expr *getAllocator() const { return Allocator; } /// Returns the location of the ':' delimiter. SourceLocation getColonLoc() const { return ColonLoc; } /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPAllocateClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAllocateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocate; } }; /// This represents 'if' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel if(parallel:a > 5) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'if' clause with /// condition 'a > 5' and directive name modifier 'parallel'. class OMPIfClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Location of ':' (if any). SourceLocation ColonLoc; /// Directive name modifier for the clause. OpenMPDirectiveKind NameModifier = llvm::omp::OMPD_unknown; /// Name modifier location. SourceLocation NameModifierLoc; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } /// Set directive name modifier for the clause. void setNameModifier(OpenMPDirectiveKind NM) { NameModifier = NM; } /// Set location of directive name modifier for the clause. void setNameModifierLoc(SourceLocation Loc) { NameModifierLoc = Loc; } /// Set location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Build 'if' clause with condition \a Cond. /// /// \param NameModifier [OpenMP 4.1] Directive name modifier of clause. /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param NameModifierLoc Location of directive name modifier. /// \param ColonLoc [OpenMP 4.1] Location of ':'. /// \param EndLoc Ending location of the clause. OMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_if, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond), ColonLoc(ColonLoc), NameModifier(NameModifier), NameModifierLoc(NameModifierLoc) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPIfClause() : OMPClause(llvm::omp::OMPC_if, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } /// Return directive name modifier associated with the clause. OpenMPDirectiveKind getNameModifier() const { return NameModifier; } /// Return the location of directive name modifier. SourceLocation getNameModifierLoc() const { return NameModifierLoc; } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPIfClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_if; } }; /// This represents 'final' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task final(a > 5) /// \endcode /// In this example directive '#pragma omp task' has simple 'final' /// clause with condition 'a > 5'. class OMPFinalClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } public: /// Build 'final' clause with condition \a Cond. /// /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPFinalClause(Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_final, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPFinalClause() : OMPClause(llvm::omp::OMPC_final, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPFinalClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_final; } }; /// This represents 'num_threads' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel num_threads(6) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'num_threads' /// clause with number of threads '6'. class OMPNumThreadsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'num_threads' clause. Stmt *NumThreads = nullptr; /// Set condition. void setNumThreads(Expr *NThreads) { NumThreads = NThreads; } public: /// Build 'num_threads' clause with condition \a NumThreads. /// /// \param NumThreads Number of threads for the construct. /// \param HelperNumThreads Helper Number of threads for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumThreadsClause(Expr *NumThreads, Stmt *HelperNumThreads, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_threads, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumThreads(NumThreads) { setPreInitStmt(HelperNumThreads, CaptureRegion); } /// Build an empty clause. OMPNumThreadsClause() : OMPClause(llvm::omp::OMPC_num_threads, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); } child_range children() { return child_range(&NumThreads, &NumThreads + 1); } const_child_range children() const { return const_child_range(&NumThreads, &NumThreads + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_threads; } }; /// This represents 'safelen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd safelen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'safelen' /// with single expression '4'. /// If the safelen clause is used then no two iterations executed /// concurrently with SIMD instructions can have a greater distance /// in the logical iteration space than its value. The parameter of /// the safelen clause must be a constant positive integer expression. class OMPSafelenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Safelen = nullptr; /// Set safelen. void setSafelen(Expr *Len) { Safelen = Len; } public: /// Build 'safelen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// Build an empty clause. explicit OMPSafelenClause() : OMPClause(llvm::omp::OMPC_safelen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); } child_range children() { return child_range(&Safelen, &Safelen + 1); } const_child_range children() const { return const_child_range(&Safelen, &Safelen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_safelen; } }; /// This represents 'simdlen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd simdlen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'simdlen' /// with single expression '4'. /// If the 'simdlen' clause is used then it specifies the preferred number of /// iterations to be executed concurrently. The parameter of the 'simdlen' /// clause must be a constant positive integer expression. class OMPSimdlenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Simdlen = nullptr; /// Set simdlen. void setSimdlen(Expr *Len) { Simdlen = Len; } public: /// Build 'simdlen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simdlen, StartLoc, EndLoc), LParenLoc(LParenLoc), Simdlen(Len) {} /// Build an empty clause. explicit OMPSimdlenClause() : OMPClause(llvm::omp::OMPC_simdlen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSimdlen() const { return cast_or_null<Expr>(Simdlen); } child_range children() { return child_range(&Simdlen, &Simdlen + 1); } const_child_range children() const { return const_child_range(&Simdlen, &Simdlen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simdlen; } }; /// This represents the 'sizes' clause in the '#pragma omp tile' directive. /// /// \code /// #pragma omp tile sizes(5,5) /// for (int i = 0; i < 64; ++i) /// for (int j = 0; j < 64; ++j) /// \endcode class OMPSizesClause final : public OMPClause, private llvm::TrailingObjects<OMPSizesClause, Expr *> { friend class OMPClauseReader; friend class llvm::TrailingObjects<OMPSizesClause, Expr *>; /// Location of '('. SourceLocation LParenLoc; /// Number of tile sizes in the clause. unsigned NumSizes; /// Build an empty clause. explicit OMPSizesClause(int NumSizes) : OMPClause(llvm::omp::OMPC_sizes, SourceLocation(), SourceLocation()), NumSizes(NumSizes) {} public: /// Build a 'sizes' AST node. /// /// \param C Context of the AST. /// \param StartLoc Location of the 'sizes' identifier. /// \param LParenLoc Location of '('. /// \param EndLoc Location of ')'. /// \param Sizes Content of the clause. static OMPSizesClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> Sizes); /// Build an empty 'sizes' AST node for deserialization. /// /// \param C Context of the AST. /// \param NumSizes Number of items in the clause. static OMPSizesClause *CreateEmpty(const ASTContext &C, unsigned NumSizes); /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns the number of list items. unsigned getNumSizes() const { return NumSizes; } /// Returns the tile size expressions. MutableArrayRef<Expr *> getSizesRefs() { return MutableArrayRef<Expr *>(static_cast<OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>(), NumSizes); } ArrayRef<Expr *> getSizesRefs() const { return ArrayRef<Expr *>(static_cast<const OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>(), NumSizes); } /// Sets the tile size expressions. void setSizesRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumSizes); std::copy(VL.begin(), VL.end(), static_cast<OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>()); } child_range children() { MutableArrayRef<Expr *> Sizes = getSizesRefs(); return child_range(reinterpret_cast<Stmt **>(Sizes.begin()), reinterpret_cast<Stmt **>(Sizes.end())); } const_child_range children() const { ArrayRef<Expr *> Sizes = getSizesRefs(); return const_child_range(reinterpret_cast<Stmt *const *>(Sizes.begin()), reinterpret_cast<Stmt *const *>(Sizes.end())); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_sizes; } }; /// This represents 'collapse' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd collapse(3) /// \endcode /// In this example directive '#pragma omp simd' has clause 'collapse' /// with single expression '3'. /// The parameter must be a constant positive integer expression, it specifies /// the number of nested loops that should be collapsed into a single iteration /// space. class OMPCollapseClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'collapse' clause. /// /// \param Num Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPCollapseClause(Expr *Num, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// Build an empty clause. explicit OMPCollapseClause() : OMPClause(llvm::omp::OMPC_collapse, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_collapse; } }; /// This represents 'default' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel default(shared) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'default' /// clause with kind 'shared'. class OMPDefaultClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. llvm::omp::DefaultKind Kind = llvm::omp::OMP_DEFAULT_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clauses. /// /// \param K Argument of clause. void setDefaultKind(llvm::omp::DefaultKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'default' clause with argument \a A ('none' or 'shared'). /// /// \param A Argument of the clause ('none' or 'shared'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDefaultClause(llvm::omp::DefaultKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPDefaultClause() : OMPClause(llvm::omp::OMPC_default, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::DefaultKind getDefaultKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_default; } }; /// This represents 'proc_bind' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel proc_bind(master) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'proc_bind' /// clause with kind 'master'. class OMPProcBindClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'proc_bind' clause. llvm::omp::ProcBindKind Kind = llvm::omp::OMP_PROC_BIND_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setProcBindKind(llvm::omp::ProcBindKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'proc_bind' clause with argument \a A ('master', 'close' or /// 'spread'). /// /// \param A Argument of the clause ('master', 'close' or 'spread'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPProcBindClause(llvm::omp::ProcBindKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPProcBindClause() : OMPClause(llvm::omp::OMPC_proc_bind, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::ProcBindKind getProcBindKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_proc_bind; } }; /// This represents 'unified_address' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_address /// \endcode /// In this example directive '#pragma omp requires' has 'unified_address' /// clause. class OMPUnifiedAddressClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_address' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_address, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedAddressClause() : OMPClause(llvm::omp::OMPC_unified_address, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_address; } }; /// This represents 'unified_shared_memory' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_shared_memory /// \endcode /// In this example directive '#pragma omp requires' has 'unified_shared_memory' /// clause. class OMPUnifiedSharedMemoryClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_shared_memory' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_shared_memory, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedSharedMemoryClause() : OMPClause(llvm::omp::OMPC_unified_shared_memory, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_shared_memory; } }; /// This represents 'reverse_offload' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires reverse_offload /// \endcode /// In this example directive '#pragma omp requires' has 'reverse_offload' /// clause. class OMPReverseOffloadClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'reverse_offload' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_reverse_offload, StartLoc, EndLoc) {} /// Build an empty clause. OMPReverseOffloadClause() : OMPClause(llvm::omp::OMPC_reverse_offload, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reverse_offload; } }; /// This represents 'dynamic_allocators' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires dynamic_allocators /// \endcode /// In this example directive '#pragma omp requires' has 'dynamic_allocators' /// clause. class OMPDynamicAllocatorsClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'dynamic_allocators' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_dynamic_allocators, StartLoc, EndLoc) {} /// Build an empty clause. OMPDynamicAllocatorsClause() : OMPClause(llvm::omp::OMPC_dynamic_allocators, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dynamic_allocators; } }; /// This represents 'atomic_default_mem_order' clause in the '#pragma omp /// requires' directive. /// /// \code /// #pragma omp requires atomic_default_mem_order(seq_cst) /// \endcode /// In this example directive '#pragma omp requires' has simple /// atomic_default_mem_order' clause with kind 'seq_cst'. class OMPAtomicDefaultMemOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '(' SourceLocation LParenLoc; /// A kind of the 'atomic_default_mem_order' clause. OpenMPAtomicDefaultMemOrderClauseKind Kind = OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setAtomicDefaultMemOrderKind(OpenMPAtomicDefaultMemOrderClauseKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setAtomicDefaultMemOrderKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'atomic_default_mem_order' clause with argument \a A ('seq_cst', /// 'acq_rel' or 'relaxed'). /// /// \param A Argument of the clause ('seq_cst', 'acq_rel' or 'relaxed'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAtomicDefaultMemOrderClause(OpenMPAtomicDefaultMemOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPAtomicDefaultMemOrderClause() : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the locaiton of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPAtomicDefaultMemOrderClauseKind getAtomicDefaultMemOrderKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getAtomicDefaultMemOrderKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_atomic_default_mem_order; } }; /// This represents 'schedule' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for schedule(static, 3) /// \endcode /// In this example directive '#pragma omp for' has 'schedule' clause with /// arguments 'static' and '3'. class OMPScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPScheduleClauseKind Kind = OMPC_SCHEDULE_unknown; /// Modifiers for 'schedule' clause. enum {FIRST, SECOND, NUM_MODIFIERS}; OpenMPScheduleClauseModifier Modifiers[NUM_MODIFIERS]; /// Locations of modifiers. SourceLocation ModifiersLoc[NUM_MODIFIERS]; /// Start location of the schedule ind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; } /// Set the first schedule modifier. /// /// \param M Schedule modifier. void setFirstScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[FIRST] = M; } /// Set the second schedule modifier. /// /// \param M Schedule modifier. void setSecondScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[SECOND] = M; } /// Set location of the first schedule modifier. void setFirstScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[FIRST] = Loc; } /// Set location of the second schedule modifier. void setSecondScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[SECOND] = Loc; } /// Set schedule modifier location. /// /// \param M Schedule modifier location. void setScheduleModifer(OpenMPScheduleClauseModifier M) { if (Modifiers[FIRST] == OMPC_SCHEDULE_MODIFIER_unknown) Modifiers[FIRST] = M; else { assert(Modifiers[SECOND] == OMPC_SCHEDULE_MODIFIER_unknown); Modifiers[SECOND] = M; } } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'schedule' clause with schedule kind \a Kind and chunk size /// expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind Schedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. /// \param M1 The first modifier applied to 'schedule' clause. /// \param M1Loc Location of the first modifier /// \param M2 The second modifier applied to 'schedule' clause. /// \param M2Loc Location of the second modifier OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize, OpenMPScheduleClauseModifier M1, SourceLocation M1Loc, OpenMPScheduleClauseModifier M2, SourceLocation M2Loc) : OMPClause(llvm::omp::OMPC_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); Modifiers[FIRST] = M1; Modifiers[SECOND] = M2; ModifiersLoc[FIRST] = M1Loc; ModifiersLoc[SECOND] = M2Loc; } /// Build an empty clause. explicit OMPScheduleClause() : OMPClause(llvm::omp::OMPC_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) { Modifiers[FIRST] = OMPC_SCHEDULE_MODIFIER_unknown; Modifiers[SECOND] = OMPC_SCHEDULE_MODIFIER_unknown; } /// Get kind of the clause. OpenMPScheduleClauseKind getScheduleKind() const { return Kind; } /// Get the first modifier of the clause. OpenMPScheduleClauseModifier getFirstScheduleModifier() const { return Modifiers[FIRST]; } /// Get the second modifier of the clause. OpenMPScheduleClauseModifier getSecondScheduleModifier() const { return Modifiers[SECOND]; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getScheduleKindLoc() { return KindLoc; } /// Get the first modifier location. SourceLocation getFirstScheduleModifierLoc() const { return ModifiersLoc[FIRST]; } /// Get the second modifier location. SourceLocation getSecondScheduleModifierLoc() const { return ModifiersLoc[SECOND]; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_schedule; } }; /// This represents 'ordered' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for ordered (2) /// \endcode /// In this example directive '#pragma omp for' has 'ordered' clause with /// parameter 2. class OMPOrderedClause final : public OMPClause, private llvm::TrailingObjects<OMPOrderedClause, Expr *> { friend class OMPClauseReader; friend TrailingObjects; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Real number of loops. unsigned NumberOfLoops = 0; /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderedClause(Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_ordered, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num), NumberOfLoops(NumLoops) {} /// Build an empty clause. explicit OMPOrderedClause(unsigned NumLoops) : OMPClause(llvm::omp::OMPC_ordered, SourceLocation(), SourceLocation()), NumberOfLoops(NumLoops) {} /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. static OMPOrderedClause *Create(const ASTContext &C, Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Build an empty clause. static OMPOrderedClause* CreateEmpty(const ASTContext &C, unsigned NumLoops); /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } /// Set number of iterations for the specified loop. void setLoopNumIterations(unsigned NumLoop, Expr *NumIterations); /// Get number of iterations for all the loops. ArrayRef<Expr *> getLoopNumIterations() const; /// Set loop counter for the specified loop. void setLoopCounter(unsigned NumLoop, Expr *Counter); /// Get loops counter for the specified loop. Expr *getLoopCounter(unsigned NumLoop); const Expr *getLoopCounter(unsigned NumLoop) const; child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_ordered; } }; /// This represents 'nowait' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for nowait /// \endcode /// In this example directive '#pragma omp for' has 'nowait' clause. class OMPNowaitClause : public OMPClause { public: /// Build 'nowait' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc) {} /// Build an empty clause. OMPNowaitClause() : OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nowait; } }; /// This represents 'untied' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task untied /// \endcode /// In this example directive '#pragma omp task' has 'untied' clause. class OMPUntiedClause : public OMPClause { public: /// Build 'untied' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_untied, StartLoc, EndLoc) {} /// Build an empty clause. OMPUntiedClause() : OMPClause(llvm::omp::OMPC_untied, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_untied; } }; /// This represents 'mergeable' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task mergeable /// \endcode /// In this example directive '#pragma omp task' has 'mergeable' clause. class OMPMergeableClause : public OMPClause { public: /// Build 'mergeable' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_mergeable, StartLoc, EndLoc) {} /// Build an empty clause. OMPMergeableClause() : OMPClause(llvm::omp::OMPC_mergeable, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_mergeable; } }; /// This represents 'read' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic read /// \endcode /// In this example directive '#pragma omp atomic' has 'read' clause. class OMPReadClause : public OMPClause { public: /// Build 'read' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_read, StartLoc, EndLoc) {} /// Build an empty clause. OMPReadClause() : OMPClause(llvm::omp::OMPC_read, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_read; } }; /// This represents 'write' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic write /// \endcode /// In this example directive '#pragma omp atomic' has 'write' clause. class OMPWriteClause : public OMPClause { public: /// Build 'write' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_write, StartLoc, EndLoc) {} /// Build an empty clause. OMPWriteClause() : OMPClause(llvm::omp::OMPC_write, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_write; } }; /// This represents 'update' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic update /// \endcode /// In this example directive '#pragma omp atomic' has 'update' clause. /// Also, this class represents 'update' clause in '#pragma omp depobj' /// directive. /// /// \code /// #pragma omp depobj(a) update(in) /// \endcode /// In this example directive '#pragma omp depobj' has 'update' clause with 'in' /// dependence kind. class OMPUpdateClause final : public OMPClause, private llvm::TrailingObjects<OMPUpdateClause, SourceLocation, OpenMPDependClauseKind> { friend class OMPClauseReader; friend TrailingObjects; /// true if extended version of the clause for 'depobj' directive. bool IsExtended = false; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<SourceLocation>) const { // 2 locations: for '(' and argument location. return IsExtended ? 2 : 0; } /// Sets the the location of '(' in clause for 'depobj' directive. void setLParenLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<SourceLocation>() = Loc; } /// Sets the the location of '(' in clause for 'depobj' directive. void setArgumentLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *std::next(getTrailingObjects<SourceLocation>(), 1) = Loc; } /// Sets the dependence kind for the clause for 'depobj' directive. void setDependencyKind(OpenMPDependClauseKind DK) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<OpenMPDependClauseKind>() = DK; } /// Build 'update' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc, bool IsExtended) : OMPClause(llvm::omp::OMPC_update, StartLoc, EndLoc), IsExtended(IsExtended) {} /// Build an empty clause. OMPUpdateClause(bool IsExtended) : OMPClause(llvm::omp::OMPC_update, SourceLocation(), SourceLocation()), IsExtended(IsExtended) {} public: /// Creates clause for 'atomic' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates clause for 'depobj' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ArgumentLoc Location of the argument. /// \param DK Dependence kind. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ArgumentLoc, OpenMPDependClauseKind DK, SourceLocation EndLoc); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param IsExtended true if extended clause for 'depobj' directive must be /// created. static OMPUpdateClause *CreateEmpty(const ASTContext &C, bool IsExtended); /// Checks if the clause is the extended clauses for 'depobj' directive. bool isExtended() const { return IsExtended; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } /// Gets the the location of '(' in clause for 'depobj' directive. SourceLocation getLParenLoc() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<SourceLocation>(); } /// Gets the the location of argument in clause for 'depobj' directive. SourceLocation getArgumentLoc() const { assert(IsExtended && "Expected extended clause."); return *std::next(getTrailingObjects<SourceLocation>(), 1); } /// Gets the dependence kind in clause for 'depobj' directive. OpenMPDependClauseKind getDependencyKind() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<OpenMPDependClauseKind>(); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_update; } }; /// This represents 'capture' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has 'capture' clause. class OMPCaptureClause : public OMPClause { public: /// Build 'capture' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_capture, StartLoc, EndLoc) {} /// Build an empty clause. OMPCaptureClause() : OMPClause(llvm::omp::OMPC_capture, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_capture; } }; /// This represents 'seq_cst' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic seq_cst /// \endcode /// In this example directive '#pragma omp atomic' has 'seq_cst' clause. class OMPSeqCstClause : public OMPClause { public: /// Build 'seq_cst' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_seq_cst, StartLoc, EndLoc) {} /// Build an empty clause. OMPSeqCstClause() : OMPClause(llvm::omp::OMPC_seq_cst, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_seq_cst; } }; /// This represents 'acq_rel' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acq_rel /// \endcode /// In this example directive '#pragma omp flush' has 'acq_rel' clause. class OMPAcqRelClause final : public OMPClause { public: /// Build 'ack_rel' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acq_rel, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcqRelClause() : OMPClause(llvm::omp::OMPC_acq_rel, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acq_rel; } }; /// This represents 'acquire' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acquire /// \endcode /// In this example directive '#pragma omp flush' has 'acquire' clause. class OMPAcquireClause final : public OMPClause { public: /// Build 'acquire' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acquire, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcquireClause() : OMPClause(llvm::omp::OMPC_acquire, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acquire; } }; /// This represents 'release' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush release /// \endcode /// In this example directive '#pragma omp flush' has 'release' clause. class OMPReleaseClause final : public OMPClause { public: /// Build 'release' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_release, StartLoc, EndLoc) {} /// Build an empty clause. OMPReleaseClause() : OMPClause(llvm::omp::OMPC_release, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_release; } }; /// This represents 'relaxed' clause in the '#pragma omp atomic' /// directives. /// /// \code /// #pragma omp atomic relaxed /// \endcode /// In this example directive '#pragma omp atomic' has 'relaxed' clause. class OMPRelaxedClause final : public OMPClause { public: /// Build 'relaxed' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_relaxed, StartLoc, EndLoc) {} /// Build an empty clause. OMPRelaxedClause() : OMPClause(llvm::omp::OMPC_relaxed, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_relaxed; } }; /// This represents clause 'private' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// with the variables 'a' and 'b'. class OMPPrivateClause final : public OMPVarListClause<OMPPrivateClause>, private llvm::TrailingObjects<OMPPrivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PrivateVL List of references to private copies with initializers. static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPPrivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_private; } }; /// This represents clause 'firstprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel firstprivate(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'firstprivate' /// with the variables 'a' and 'b'. class OMPFirstprivateClause final : public OMPVarListClause<OMPFirstprivateClause>, public OMPClauseWithPreInit, private llvm::TrailingObjects<OMPFirstprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFirstprivateClause>(llvm::omp::OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPreInit(this) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( llvm::omp::OMPC_firstprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPreInit(this) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new /// private variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new /// private variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. /// \param PrivateVL List of references to private copies with initializers. /// \param InitVL List of references to auto generated variables used for /// initialization of a single array element. Used if firstprivate variable is /// of array type. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. static OMPFirstprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL, ArrayRef<Expr *> InitVL, Stmt *PreInit); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_firstprivate; } }; /// This represents clause 'lastprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd lastprivate(a,b) /// \endcode /// In this example directive '#pragma omp simd' has clause 'lastprivate' /// with the variables 'a' and 'b'. class OMPLastprivateClause final : public OMPVarListClause<OMPLastprivateClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLastprivateClause, Expr *> { // There are 4 additional tail-allocated arrays at the end of the class: // 1. Contains list of pseudo variables with the default initialization for // each non-firstprivate variables. Used in codegen for initialization of // lastprivate copies. // 2. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents private variables // (for arrays, single array element). // 3. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents original variables // (for arrays, single array element). // 4. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of final assignment performed by the // lastprivate clause. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Optional lastprivate kind, e.g. 'conditional', if specified by user. OpenMPLastprivateModifier LPKind; /// Optional location of the lasptrivate kind, if specified by user. SourceLocation LPKindLoc; /// Optional colon location, if specified by user. SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, unsigned N) : OMPVarListClause<OMPLastprivateClause>(llvm::omp::OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), LPKind(LPKind), LPKindLoc(LPKindLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( llvm::omp::OMPC_lastprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Get the list of helper expressions for initialization of private /// copies for lastprivate variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent original variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign private copy of the variable to original variable. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } /// Sets lastprivate kind. void setKind(OpenMPLastprivateModifier Kind) { LPKind = Kind; } /// Sets location of the lastprivate kind. void setKindLoc(SourceLocation Loc) { LPKindLoc = Loc; } /// Sets colon symbol location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// private variables (for arrays, single array element). /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// original variables (for arrays, single array element). /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// lastprivate clause. /// \param LPKind Lastprivate kind, e.g. 'conditional'. /// \param LPKindLoc Location of the lastprivate kind. /// \param ColonLoc Location of the ':' symbol if lastprivate kind is used. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLastprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N); /// Lastprivate kind. OpenMPLastprivateModifier getKind() const { return LPKind; } /// Returns the location of the lastprivate kind. SourceLocation getKindLoc() const { return LPKindLoc; } /// Returns the location of the ':' symbol, if any. SourceLocation getColonLoc() const { return ColonLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; /// Set list of helper expressions, required for generation of private /// copies of original lastprivate variables. void setPrivateCopies(ArrayRef<Expr *> PrivateCopies); helper_expr_const_range private_copies() const { return helper_expr_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_range private_copies() { return helper_expr_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLastprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_lastprivate; } }; /// This represents clause 'shared' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel shared(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'shared' /// with the variables 'a' and 'b'. class OMPSharedClause final : public OMPVarListClause<OMPSharedClause>, private llvm::TrailingObjects<OMPSharedClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPSharedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_shared; } }; /// This represents clause 'reduction' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'reduction' /// with operator '+' and the variables 'a' and 'b'. class OMPReductionClause final : public OMPVarListClause<OMPReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Reduction modifier. OpenMPReductionClauseModifier Modifier = OMPC_REDUCTION_unknown; /// Reduction modifier location. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets reduction modifier. void setModifier(OpenMPReductionClauseModifier M) { Modifier = M; } /// Sets location of the modifier. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private copy of the reduction /// variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent LHS expression in the final /// reduction expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent RHS expression in the final /// reduction expression performed by the reduction clause. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } /// Set list of helper copy operations for inscan reductions. /// The form is: Temps[i] = LHS[i]; void setInscanCopyOps(ArrayRef<Expr *> Ops); /// Get the list of helper inscan copy operations. MutableArrayRef<Expr *> getInscanCopyOps() { return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyOps() const { return llvm::makeArrayRef(getReductionOps().end(), varlist_size()); } /// Set list of helper temp vars for inscan copy array operations. void setInscanCopyArrayTemps(ArrayRef<Expr *> CopyArrayTemps); /// Get the list of helper inscan copy temps. MutableArrayRef<Expr *> getInscanCopyArrayTemps() { return MutableArrayRef<Expr *>(getInscanCopyOps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyArrayTemps() const { return llvm::makeArrayRef(getInscanCopyOps().end(), varlist_size()); } /// Set list of helper temp elements vars for inscan copy array operations. void setInscanCopyArrayElems(ArrayRef<Expr *> CopyArrayElems); /// Get the list of helper inscan copy temps. MutableArrayRef<Expr *> getInscanCopyArrayElems() { return MutableArrayRef<Expr *>(getInscanCopyArrayTemps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyArrayElems() const { return llvm::makeArrayRef(getInscanCopyArrayTemps().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param CopyOps List of copy operations for inscan reductions: /// \code /// TempExprs = LHSExprs; /// \endcode /// \param CopyArrayTemps Temp arrays for prefix sums. /// \param CopyArrayElems Temp arrays for prefix sums. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> CopyOps, ArrayRef<Expr *> CopyArrayTemps, ArrayRef<Expr *> CopyArrayElems, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// \param Modifier Reduction modifier. static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier); /// Returns modifier. OpenMPReductionClauseModifier getModifier() const { return Modifier; } /// Returns modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_const_range copy_ops() const { return helper_expr_const_range(getInscanCopyOps().begin(), getInscanCopyOps().end()); } helper_expr_range copy_ops() { return helper_expr_range(getInscanCopyOps().begin(), getInscanCopyOps().end()); } helper_expr_const_range copy_array_temps() const { return helper_expr_const_range(getInscanCopyArrayTemps().begin(), getInscanCopyArrayTemps().end()); } helper_expr_range copy_array_temps() { return helper_expr_range(getInscanCopyArrayTemps().begin(), getInscanCopyArrayTemps().end()); } helper_expr_const_range copy_array_elems() const { return helper_expr_const_range(getInscanCopyArrayElems().begin(), getInscanCopyArrayElems().end()); } helper_expr_range copy_array_elems() { return helper_expr_range(getInscanCopyArrayElems().begin(), getInscanCopyArrayElems().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPReductionClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reduction; } }; /// This represents clause 'task_reduction' in the '#pragma omp taskgroup' /// directives. /// /// \code /// #pragma omp taskgroup task_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp taskgroup' has clause /// 'task_reduction' with operator '+' and the variables 'a' and 'b'. class OMPTaskReductionClause final : public OMPVarListClause<OMPTaskReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPTaskReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPTaskReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPTaskReductionClause(unsigned N) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPTaskReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPTaskReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPTaskReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_task_reduction; } }; /// This represents clause 'in_reduction' in the '#pragma omp task' directives. /// /// \code /// #pragma omp task in_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp task' has clause 'in_reduction' with /// operator '+' and the variables 'a' and 'b'. class OMPInReductionClause final : public OMPVarListClause<OMPInReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPInReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPInReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPInReductionClause>(llvm::omp::OMPC_in_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInReductionClause(unsigned N) : OMPVarListClause<OMPInReductionClause>( llvm::omp::OMPC_in_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } /// Set list of helper reduction taskgroup descriptors. void setTaskgroupDescriptors(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction taskgroup descriptors. MutableArrayRef<Expr *> getTaskgroupDescriptors() { return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size()); } ArrayRef<const Expr *> getTaskgroupDescriptors() const { return llvm::makeArrayRef(getReductionOps().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param TaskgroupDescriptors List of helper taskgroup descriptors for /// corresponding items in parent taskgroup task_reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPInReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> TaskgroupDescriptors, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_const_range taskgroup_descriptors() const { return helper_expr_const_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } helper_expr_range taskgroup_descriptors() { return helper_expr_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_in_reduction; } }; /// This represents clause 'linear' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd linear(a,b : 2) /// \endcode /// In this example directive '#pragma omp simd' has clause 'linear' /// with variables 'a', 'b' and linear step '2'. class OMPLinearClause final : public OMPVarListClause<OMPLinearClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLinearClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Modifier of 'linear' clause. OpenMPLinearClauseKind Modifier = OMPC_LINEAR_val; /// Location of linear modifier if any. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Sets the linear step for clause. void setStep(Expr *Step) { *(getFinals().end()) = Step; } /// Sets the expression to calculate linear step for clause. void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; } /// Build 'linear' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, StartLoc, LParenLoc, EndLoc, NumVars), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPLinearClause(unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), OMPClauseWithPostUpdate(this) {} /// Gets the list of initial values for linear variables. /// /// There are NumVars expressions with initial values allocated after the /// varlist, they are followed by NumVars update expressions (used to update /// the linear variable's value on current iteration) and they are followed by /// NumVars final expressions (used to calculate the linear variable's /// value after the loop body). After these lists, there are 2 helper /// expressions - linear step and a helper to calculate it before the /// loop body (used when the linear step is not constant): /// /// { Vars[] /* in OMPVarListClause */; Privates[]; Inits[]; Updates[]; /// Finals[]; Step; CalcStep; } MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Sets the list of update expressions for linear variables. MutableArrayRef<Expr *> getUpdates() { return MutableArrayRef<Expr *>(getInits().end(), varlist_size()); } ArrayRef<const Expr *> getUpdates() const { return llvm::makeArrayRef(getInits().end(), varlist_size()); } /// Sets the list of final update expressions for linear variables. MutableArrayRef<Expr *> getFinals() { return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size()); } ArrayRef<const Expr *> getFinals() const { return llvm::makeArrayRef(getUpdates().end(), varlist_size()); } /// Gets the list of used expressions for linear variables. MutableArrayRef<Expr *> getUsedExprs() { return MutableArrayRef<Expr *>(getFinals().end() + 2, varlist_size() + 1); } ArrayRef<const Expr *> getUsedExprs() const { return llvm::makeArrayRef(getFinals().end() + 2, varlist_size() + 1); } /// Sets the list of the copies of original linear variables. /// \param PL List of expressions. void setPrivates(ArrayRef<Expr *> PL); /// Sets the list of the initial values for linear variables. /// \param IL List of expressions. void setInits(ArrayRef<Expr *> IL); public: /// Creates clause with a list of variables \a VL and a linear step /// \a Step. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Modifier Modifier of 'linear' clause. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PL List of private copies of original variables. /// \param IL List of initial values for the variables. /// \param Step Linear step. /// \param CalcStep Calculation of the linear step. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Set modifier. void setModifier(OpenMPLinearClauseKind Kind) { Modifier = Kind; } /// Return modifier. OpenMPLinearClauseKind getModifier() const { return Modifier; } /// Set modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Return modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns linear step. Expr *getStep() { return *(getFinals().end()); } /// Returns linear step. const Expr *getStep() const { return *(getFinals().end()); } /// Returns expression to calculate linear step. Expr *getCalcStep() { return *(getFinals().end() + 1); } /// Returns expression to calculate linear step. const Expr *getCalcStep() const { return *(getFinals().end() + 1); } /// Sets the list of update expressions for linear variables. /// \param UL List of expressions. void setUpdates(ArrayRef<Expr *> UL); /// Sets the list of final update expressions for linear variables. /// \param FL List of expressions. void setFinals(ArrayRef<Expr *> FL); /// Sets the list of used expressions for the linear clause. void setUsedExprs(ArrayRef<Expr *> UE); using privates_iterator = MutableArrayRef<Expr *>::iterator; using privates_const_iterator = ArrayRef<const Expr *>::iterator; using privates_range = llvm::iterator_range<privates_iterator>; using privates_const_range = llvm::iterator_range<privates_const_iterator>; privates_range privates() { return privates_range(getPrivates().begin(), getPrivates().end()); } privates_const_range privates() const { return privates_const_range(getPrivates().begin(), getPrivates().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } using updates_iterator = MutableArrayRef<Expr *>::iterator; using updates_const_iterator = ArrayRef<const Expr *>::iterator; using updates_range = llvm::iterator_range<updates_iterator>; using updates_const_range = llvm::iterator_range<updates_const_iterator>; updates_range updates() { return updates_range(getUpdates().begin(), getUpdates().end()); } updates_const_range updates() const { return updates_const_range(getUpdates().begin(), getUpdates().end()); } using finals_iterator = MutableArrayRef<Expr *>::iterator; using finals_const_iterator = ArrayRef<const Expr *>::iterator; using finals_range = llvm::iterator_range<finals_iterator>; using finals_const_range = llvm::iterator_range<finals_const_iterator>; finals_range finals() { return finals_range(getFinals().begin(), getFinals().end()); } finals_const_range finals() const { return finals_const_range(getFinals().begin(), getFinals().end()); } using used_expressions_iterator = MutableArrayRef<Expr *>::iterator; using used_expressions_const_iterator = ArrayRef<const Expr *>::iterator; using used_expressions_range = llvm::iterator_range<used_expressions_iterator>; using used_expressions_const_range = llvm::iterator_range<used_expressions_const_iterator>; used_expressions_range used_expressions() { return finals_range(getUsedExprs().begin(), getUsedExprs().end()); } used_expressions_const_range used_expressions() const { return finals_const_range(getUsedExprs().begin(), getUsedExprs().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLinearClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPLinearClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_linear; } }; /// This represents clause 'aligned' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd aligned(a,b : 8) /// \endcode /// In this example directive '#pragma omp simd' has clause 'aligned' /// with variables 'a', 'b' and alignment '8'. class OMPAlignedClause final : public OMPVarListClause<OMPAlignedClause>, private llvm::TrailingObjects<OMPAlignedClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Sets the alignment for clause. void setAlignment(Expr *A) { *varlist_end() = A; } /// Build 'aligned' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, SourceLocation(), SourceLocation(), SourceLocation(), NumVars) {} public: /// Creates clause with a list of variables \a VL and alignment \a A. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param A Alignment. static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *A); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns alignment. Expr *getAlignment() { return *varlist_end(); } /// Returns alignment. const Expr *getAlignment() const { return *varlist_end(); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAlignedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_aligned; } }; /// This represents clause 'copyin' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel copyin(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'copyin' /// with the variables 'a' and 'b'. class OMPCopyinClause final : public OMPVarListClause<OMPCopyinClause>, private llvm::TrailingObjects<OMPCopyinClause, Expr *> { // Class has 3 additional tail allocated arrays: // 1. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents sources. // 2. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents destinations. // 3. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of propagation of master's thread values of // threadprivate variables to local instances of that variables in other // implicit threads. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyin clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyin clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of propagation of master's thread values of /// threadprivate variables to local instances of that variables in other /// implicit threads. static OMPCopyinClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyinClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyin; } }; /// This represents clause 'copyprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp single copyprivate(a,b) /// \endcode /// In this example directive '#pragma omp single' has clause 'copyprivate' /// with the variables 'a' and 'b'. class OMPCopyprivateClause final : public OMPVarListClause<OMPCopyprivateClause>, private llvm::TrailingObjects<OMPCopyprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyprivateClause>(llvm::omp::OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( llvm::omp::OMPC_copyprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// copyprivate clause. static OMPCopyprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyprivate; } }; /// This represents implicit clause 'flush' for the '#pragma omp flush' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// flush' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has implicit clause 'flush' /// with the variables 'a' and 'b'. class OMPFlushClause final : public OMPVarListClause<OMPFlushClause>, private llvm::TrailingObjects<OMPFlushClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFlushClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_flush; } }; /// This represents implicit clause 'depobj' for the '#pragma omp depobj' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// depobj' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp depobj(a) destroy /// \endcode /// In this example directive '#pragma omp depobj' has implicit clause 'depobj' /// with the depobj 'a'. class OMPDepobjClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Chunk size. Expr *Depobj = nullptr; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDepobjClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_depobj, StartLoc, EndLoc), LParenLoc(LParenLoc) {} /// Build an empty clause. /// explicit OMPDepobjClause() : OMPClause(llvm::omp::OMPC_depobj, SourceLocation(), SourceLocation()) {} void setDepobj(Expr *E) { Depobj = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Creates clause. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Depobj depobj expression associated with the 'depobj' directive. static OMPDepobjClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *Depobj); /// Creates an empty clause. /// /// \param C AST context. static OMPDepobjClause *CreateEmpty(const ASTContext &C); /// Returns depobj expression associated with the clause. Expr *getDepobj() { return Depobj; } const Expr *getDepobj() const { return Depobj; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&Depobj), reinterpret_cast<Stmt **>(&Depobj) + 1); } const_child_range children() const { auto Children = const_cast<OMPDepobjClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depobj; } }; /// This represents implicit clause 'depend' for the '#pragma omp task' /// directive. /// /// \code /// #pragma omp task depend(in:a,b) /// \endcode /// In this example directive '#pragma omp task' with clause 'depend' with the /// variables 'a' and 'b' with dependency 'in'. class OMPDependClause final : public OMPVarListClause<OMPDependClause>, private llvm::TrailingObjects<OMPDependClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Dependency type (one of in, out, inout). OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; /// Dependency type location. SourceLocation DepLoc; /// Colon location. SourceLocation ColonLoc; /// Number of loops, associated with the depend clause. unsigned NumLoops = 0; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param NumLoops Number of loops that is associated with this depend /// clause. OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, StartLoc, LParenLoc, EndLoc, N), NumLoops(NumLoops) {} /// Build an empty clause. /// /// \param N Number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. explicit OMPDependClause(unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, SourceLocation(), SourceLocation(), SourceLocation(), N), NumLoops(NumLoops) {} /// Set dependency kind. void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; } /// Set dependency kind and its location. void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Sets optional dependency modifier. void setModifier(Expr *DepModifier); public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param DepKind Dependency type. /// \param DepLoc Location of the dependency type. /// \param ColonLoc Colon location. /// \param VL List of references to the variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VL, unsigned NumLoops); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops); /// Get dependency type. OpenMPDependClauseKind getDependencyKind() const { return DepKind; } /// Return optional depend modifier. Expr *getModifier(); const Expr *getModifier() const { return const_cast<OMPDependClause *>(this)->getModifier(); } /// Get dependency type location. SourceLocation getDependencyLoc() const { return DepLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } /// Get number of loops associated with the clause. unsigned getNumLoops() const { return NumLoops; } /// Set the loop data for the depend clauses with 'sink|source' kind of /// dependency. void setLoopData(unsigned NumLoop, Expr *Cnt); /// Get the loop data. Expr *getLoopData(unsigned NumLoop); const Expr *getLoopData(unsigned NumLoop) const; child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPDependClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depend; } }; /// This represents 'device' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp target device(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'device' /// with single expression 'a'. class OMPDeviceClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Device clause modifier. OpenMPDeviceClauseModifier Modifier = OMPC_DEVICE_unknown; /// Location of the modifier. SourceLocation ModifierLoc; /// Device number. Stmt *Device = nullptr; /// Set the device number. /// /// \param E Device number. void setDevice(Expr *E) { Device = E; } /// Sets modifier. void setModifier(OpenMPDeviceClauseModifier M) { Modifier = M; } /// Setst modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } public: /// Build 'device' clause. /// /// \param Modifier Clause modifier. /// \param E Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param ModifierLoc Modifier location. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_device, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Modifier(Modifier), ModifierLoc(ModifierLoc), Device(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPDeviceClause() : OMPClause(llvm::omp::OMPC_device, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return device number. Expr *getDevice() { return cast<Expr>(Device); } /// Return device number. Expr *getDevice() const { return cast<Expr>(Device); } /// Gets modifier. OpenMPDeviceClauseModifier getModifier() const { return Modifier; } /// Gets modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(&Device, &Device + 1); } const_child_range children() const { return const_child_range(&Device, &Device + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_device; } }; /// This represents 'threads' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered threads /// \endcode /// In this example directive '#pragma omp ordered' has simple 'threads' clause. class OMPThreadsClause : public OMPClause { public: /// Build 'threads' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_threads, StartLoc, EndLoc) {} /// Build an empty clause. OMPThreadsClause() : OMPClause(llvm::omp::OMPC_threads, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_threads; } }; /// This represents 'simd' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered simd /// \endcode /// In this example directive '#pragma omp ordered' has simple 'simd' clause. class OMPSIMDClause : public OMPClause { public: /// Build 'simd' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simd, StartLoc, EndLoc) {} /// Build an empty clause. OMPSIMDClause() : OMPClause(llvm::omp::OMPC_simd, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simd; } }; /// Struct that defines common infrastructure to handle mappable /// expressions used in OpenMP clauses. class OMPClauseMappableExprCommon { public: /// Class that represents a component of a mappable expression. E.g. /// for an expression S.a, the first component is a declaration reference /// expression associated with 'S' and the second is a member expression /// associated with the field declaration 'a'. If the expression is an array /// subscript it may not have any associated declaration. In that case the /// associated declaration is set to nullptr. class MappableComponent { /// Pair of Expression and Non-contiguous pair associated with the /// component. llvm::PointerIntPair<Expr *, 1, bool> AssociatedExpressionNonContiguousPr; /// Declaration associated with the declaration. If the component does /// not have a declaration (e.g. array subscripts or section), this is set /// to nullptr. ValueDecl *AssociatedDeclaration = nullptr; public: explicit MappableComponent() = default; explicit MappableComponent(Expr *AssociatedExpression, ValueDecl *AssociatedDeclaration, bool IsNonContiguous) : AssociatedExpressionNonContiguousPr(AssociatedExpression, IsNonContiguous), AssociatedDeclaration( AssociatedDeclaration ? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl()) : nullptr) {} Expr *getAssociatedExpression() const { return AssociatedExpressionNonContiguousPr.getPointer(); } bool isNonContiguous() const { return AssociatedExpressionNonContiguousPr.getInt(); } ValueDecl *getAssociatedDeclaration() const { return AssociatedDeclaration; } }; // List of components of an expression. This first one is the whole // expression and the last one is the base expression. using MappableExprComponentList = SmallVector<MappableComponent, 8>; using MappableExprComponentListRef = ArrayRef<MappableComponent>; // List of all component lists associated to the same base declaration. // E.g. if both 'S.a' and 'S.b' are a mappable expressions, each will have // their component list but the same base declaration 'S'. using MappableExprComponentLists = SmallVector<MappableExprComponentList, 8>; using MappableExprComponentListsRef = ArrayRef<MappableExprComponentList>; protected: // Return the total number of elements in a list of component lists. static unsigned getComponentsTotalNumber(MappableExprComponentListsRef ComponentLists); // Return the total number of elements in a list of declarations. All // declarations are expected to be canonical. static unsigned getUniqueDeclarationsTotalNumber(ArrayRef<const ValueDecl *> Declarations); }; /// This structure contains all sizes needed for by an /// OMPMappableExprListClause. struct OMPMappableExprListSizeTy { /// Number of expressions listed. unsigned NumVars; /// Number of unique base declarations. unsigned NumUniqueDeclarations; /// Number of component lists. unsigned NumComponentLists; /// Total number of expression components. unsigned NumComponents; OMPMappableExprListSizeTy() = default; OMPMappableExprListSizeTy(unsigned NumVars, unsigned NumUniqueDeclarations, unsigned NumComponentLists, unsigned NumComponents) : NumVars(NumVars), NumUniqueDeclarations(NumUniqueDeclarations), NumComponentLists(NumComponentLists), NumComponents(NumComponents) {} }; /// This represents clauses with a list of expressions that are mappable. /// Examples of these clauses are 'map' in /// '#pragma omp target [enter|exit] [data]...' directives, and 'to' and 'from /// in '#pragma omp target update...' directives. template <class T> class OMPMappableExprListClause : public OMPVarListClause<T>, public OMPClauseMappableExprCommon { friend class OMPClauseReader; /// Number of unique declarations in this clause. unsigned NumUniqueDeclarations; /// Number of component lists in this clause. unsigned NumComponentLists; /// Total number of components in this clause. unsigned NumComponents; /// Whether this clause is possible to have user-defined mappers associated. /// It should be true for map, to, and from clauses, and false for /// use_device_ptr and is_device_ptr. const bool SupportsMapper; /// C++ nested name specifier for the associated user-defined mapper. NestedNameSpecifierLoc MapperQualifierLoc; /// The associated user-defined mapper identifier information. DeclarationNameInfo MapperIdInfo; protected: /// Build a clause for \a NumUniqueDeclarations declarations, \a /// NumComponentLists total component lists, and \a NumComponents total /// components. /// /// \param K Kind of the clause. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. /// \param SupportsMapper Indicates whether this clause is possible to have /// user-defined mappers associated. /// \param MapperQualifierLocPtr C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfoPtr The identifier of associated user-defined mapper. OMPMappableExprListClause( OpenMPClauseKind K, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes, bool SupportsMapper = false, NestedNameSpecifierLoc *MapperQualifierLocPtr = nullptr, DeclarationNameInfo *MapperIdInfoPtr = nullptr) : OMPVarListClause<T>(K, Locs.StartLoc, Locs.LParenLoc, Locs.EndLoc, Sizes.NumVars), NumUniqueDeclarations(Sizes.NumUniqueDeclarations), NumComponentLists(Sizes.NumComponentLists), NumComponents(Sizes.NumComponents), SupportsMapper(SupportsMapper) { if (MapperQualifierLocPtr) MapperQualifierLoc = *MapperQualifierLocPtr; if (MapperIdInfoPtr) MapperIdInfo = *MapperIdInfoPtr; } /// Get the unique declarations that are in the trailing objects of the /// class. MutableArrayRef<ValueDecl *> getUniqueDeclsRef() { return MutableArrayRef<ValueDecl *>( static_cast<T *>(this)->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Get the unique declarations that are in the trailing objects of the /// class. ArrayRef<ValueDecl *> getUniqueDeclsRef() const { return ArrayRef<ValueDecl *>( static_cast<const T *>(this) ->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Set the unique declarations that are in the trailing objects of the /// class. void setUniqueDecls(ArrayRef<ValueDecl *> UDs) { assert(UDs.size() == NumUniqueDeclarations && "Unexpected amount of unique declarations."); std::copy(UDs.begin(), UDs.end(), getUniqueDeclsRef().begin()); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. MutableArrayRef<unsigned> getDeclNumListsRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. ArrayRef<unsigned> getDeclNumListsRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Set the number of lists per declaration that are in the trailing /// objects of the class. void setDeclNumLists(ArrayRef<unsigned> DNLs) { assert(DNLs.size() == NumUniqueDeclarations && "Unexpected amount of list numbers."); std::copy(DNLs.begin(), DNLs.end(), getDeclNumListsRef().begin()); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. MutableArrayRef<unsigned> getComponentListSizesRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. ArrayRef<unsigned> getComponentListSizesRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Set the cumulative component lists sizes that are in the trailing /// objects of the class. void setComponentListSizes(ArrayRef<unsigned> CLSs) { assert(CLSs.size() == NumComponentLists && "Unexpected amount of component lists."); std::copy(CLSs.begin(), CLSs.end(), getComponentListSizesRef().begin()); } /// Get the components that are in the trailing objects of the class. MutableArrayRef<MappableComponent> getComponentsRef() { return MutableArrayRef<MappableComponent>( static_cast<T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Get the components that are in the trailing objects of the class. ArrayRef<MappableComponent> getComponentsRef() const { return ArrayRef<MappableComponent>( static_cast<const T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Set the components that are in the trailing objects of the class. /// This requires the list sizes so that it can also fill the original /// expressions, which are the first component of each list. void setComponents(ArrayRef<MappableComponent> Components, ArrayRef<unsigned> CLSs) { assert(Components.size() == NumComponents && "Unexpected amount of component lists."); assert(CLSs.size() == NumComponentLists && "Unexpected amount of list sizes."); std::copy(Components.begin(), Components.end(), getComponentsRef().begin()); } /// Fill the clause information from the list of declarations and /// associated component lists. void setClauseInfo(ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists) { // Perform some checks to make sure the data sizes are consistent with the // information available when the clause was created. assert(getUniqueDeclarationsTotalNumber(Declarations) == NumUniqueDeclarations && "Unexpected number of mappable expression info entries!"); assert(getComponentsTotalNumber(ComponentLists) == NumComponents && "Unexpected total number of components!"); assert(Declarations.size() == ComponentLists.size() && "Declaration and component lists size is not consistent!"); assert(Declarations.size() == NumComponentLists && "Unexpected declaration and component lists size!"); // Organize the components by declaration and retrieve the original // expression. Original expressions are always the first component of the // mappable component list. llvm::MapVector<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>> ComponentListMap; { auto CI = ComponentLists.begin(); for (auto DI = Declarations.begin(), DE = Declarations.end(); DI != DE; ++DI, ++CI) { assert(!CI->empty() && "Invalid component list!"); ComponentListMap[*DI].push_back(*CI); } } // Iterators of the target storage. auto UniqueDeclarations = getUniqueDeclsRef(); auto UDI = UniqueDeclarations.begin(); auto DeclNumLists = getDeclNumListsRef(); auto DNLI = DeclNumLists.begin(); auto ComponentListSizes = getComponentListSizesRef(); auto CLSI = ComponentListSizes.begin(); auto Components = getComponentsRef(); auto CI = Components.begin(); // Variable to compute the accumulation of the number of components. unsigned PrevSize = 0u; // Scan all the declarations and associated component lists. for (auto &M : ComponentListMap) { // The declaration. auto *D = M.first; // The component lists. auto CL = M.second; // Initialize the entry. *UDI = D; ++UDI; *DNLI = CL.size(); ++DNLI; // Obtain the cumulative sizes and concatenate all the components in the // reserved storage. for (auto C : CL) { // Accumulate with the previous size. PrevSize += C.size(); // Save the size. *CLSI = PrevSize; ++CLSI; // Append components after the current components iterator. CI = std::copy(C.begin(), C.end(), CI); } } } /// Set the nested name specifier of associated user-defined mapper. void setMapperQualifierLoc(NestedNameSpecifierLoc NNSL) { MapperQualifierLoc = NNSL; } /// Set the name of associated user-defined mapper. void setMapperIdInfo(DeclarationNameInfo MapperId) { MapperIdInfo = MapperId; } /// Get the user-defined mapper references that are in the trailing objects of /// the class. MutableArrayRef<Expr *> getUDMapperRefs() { assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); return llvm::makeMutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Get the user-defined mappers references that are in the trailing objects /// of the class. ArrayRef<Expr *> getUDMapperRefs() const { assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); return llvm::makeArrayRef<Expr *>( static_cast<const T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Set the user-defined mappers that are in the trailing objects of the /// class. void setUDMapperRefs(ArrayRef<Expr *> DMDs) { assert(DMDs.size() == OMPVarListClause<T>::varlist_size() && "Unexpected number of user-defined mappers."); assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); std::copy(DMDs.begin(), DMDs.end(), getUDMapperRefs().begin()); } public: /// Return the number of unique base declarations in this clause. unsigned getUniqueDeclarationsNum() const { return NumUniqueDeclarations; } /// Return the number of lists derived from the clause expressions. unsigned getTotalComponentListNum() const { return NumComponentLists; } /// Return the total number of components in all lists derived from the /// clause. unsigned getTotalComponentsNum() const { return NumComponents; } /// Gets the nested name specifier for associated user-defined mapper. NestedNameSpecifierLoc getMapperQualifierLoc() const { return MapperQualifierLoc; } /// Gets the name info for associated user-defined mapper. const DeclarationNameInfo &getMapperIdInfo() const { return MapperIdInfo; } /// Iterator that browse the components by lists. It also allows /// browsing components of a single declaration. class const_component_lists_iterator : public llvm::iterator_adaptor_base< const_component_lists_iterator, MappableExprComponentListRef::const_iterator, std::forward_iterator_tag, MappableComponent, ptrdiff_t, MappableComponent, MappableComponent> { // The declaration the iterator currently refers to. ArrayRef<ValueDecl *>::iterator DeclCur; // The list number associated with the current declaration. ArrayRef<unsigned>::iterator NumListsCur; // Whether this clause is possible to have user-defined mappers associated. const bool SupportsMapper; // The user-defined mapper associated with the current declaration. ArrayRef<Expr *>::iterator MapperCur; // Remaining lists for the current declaration. unsigned RemainingLists = 0; // The cumulative size of the previous list, or zero if there is no previous // list. unsigned PrevListSize = 0; // The cumulative sizes of the current list - it will delimit the remaining // range of interest. ArrayRef<unsigned>::const_iterator ListSizeCur; ArrayRef<unsigned>::const_iterator ListSizeEnd; // Iterator to the end of the components storage. MappableExprComponentListRef::const_iterator End; public: /// Construct an iterator that scans all lists. explicit const_component_lists_iterator( ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components, bool SupportsMapper, ArrayRef<Expr *> Mappers) : const_component_lists_iterator::iterator_adaptor_base( Components.begin()), DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()), SupportsMapper(SupportsMapper), ListSizeCur(CumulativeListSizes.begin()), ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) { assert(UniqueDecls.size() == DeclsListNum.size() && "Inconsistent number of declarations and list sizes!"); if (!DeclsListNum.empty()) RemainingLists = *NumListsCur; if (SupportsMapper) MapperCur = Mappers.begin(); } /// Construct an iterator that scan lists for a given declaration \a /// Declaration. explicit const_component_lists_iterator( const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components, bool SupportsMapper, ArrayRef<Expr *> Mappers) : const_component_lists_iterator(UniqueDecls, DeclsListNum, CumulativeListSizes, Components, SupportsMapper, Mappers) { // Look for the desired declaration. While we are looking for it, we // update the state so that we know the component where a given list // starts. for (; DeclCur != UniqueDecls.end(); ++DeclCur, ++NumListsCur) { if (*DeclCur == Declaration) break; assert(*NumListsCur > 0 && "No lists associated with declaration??"); // Skip the lists associated with the current declaration, but save the // last list size that was skipped. std::advance(ListSizeCur, *NumListsCur - 1); PrevListSize = *ListSizeCur; ++ListSizeCur; if (SupportsMapper) ++MapperCur; } // If we didn't find any declaration, advance the iterator to after the // last component and set remaining lists to zero. if (ListSizeCur == CumulativeListSizes.end()) { this->I = End; RemainingLists = 0u; return; } // Set the remaining lists with the total number of lists of the current // declaration. RemainingLists = *NumListsCur; // Adjust the list size end iterator to the end of the relevant range. ListSizeEnd = ListSizeCur; std::advance(ListSizeEnd, RemainingLists); // Given that the list sizes are cumulative, the index of the component // that start the list is the size of the previous list. std::advance(this->I, PrevListSize); } // Return the array with the current list. The sizes are cumulative, so the // array size is the difference between the current size and previous one. std::tuple<const ValueDecl *, MappableExprComponentListRef, const ValueDecl *> operator*() const { assert(ListSizeCur != ListSizeEnd && "Invalid iterator!"); const ValueDecl *Mapper = nullptr; if (SupportsMapper && *MapperCur) Mapper = cast<ValueDecl>(cast<DeclRefExpr>(*MapperCur)->getDecl()); return std::make_tuple( *DeclCur, MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize), Mapper); } std::tuple<const ValueDecl *, MappableExprComponentListRef, const ValueDecl *> operator->() const { return **this; } // Skip the components of the current list. const_component_lists_iterator &operator++() { assert(ListSizeCur != ListSizeEnd && RemainingLists && "Invalid iterator!"); // If we don't have more lists just skip all the components. Otherwise, // advance the iterator by the number of components in the current list. if (std::next(ListSizeCur) == ListSizeEnd) { this->I = End; RemainingLists = 0; } else { std::advance(this->I, *ListSizeCur - PrevListSize); PrevListSize = *ListSizeCur; // We are done with a declaration, move to the next one. if (!(--RemainingLists)) { ++DeclCur; ++NumListsCur; RemainingLists = *NumListsCur; assert(RemainingLists && "No lists in the following declaration??"); } } ++ListSizeCur; if (SupportsMapper) ++MapperCur; return *this; } }; using const_component_lists_range = llvm::iterator_range<const_component_lists_iterator>; /// Iterators for all component lists. const_component_lists_iterator component_lists_begin() const { return const_component_lists_iterator( getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef(), SupportsMapper, SupportsMapper ? getUDMapperRefs() : llvm::None); } const_component_lists_iterator component_lists_end() const { return const_component_lists_iterator( ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(), MappableExprComponentListRef(getComponentsRef().end(), getComponentsRef().end()), SupportsMapper, llvm::None); } const_component_lists_range component_lists() const { return {component_lists_begin(), component_lists_end()}; } /// Iterators for component lists associated with the provided /// declaration. const_component_lists_iterator decl_component_lists_begin(const ValueDecl *VD) const { return const_component_lists_iterator( VD, getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef(), SupportsMapper, SupportsMapper ? getUDMapperRefs() : llvm::None); } const_component_lists_iterator decl_component_lists_end() const { return component_lists_end(); } const_component_lists_range decl_component_lists(const ValueDecl *VD) const { return {decl_component_lists_begin(VD), decl_component_lists_end()}; } /// Iterators to access all the declarations, number of lists, list sizes, and /// components. using const_all_decls_iterator = ArrayRef<ValueDecl *>::iterator; using const_all_decls_range = llvm::iterator_range<const_all_decls_iterator>; const_all_decls_range all_decls() const { auto A = getUniqueDeclsRef(); return const_all_decls_range(A.begin(), A.end()); } using const_all_num_lists_iterator = ArrayRef<unsigned>::iterator; using const_all_num_lists_range = llvm::iterator_range<const_all_num_lists_iterator>; const_all_num_lists_range all_num_lists() const { auto A = getDeclNumListsRef(); return const_all_num_lists_range(A.begin(), A.end()); } using const_all_lists_sizes_iterator = ArrayRef<unsigned>::iterator; using const_all_lists_sizes_range = llvm::iterator_range<const_all_lists_sizes_iterator>; const_all_lists_sizes_range all_lists_sizes() const { auto A = getComponentListSizesRef(); return const_all_lists_sizes_range(A.begin(), A.end()); } using const_all_components_iterator = ArrayRef<MappableComponent>::iterator; using const_all_components_range = llvm::iterator_range<const_all_components_iterator>; const_all_components_range all_components() const { auto A = getComponentsRef(); return const_all_components_range(A.begin(), A.end()); } using mapperlist_iterator = MutableArrayRef<Expr *>::iterator; using mapperlist_const_iterator = ArrayRef<const Expr *>::iterator; using mapperlist_range = llvm::iterator_range<mapperlist_iterator>; using mapperlist_const_range = llvm::iterator_range<mapperlist_const_iterator>; mapperlist_iterator mapperlist_begin() { return getUDMapperRefs().begin(); } mapperlist_iterator mapperlist_end() { return getUDMapperRefs().end(); } mapperlist_const_iterator mapperlist_begin() const { return getUDMapperRefs().begin(); } mapperlist_const_iterator mapperlist_end() const { return getUDMapperRefs().end(); } mapperlist_range mapperlists() { return mapperlist_range(mapperlist_begin(), mapperlist_end()); } mapperlist_const_range mapperlists() const { return mapperlist_const_range(mapperlist_begin(), mapperlist_end()); } }; /// This represents clause 'map' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target map(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause 'map' /// with the variables 'a' and 'b'. class OMPMapClause final : public OMPMappableExprListClause<OMPMapClause>, private llvm::TrailingObjects< OMPMapClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } private: /// Map-type-modifiers for the 'map' clause. OpenMPMapModifierKind MapTypeModifiers[NumberOfOMPMapClauseModifiers] = { OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown}; /// Location of map-type-modifiers for the 'map' clause. SourceLocation MapTypeModifiersLoc[NumberOfOMPMapClauseModifiers]; /// Map type for the 'map' clause. OpenMPMapClauseKind MapType = OMPC_MAP_unknown; /// Is this an implicit map type or not. bool MapTypeIsImplicit = false; /// Location of the map type. SourceLocation MapLoc; /// Colon location. SourceLocation ColonLoc; /// Build a clause for \a NumVars listed expressions, \a /// NumUniqueDeclarations declarations, \a NumComponentLists total component /// lists, and \a NumComponents total expression components. /// /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Locations of map-type-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param MapType Map type. /// \param MapTypeIsImplicit Map type is inferred implicitly. /// \param MapLoc Location of the map type. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, OpenMPMapClauseKind MapType, bool MapTypeIsImplicit, SourceLocation MapLoc, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo), MapType(MapType), MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) { assert(llvm::array_lengthof(MapTypeModifiers) == MapModifiers.size() && "Unexpected number of map type modifiers."); llvm::copy(MapModifiers, std::begin(MapTypeModifiers)); assert(llvm::array_lengthof(MapTypeModifiersLoc) == MapModifiersLoc.size() && "Unexpected number of map type modifier locations."); llvm::copy(MapModifiersLoc, std::begin(MapTypeModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set map-type-modifier for the clause. /// /// \param I index for map-type-modifier. /// \param T map-type-modifier for the clause. void setMapTypeModifier(unsigned I, OpenMPMapModifierKind T) { assert(I < NumberOfOMPMapClauseModifiers && "Unexpected index to store map type modifier, exceeds array size."); MapTypeModifiers[I] = T; } /// Set location for the map-type-modifier. /// /// \param I index for map-type-modifier location. /// \param TLoc map-type-modifier location. void setMapTypeModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMapClauseModifiers && "Index to store map type modifier location exceeds array size."); MapTypeModifiersLoc[I] = TLoc; } /// Set type for the clause. /// /// \param T Type for the clause. void setMapType(OpenMPMapClauseKind T) { MapType = T; } /// Set type location. /// /// \param TLoc Type location. void setMapLoc(SourceLocation TLoc) { MapLoc = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Location of map-type-modifiers. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. /// \param Type Map type. /// \param TypeIsImplicit Map type is inferred implicitly. /// \param TypeLoc Location of the map type. static OMPMapClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId, OpenMPMapClauseKind Type, bool TypeIsImplicit, SourceLocation TypeLoc); /// Creates an empty clause with the place for \a NumVars original /// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists /// lists, and \a NumComponents expression components. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPMapClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches mapping kind for the clause. OpenMPMapClauseKind getMapType() const LLVM_READONLY { return MapType; } /// Is this an implicit map type? /// We have to capture 'IsMapTypeImplicit' from the parser for more /// informative error messages. It helps distinguish map(r) from /// map(tofrom: r), which is important to print more helpful error /// messages for some target directives. bool isImplicitMapType() const LLVM_READONLY { return MapTypeIsImplicit; } /// Fetches the map-type-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for map-type-modifier. OpenMPMapModifierKind getMapTypeModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier exceeds the total number of modifiers."); return MapTypeModifiers[Cnt]; } /// Fetches the map-type-modifier location at 'Cnt' index of array of /// modifiers' locations. /// /// \param Cnt index for map-type-modifier location. SourceLocation getMapTypeModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier location exceeds total number of modifiers."); return MapTypeModifiersLoc[Cnt]; } /// Fetches ArrayRef of map-type-modifiers. ArrayRef<OpenMPMapModifierKind> getMapTypeModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiers); } /// Fetches ArrayRef of location of map-type-modifiers. ArrayRef<SourceLocation> getMapTypeModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiersLoc); } /// Fetches location of clause mapping kind. SourceLocation getMapLoc() const LLVM_READONLY { return MapLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range( reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPMapClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_tofrom) return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { auto Children = const_cast<OMPMapClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_map; } }; /// This represents 'num_teams' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams num_teams(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'num_teams' /// with single expression 'n'. class OMPNumTeamsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// NumTeams number. Stmt *NumTeams = nullptr; /// Set the NumTeams number. /// /// \param E NumTeams number. void setNumTeams(Expr *E) { NumTeams = E; } public: /// Build 'num_teams' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumTeamsClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_teams, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTeams(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPNumTeamsClause() : OMPClause(llvm::omp::OMPC_num_teams, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return NumTeams number. Expr *getNumTeams() { return cast<Expr>(NumTeams); } /// Return NumTeams number. Expr *getNumTeams() const { return cast<Expr>(NumTeams); } child_range children() { return child_range(&NumTeams, &NumTeams + 1); } const_child_range children() const { return const_child_range(&NumTeams, &NumTeams + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_teams; } }; /// This represents 'thread_limit' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams thread_limit(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'thread_limit' /// with single expression 'n'. class OMPThreadLimitClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// ThreadLimit number. Stmt *ThreadLimit = nullptr; /// Set the ThreadLimit number. /// /// \param E ThreadLimit number. void setThreadLimit(Expr *E) { ThreadLimit = E; } public: /// Build 'thread_limit' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPThreadLimitClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_thread_limit, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPThreadLimitClause() : OMPClause(llvm::omp::OMPC_thread_limit, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return ThreadLimit number. Expr *getThreadLimit() { return cast<Expr>(ThreadLimit); } /// Return ThreadLimit number. Expr *getThreadLimit() const { return cast<Expr>(ThreadLimit); } child_range children() { return child_range(&ThreadLimit, &ThreadLimit + 1); } const_child_range children() const { return const_child_range(&ThreadLimit, &ThreadLimit + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_thread_limit; } }; /// This represents 'priority' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task priority(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'priority' with /// single expression 'n'. class OMPPriorityClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Priority number. Stmt *Priority = nullptr; /// Set the Priority number. /// /// \param E Priority number. void setPriority(Expr *E) { Priority = E; } public: /// Build 'priority' clause. /// /// \param Priority Expression associated with this clause. /// \param HelperPriority Helper priority for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPPriorityClause(Expr *Priority, Stmt *HelperPriority, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_priority, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Priority(Priority) { setPreInitStmt(HelperPriority, CaptureRegion); } /// Build an empty clause. OMPPriorityClause() : OMPClause(llvm::omp::OMPC_priority, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return Priority number. Expr *getPriority() { return cast<Expr>(Priority); } /// Return Priority number. Expr *getPriority() const { return cast<Expr>(Priority); } child_range children() { return child_range(&Priority, &Priority + 1); } const_child_range children() const { return const_child_range(&Priority, &Priority + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPPriorityClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_priority; } }; /// This represents 'grainsize' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop grainsize(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'grainsize' /// with single expression '4'. class OMPGrainsizeClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Grainsize = nullptr; /// Set safelen. void setGrainsize(Expr *Size) { Grainsize = Size; } public: /// Build 'grainsize' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPGrainsizeClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_grainsize, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Grainsize(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPGrainsizeClause() : OMPClause(llvm::omp::OMPC_grainsize, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getGrainsize() const { return cast_or_null<Expr>(Grainsize); } child_range children() { return child_range(&Grainsize, &Grainsize + 1); } const_child_range children() const { return const_child_range(&Grainsize, &Grainsize + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPGrainsizeClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_grainsize; } }; /// This represents 'nogroup' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp taskloop nogroup /// \endcode /// In this example directive '#pragma omp taskloop' has 'nogroup' clause. class OMPNogroupClause : public OMPClause { public: /// Build 'nogroup' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nogroup, StartLoc, EndLoc) {} /// Build an empty clause. OMPNogroupClause() : OMPClause(llvm::omp::OMPC_nogroup, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nogroup; } }; /// This represents 'num_tasks' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop num_tasks(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'num_tasks' /// with single expression '4'. class OMPNumTasksClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *NumTasks = nullptr; /// Set safelen. void setNumTasks(Expr *Size) { NumTasks = Size; } public: /// Build 'num_tasks' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNumTasksClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_tasks, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTasks(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPNumTasksClause() : OMPClause(llvm::omp::OMPC_num_tasks, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getNumTasks() const { return cast_or_null<Expr>(NumTasks); } child_range children() { return child_range(&NumTasks, &NumTasks + 1); } const_child_range children() const { return const_child_range(&NumTasks, &NumTasks + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPNumTasksClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_tasks; } }; /// This represents 'hint' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp critical (name) hint(6) /// \endcode /// In this example directive '#pragma omp critical' has name 'name' and clause /// 'hint' with argument '6'. class OMPHintClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Hint expression of the 'hint' clause. Stmt *Hint = nullptr; /// Set hint expression. void setHint(Expr *H) { Hint = H; } public: /// Build 'hint' clause with expression \a Hint. /// /// \param Hint Hint expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc), Hint(Hint) {} /// Build an empty clause. OMPHintClause() : OMPClause(llvm::omp::OMPC_hint, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getHint() const { return cast_or_null<Expr>(Hint); } child_range children() { return child_range(&Hint, &Hint + 1); } const_child_range children() const { return const_child_range(&Hint, &Hint + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_hint; } }; /// This represents 'dist_schedule' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp distribute dist_schedule(static, 3) /// \endcode /// In this example directive '#pragma omp distribute' has 'dist_schedule' /// clause with arguments 'static' and '3'. class OMPDistScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPDistScheduleClauseKind Kind = OMPC_DIST_SCHEDULE_unknown; /// Start location of the schedule kind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setDistScheduleKind(OpenMPDistScheduleClauseKind K) { Kind = K; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setDistScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'dist_schedule' clause with schedule kind \a Kind and chunk /// size expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind DistSchedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. OMPDistScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize) : OMPClause(llvm::omp::OMPC_dist_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); } /// Build an empty clause. explicit OMPDistScheduleClause() : OMPClause(llvm::omp::OMPC_dist_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Get kind of the clause. OpenMPDistScheduleClauseKind getDistScheduleKind() const { return Kind; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDistScheduleKindLoc() { return KindLoc; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPDistScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dist_schedule; } }; /// This represents 'defaultmap' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp target defaultmap(tofrom: scalar) /// \endcode /// In this example directive '#pragma omp target' has 'defaultmap' clause of kind /// 'scalar' with modifier 'tofrom'. class OMPDefaultmapClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Modifiers for 'defaultmap' clause. OpenMPDefaultmapClauseModifier Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; /// Locations of modifiers. SourceLocation ModifierLoc; /// A kind of the 'defaultmap' clause. OpenMPDefaultmapClauseKind Kind = OMPC_DEFAULTMAP_unknown; /// Start location of the defaultmap kind in source code. SourceLocation KindLoc; /// Set defaultmap kind. /// /// \param K Defaultmap kind. void setDefaultmapKind(OpenMPDefaultmapClauseKind K) { Kind = K; } /// Set the defaultmap modifier. /// /// \param M Defaultmap modifier. void setDefaultmapModifier(OpenMPDefaultmapClauseModifier M) { Modifier = M; } /// Set location of the defaultmap modifier. void setDefaultmapModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set defaultmap kind start location. /// /// \param KLoc Defaultmap kind location. void setDefaultmapKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } public: /// Build 'defaultmap' clause with defaultmap kind \a Kind /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param EndLoc Ending location of the clause. /// \param Kind Defaultmap kind. /// \param M The modifier applied to 'defaultmap' clause. /// \param MLoc Location of the modifier OMPDefaultmapClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KLoc, SourceLocation EndLoc, OpenMPDefaultmapClauseKind Kind, OpenMPDefaultmapClauseModifier M) : OMPClause(llvm::omp::OMPC_defaultmap, StartLoc, EndLoc), LParenLoc(LParenLoc), Modifier(M), ModifierLoc(MLoc), Kind(Kind), KindLoc(KLoc) {} /// Build an empty clause. explicit OMPDefaultmapClause() : OMPClause(llvm::omp::OMPC_defaultmap, SourceLocation(), SourceLocation()) {} /// Get kind of the clause. OpenMPDefaultmapClauseKind getDefaultmapKind() const { return Kind; } /// Get the modifier of the clause. OpenMPDefaultmapClauseModifier getDefaultmapModifier() const { return Modifier; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDefaultmapKindLoc() { return KindLoc; } /// Get the modifier location. SourceLocation getDefaultmapModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_defaultmap; } }; /// This represents clause 'to' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update to(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' /// with the variables 'a' and 'b'. class OMPToClause final : public OMPMappableExprListClause<OMPToClause>, private llvm::TrailingObjects< OMPToClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Motion-modifiers for the 'to' clause. OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = { OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown}; /// Location of motion-modifiers for the 'to' clause. SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers]; /// Colon location. SourceLocation ColonLoc; /// Build clause with number of variables \a NumVars. /// /// \param TheMotionModifiers Motion-modifiers. /// \param TheMotionModifiersLoc Locations of motion-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers, ArrayRef<SourceLocation> TheMotionModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo) { assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() && "Unexpected number of motion modifiers."); llvm::copy(TheMotionModifiers, std::begin(MotionModifiers)); assert(llvm::array_lengthof(MotionModifiersLoc) == TheMotionModifiersLoc.size() && "Unexpected number of motion modifier locations."); llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set motion-modifier for the clause. /// /// \param I index for motion-modifier. /// \param T motion-modifier for the clause. void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) { assert(I < NumberOfOMPMotionModifiers && "Unexpected index to store motion modifier, exceeds array size."); MotionModifiers[I] = T; } /// Set location for the motion-modifier. /// /// \param I index for motion-modifier location. /// \param TLoc motion-modifier location. void setMotionModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMotionModifiers && "Index to store motion modifier location exceeds array size."); MotionModifiersLoc[I] = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param MotionModifiers Motion-modifiers. /// \param MotionModifiersLoc Location of motion-modifiers. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPToClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPToClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches the motion-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for motion-modifier. OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier exceeds the total number of modifiers."); return MotionModifiers[Cnt]; } /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers' /// locations. /// /// \param Cnt index for motion-modifier location. SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier location exceeds total number of modifiers."); return MotionModifiersLoc[Cnt]; } /// Fetches ArrayRef of motion-modifiers. ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiers); } /// Fetches ArrayRef of location of motion-modifiers. ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiersLoc); } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPToClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_to; } }; /// This represents clause 'from' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update from(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'from' /// with the variables 'a' and 'b'. class OMPFromClause final : public OMPMappableExprListClause<OMPFromClause>, private llvm::TrailingObjects< OMPFromClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Motion-modifiers for the 'from' clause. OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = { OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown}; /// Location of motion-modifiers for the 'from' clause. SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers]; /// Colon location. SourceLocation ColonLoc; /// Build clause with number of variables \a NumVars. /// /// \param TheMotionModifiers Motion-modifiers. /// \param TheMotionModifiersLoc Locations of motion-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers, ArrayRef<SourceLocation> TheMotionModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo) { assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() && "Unexpected number of motion modifiers."); llvm::copy(TheMotionModifiers, std::begin(MotionModifiers)); assert(llvm::array_lengthof(MotionModifiersLoc) == TheMotionModifiersLoc.size() && "Unexpected number of motion modifier locations."); llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set motion-modifier for the clause. /// /// \param I index for motion-modifier. /// \param T motion-modifier for the clause. void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) { assert(I < NumberOfOMPMotionModifiers && "Unexpected index to store motion modifier, exceeds array size."); MotionModifiers[I] = T; } /// Set location for the motion-modifier. /// /// \param I index for motion-modifier location. /// \param TLoc motion-modifier location. void setMotionModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMotionModifiers && "Index to store motion modifier location exceeds array size."); MotionModifiersLoc[I] = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param MotionModifiers Motion-modifiers. /// \param MotionModifiersLoc Location of motion-modifiers. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPFromClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPFromClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches the motion-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for motion-modifier. OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier exceeds the total number of modifiers."); return MotionModifiers[Cnt]; } /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers' /// locations. /// /// \param Cnt index for motion-modifier location. SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier location exceeds total number of modifiers."); return MotionModifiersLoc[Cnt]; } /// Fetches ArrayRef of motion-modifiers. ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiers); } /// Fetches ArrayRef of location of motion-modifiers. ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiersLoc); } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFromClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_from; } }; /// This represents clause 'use_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target data use_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target data' has clause /// 'use_device_ptr' with the variables 'a' and 'b'. class OMPUseDevicePtrClause final : public OMPMappableExprListClause<OMPUseDevicePtrClause>, private llvm::TrailingObjects< OMPUseDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, Locs, Sizes) { } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return 3 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } /// Sets the list of references to private copies with initializers for new /// private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for new /// private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new private /// variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new private /// variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param PrivateVars Expressions referring to private copies. /// \param Inits Expressions referring to private copy initializers. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPUseDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<Expr *> PrivateVars, ArrayRef<Expr *> Inits, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPUseDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use_device_ptr; } }; /// This represents clause 'use_device_addr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target data use_device_addr(a,b) /// \endcode /// In this example directive '#pragma omp target data' has clause /// 'use_device_addr' with the variables 'a' and 'b'. class OMPUseDeviceAddrClause final : public OMPMappableExprListClause<OMPUseDeviceAddrClause>, private llvm::TrailingObjects< OMPUseDeviceAddrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDeviceAddrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr, Locs, Sizes) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDeviceAddrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPUseDeviceAddrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPUseDeviceAddrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use_device_addr; } }; /// This represents clause 'is_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target is_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause /// 'is_device_ptr' with the variables 'a' and 'b'. class OMPIsDevicePtrClause final : public OMPMappableExprListClause<OMPIsDevicePtrClause>, private llvm::TrailingObjects< OMPIsDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, Locs, Sizes) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPIsDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPIsDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_is_device_ptr; } }; /// This represents clause 'nontemporal' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp simd nontemporal(a) /// \endcode /// In this example directive '#pragma omp simd' has clause 'nontemporal' for /// the variable 'a'. class OMPNontemporalClause final : public OMPVarListClause<OMPNontemporalClause>, private llvm::TrailingObjects<OMPNontemporalClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPNontemporalClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPNontemporalClause>(llvm::omp::OMPC_nontemporal, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPNontemporalClause(unsigned N) : OMPVarListClause<OMPNontemporalClause>( llvm::omp::OMPC_nontemporal, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Get the list of privatied copies if the member expression was captured by /// one of the privatization clauses. MutableArrayRef<Expr *> getPrivateRefs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateRefs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPNontemporalClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPNontemporalClause *CreateEmpty(const ASTContext &C, unsigned N); /// Sets the list of references to private copies created in private clauses. /// \param VL List of references. void setPrivateRefs(ArrayRef<Expr *> VL); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPNontemporalClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range private_refs() { return child_range(reinterpret_cast<Stmt **>(getPrivateRefs().begin()), reinterpret_cast<Stmt **>(getPrivateRefs().end())); } const_child_range private_refs() const { auto Children = const_cast<OMPNontemporalClause *>(this)->private_refs(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nontemporal; } }; /// This represents 'order' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp simd order(concurrent) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'order' /// clause with kind 'concurrent'. class OMPOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. OpenMPOrderClauseKind Kind = OMPC_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Argument of clause. void setKind(OpenMPOrderClauseKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'order' clause with argument \p A ('concurrent'). /// /// \param A Argument of the clause ('concurrent'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPOrderClause() : OMPClause(llvm::omp::OMPC_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPOrderClauseKind getKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_order; } }; /// This represents 'destroy' clause in the '#pragma omp depobj' /// directive. /// /// \code /// #pragma omp depobj(a) destroy /// \endcode /// In this example directive '#pragma omp depobj' has 'destroy' clause. class OMPDestroyClause final : public OMPClause { public: /// Build 'destroy' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_destroy, StartLoc, EndLoc) {} /// Build an empty clause. OMPDestroyClause() : OMPClause(llvm::omp::OMPC_destroy, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_destroy; } }; /// This represents 'detach' clause in the '#pragma omp task' directive. /// /// \code /// #pragma omp task detach(evt) /// \endcode /// In this example directive '#pragma omp detach' has simple 'detach' clause /// with the variable 'evt'. class OMPDetachClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression of the 'detach' clause. Stmt *Evt = nullptr; /// Set condition. void setEventHandler(Expr *E) { Evt = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'detach' clause with event-handler \a Evt. /// /// \param Evt Event handler expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_detach, StartLoc, EndLoc), LParenLoc(LParenLoc), Evt(Evt) {} /// Build an empty clause. OMPDetachClause() : OMPClause(llvm::omp::OMPC_detach, SourceLocation(), SourceLocation()) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns event-handler expression. Expr *getEventHandler() const { return cast_or_null<Expr>(Evt); } child_range children() { return child_range(&Evt, &Evt + 1); } const_child_range children() const { return const_child_range(&Evt, &Evt + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_detach; } }; /// This represents clause 'inclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan inclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'inclusive' /// with the variables 'a' and 'b'. class OMPInclusiveClause final : public OMPVarListClause<OMPInclusiveClause>, private llvm::TrailingObjects<OMPInclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPInclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInclusiveClause(unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPInclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_inclusive; } }; /// This represents clause 'exclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan exclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'exclusive' /// with the variables 'a' and 'b'. class OMPExclusiveClause final : public OMPVarListClause<OMPExclusiveClause>, private llvm::TrailingObjects<OMPExclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPExclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPExclusiveClause(unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPExclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPExclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPExclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_exclusive; } }; /// This represents clause 'uses_allocators' in the '#pragma omp target'-based /// directives. /// /// \code /// #pragma omp target uses_allocators(default_allocator, my_allocator(traits)) /// \endcode /// In this example directive '#pragma omp target' has clause 'uses_allocators' /// with the allocators 'default_allocator' and user-defined 'my_allocator'. class OMPUsesAllocatorsClause final : public OMPClause, private llvm::TrailingObjects<OMPUsesAllocatorsClause, Expr *, SourceLocation> { public: /// Data for list of allocators. struct Data { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; private: friend class OMPClauseReader; friend TrailingObjects; enum class ExprOffsets { Allocator, AllocatorTraits, Total, }; enum class ParenLocsOffsets { LParen, RParen, Total, }; /// Location of '('. SourceLocation LParenLoc; /// Total number of allocators in the clause. unsigned NumOfAllocators = 0; /// Build clause. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of allocators asssociated with the clause. OMPUsesAllocatorsClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, StartLoc, EndLoc), LParenLoc(LParenLoc), NumOfAllocators(N) {} /// Build an empty clause. /// \param N Number of allocators asssociated with the clause. /// explicit OMPUsesAllocatorsClause(unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, SourceLocation(), SourceLocation()), NumOfAllocators(N) {} unsigned numTrailingObjects(OverloadToken<Expr *>) const { return NumOfAllocators * static_cast<int>(ExprOffsets::Total); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Sets the allocators data for the clause. void setAllocatorsData(ArrayRef<OMPUsesAllocatorsClause::Data> Data); public: /// Creates clause with a list of allocators \p Data. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Data List of allocators. static OMPUsesAllocatorsClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<OMPUsesAllocatorsClause::Data> Data); /// Creates an empty clause with the place for \p N allocators. /// /// \param C AST context. /// \param N The number of allocators. static OMPUsesAllocatorsClause *CreateEmpty(const ASTContext &C, unsigned N); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of allocators associated with the clause. unsigned getNumberOfAllocators() const { return NumOfAllocators; } /// Returns data for the specified allocator. OMPUsesAllocatorsClause::Data getAllocatorData(unsigned I) const; // Iterators child_range children() { Stmt **Begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); return child_range(Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } const_child_range children() const { Stmt *const *Begin = reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); return const_child_range( Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_uses_allocators; } }; /// This represents clause 'affinity' in the '#pragma omp task'-based /// directives. /// /// \code /// #pragma omp task affinity(iterator(i = 0:n) : ([3][n])a, b[:n], c[i]) /// \endcode /// In this example directive '#pragma omp task' has clause 'affinity' with the /// affinity modifer 'iterator(i = 0:n)' and locator items '([3][n])a', 'b[:n]' /// and 'c[i]'. class OMPAffinityClause final : public OMPVarListClause<OMPAffinityClause>, private llvm::TrailingObjects<OMPAffinityClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':' symbol. SourceLocation ColonLoc; /// Build clause. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param N Number of locators asssociated with the clause. OMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// \param N Number of locators asssociated with the clause. /// explicit OMPAffinityClause(unsigned N) : OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets the affinity modifier for the clause, if any. void setModifier(Expr *E) { getTrailingObjects<Expr *>()[varlist_size()] = E; } /// Sets the location of ':' symbol. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a modifier a list of locator items. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param Locators List of locator items. static OMPAffinityClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// Creates an empty clause with the place for \p N locator items. /// /// \param C AST context. /// \param N The number of locator items. static OMPAffinityClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets affinity modifier. Expr *getModifier() { return getTrailingObjects<Expr *>()[varlist_size()]; } Expr *getModifier() const { return getTrailingObjects<Expr *>()[varlist_size()]; } /// Gets the location of ':' symbol. SourceLocation getColonLoc() const { return ColonLoc; } // Iterators child_range children() { int Offset = getModifier() ? 1 : 0; return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end() + Offset)); } const_child_range children() const { auto Children = const_cast<OMPAffinityClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_affinity; } }; /// This class implements a simple visitor for OMPClause /// subclasses. template<class ImplClass, template <typename> class Ptr, typename RetTy> class OMPClauseVisitorBase { public: #define PTR(CLASS) Ptr<CLASS> #define DISPATCH(CLASS) \ return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S)) #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) \ RetTy Visit##Class(PTR(Class) S) { DISPATCH(Class); } #include "llvm/Frontend/OpenMP/OMP.inc" RetTy Visit(PTR(OMPClause) S) { // Top switch clause: visit each OMPClause. switch (S->getClauseKind()) { #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) \ case llvm::omp::Clause::Enum: \ return Visit##Class(static_cast<PTR(Class)>(S)); #define CLAUSE_NO_CLASS(Enum, Str) \ case llvm::omp::Clause::Enum: \ break; #include "llvm/Frontend/OpenMP/OMP.inc" } } // Base case, ignore it. :) RetTy VisitOMPClause(PTR(OMPClause) Node) { return RetTy(); } #undef PTR #undef DISPATCH }; template <typename T> using const_ptr = std::add_pointer_t<std::add_const_t<T>>; template <class ImplClass, typename RetTy = void> class OMPClauseVisitor : public OMPClauseVisitorBase<ImplClass, std::add_pointer_t, RetTy> {}; template<class ImplClass, typename RetTy = void> class ConstOMPClauseVisitor : public OMPClauseVisitorBase <ImplClass, const_ptr, RetTy> {}; class OMPClausePrinter final : public OMPClauseVisitor<OMPClausePrinter> { raw_ostream &OS; const PrintingPolicy &Policy; /// Process clauses with list of variables. template <typename T> void VisitOMPClauseList(T *Node, char StartSym); /// Process motion clauses. template <typename T> void VisitOMPMotionClause(T *Node); public: OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy) : OS(OS), Policy(Policy) {} #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S); #include "llvm/Frontend/OpenMP/OMP.inc" }; struct OMPTraitProperty { llvm::omp::TraitProperty Kind = llvm::omp::TraitProperty::invalid; /// The raw string as we parsed it. This is needed for the `isa` trait set /// (which accepts anything) and (later) extensions. StringRef RawString; }; struct OMPTraitSelector { Expr *ScoreOrCondition = nullptr; llvm::omp::TraitSelector Kind = llvm::omp::TraitSelector::invalid; llvm::SmallVector<OMPTraitProperty, 1> Properties; }; struct OMPTraitSet { llvm::omp::TraitSet Kind = llvm::omp::TraitSet::invalid; llvm::SmallVector<OMPTraitSelector, 2> Selectors; }; /// Helper data structure representing the traits in a match clause of an /// `declare variant` or `metadirective`. The outer level is an ordered /// collection of selector sets, each with an associated kind and an ordered /// collection of selectors. A selector has a kind, an optional score/condition, /// and an ordered collection of properties. class OMPTraitInfo { /// Private constructor accesible only by ASTContext. OMPTraitInfo() {} friend class ASTContext; public: /// Reconstruct a (partial) OMPTraitInfo object from a mangled name. OMPTraitInfo(StringRef MangledName); /// The outermost level of selector sets. llvm::SmallVector<OMPTraitSet, 2> Sets; bool anyScoreOrCondition( llvm::function_ref<bool(Expr *&, bool /* IsScore */)> Cond) { return llvm::any_of(Sets, [&](OMPTraitSet &Set) { return llvm::any_of( Set.Selectors, [&](OMPTraitSelector &Selector) { return Cond(Selector.ScoreOrCondition, /* IsScore */ Selector.Kind != llvm::omp::TraitSelector::user_condition); }); }); } /// Create a variant match info object from this trait info object. While the /// former is a flat representation the actual main difference is that the /// latter uses clang::Expr to store the score/condition while the former is /// independent of clang. Thus, expressions and conditions are evaluated in /// this method. void getAsVariantMatchInfo(ASTContext &ASTCtx, llvm::omp::VariantMatchInfo &VMI) const; /// Return a string representation identifying this context selector. std::string getMangledName() const; /// Check the extension trait \p TP is active. bool isExtensionActive(llvm::omp::TraitProperty TP) { for (const OMPTraitSet &Set : Sets) { if (Set.Kind != llvm::omp::TraitSet::implementation) continue; for (const OMPTraitSelector &Selector : Set.Selectors) { if (Selector.Kind != llvm::omp::TraitSelector::implementation_extension) continue; for (const OMPTraitProperty &Property : Selector.Properties) { if (Property.Kind == TP) return true; } } } return false; } /// Print a human readable representation into \p OS. void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const; }; llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI); llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI); /// Clang specific specialization of the OMPContext to lookup target features. struct TargetOMPContext final : public llvm::omp::OMPContext { TargetOMPContext(ASTContext &ASTCtx, std::function<void(StringRef)> &&DiagUnknownTrait, const FunctionDecl *CurrentFunctionDecl); virtual ~TargetOMPContext() = default; /// See llvm::omp::OMPContext::matchesISATrait bool matchesISATrait(StringRef RawString) const override; private: std::function<bool(StringRef)> FeatureValidityCheck; std::function<void(StringRef)> DiagUnknownTrait; llvm::StringMap<bool> FeatureMap; }; /// Contains data for OpenMP directives: clauses, children /// expressions/statements (helpers for codegen) and associated statement, if /// any. class OMPChildren final : private llvm::TrailingObjects<OMPChildren, OMPClause *, Stmt *> { friend TrailingObjects; friend class OMPClauseReader; friend class OMPExecutableDirective; template <typename T> friend class OMPDeclarativeDirective; /// Numbers of clauses. unsigned NumClauses = 0; /// Number of child expressions/stmts. unsigned NumChildren = 0; /// true if the directive has associated statement. bool HasAssociatedStmt = false; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<OMPClause *>) const { return NumClauses; } OMPChildren() = delete; OMPChildren(unsigned NumClauses, unsigned NumChildren, bool HasAssociatedStmt) : NumClauses(NumClauses), NumChildren(NumChildren), HasAssociatedStmt(HasAssociatedStmt) {} static size_t size(unsigned NumClauses, bool HasAssociatedStmt, unsigned NumChildren); static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses); static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses, Stmt *S, unsigned NumChildren = 0); static OMPChildren *CreateEmpty(void *Mem, unsigned NumClauses, bool HasAssociatedStmt = false, unsigned NumChildren = 0); public: unsigned getNumClauses() const { return NumClauses; } unsigned getNumChildren() const { return NumChildren; } bool hasAssociatedStmt() const { return HasAssociatedStmt; } /// Set associated statement. void setAssociatedStmt(Stmt *S) { getTrailingObjects<Stmt *>()[NumChildren] = S; } void setChildren(ArrayRef<Stmt *> Children); /// Sets the list of variables for this clause. /// /// \param Clauses The list of clauses for the directive. /// void setClauses(ArrayRef<OMPClause *> Clauses); /// Returns statement associated with the directive. const Stmt *getAssociatedStmt() const { return const_cast<OMPChildren *>(this)->getAssociatedStmt(); } Stmt *getAssociatedStmt() { assert(HasAssociatedStmt && "Expected directive with the associated statement."); return getTrailingObjects<Stmt *>()[NumChildren]; } /// Get the clauses storage. MutableArrayRef<OMPClause *> getClauses() { return llvm::makeMutableArrayRef(getTrailingObjects<OMPClause *>(), NumClauses); } ArrayRef<OMPClause *> getClauses() const { return const_cast<OMPChildren *>(this)->getClauses(); } /// Returns the captured statement associated with the /// component region within the (combined) directive. /// /// \param RegionKind Component region kind. const CapturedStmt * getCapturedStmt(OpenMPDirectiveKind RegionKind, ArrayRef<OpenMPDirectiveKind> CaptureRegions) const { assert(llvm::any_of( CaptureRegions, [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) && "RegionKind not found in OpenMP CaptureRegions."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (auto ThisCaptureRegion : CaptureRegions) { if (ThisCaptureRegion == RegionKind) return CS; CS = cast<CapturedStmt>(CS->getCapturedStmt()); } llvm_unreachable("Incorrect RegionKind specified for directive."); } /// Get innermost captured statement for the construct. CapturedStmt * getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) { assert(hasAssociatedStmt() && "Must have associated captured statement."); assert(!CaptureRegions.empty() && "At least one captured statement must be provided."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (unsigned Level = CaptureRegions.size(); Level > 1; --Level) CS = cast<CapturedStmt>(CS->getCapturedStmt()); return CS; } const CapturedStmt * getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) const { return const_cast<OMPChildren *>(this)->getInnermostCapturedStmt( CaptureRegions); } MutableArrayRef<Stmt *> getChildren(); ArrayRef<Stmt *> getChildren() const { return const_cast<OMPChildren *>(this)->getChildren(); } Stmt *getRawStmt() { assert(HasAssociatedStmt && "Expected directive with the associated statement."); if (auto *CS = dyn_cast<CapturedStmt>(getAssociatedStmt())) { Stmt *S = nullptr; do { S = CS->getCapturedStmt(); CS = dyn_cast<CapturedStmt>(S); } while (CS); return S; } return getAssociatedStmt(); } const Stmt *getRawStmt() const { return const_cast<OMPChildren *>(this)->getRawStmt(); } Stmt::child_range getAssociatedStmtAsRange() { if (!HasAssociatedStmt) return Stmt::child_range(Stmt::child_iterator(), Stmt::child_iterator()); return Stmt::child_range(&getTrailingObjects<Stmt *>()[NumChildren], &getTrailingObjects<Stmt *>()[NumChildren + 1]); } }; } // namespace clang #endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
VolumetricDilatedMaxPooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "THNN/generic/VolumetricDilatedMaxPooling.c" #else #include <THNN/generic/pooling_shape.h> #include <algorithm> static inline void THNN_(VolumetricDilatedMaxPooling_shapeCheck)( THNNState *state, THTensor *input, THTensor *gradOutput, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int ndim = input->dim(); int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; int64_t nslices; int64_t itime; int64_t iheight; int64_t iwidth; int64_t otime; int64_t oheight; int64_t owidth; THArgCheck(kT > 0 && kW > 0 && kH > 0, 5, "kernel size should be greater than zero, but got kT: %d kH: %d kW: %d", kT, kH, kW); THArgCheck(dT > 0 && dW > 0 && dH > 0, 8, "stride should be greater than zero, but got dT: %d dH: %d dW: %d", dT, dH, dW); THArgCheck(dilationT > 0 && dilationW > 0 && dilationH > 0, 14, "dilation should be greater than 0, but got dilationT: %d dilationH: %d dilationW: %d", dilationT, dilationH, dilationW); THNN_ARGCHECK(!input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } THArgCheck(kT/2 >= pT && kW/2 >= pW && kH/2 >= pH, 2, "pad should be smaller than half of kernel size, but got " "kT: %d kW: %d, kH: %d, padT: %d, padW: %d, padH: %d", kT, kW, kH, pT, pW, pH); nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); otime = pooling_output_shape<int64_t>(itime, kT, pT, dT, dilationT, ceilMode); oheight = pooling_output_shape<int64_t>(iheight, kH, pH, dH, dilationH, ceilMode); owidth = pooling_output_shape<int64_t>(iwidth, kW, pW, dW, dilationW, ceilMode); if (otime < 1 || owidth < 1 || oheight < 1) THError("Given input size: (%dx%dx%dx%d). Calculated output size: (%dx%dx%dx%d). Output size is too small", nslices,itime,iheight,iwidth,nslices,otime,oheight,owidth); if (gradOutput != NULL) { THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimN, nslices); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimt, otime); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, oheight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, owidth); } if (indices != NULL) { THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimN, nslices); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimt, otime); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimh, oheight); THNN_CHECK_DIM_SIZE_INDICES(indices, ndim, dimw, owidth); } } static void THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( scalar_t *input_p, scalar_t *output_p, THIndex_t *indz_p, int64_t nslices, int64_t itime, int64_t iwidth, int64_t iheight, int64_t otime, int64_t owidth, int64_t oheight, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) { int64_t k; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { /* loop over output */ int64_t i, j, ti; scalar_t *ip = input_p + k * itime * iwidth * iheight; for (ti = 0; ti < otime; ti++) { for (i = 0; i < oheight; i++) { for (j = 0; j < owidth; j++) { /* local pointers */ int64_t start_t = ti * dT - pT; int64_t start_h = i * dH - pH; int64_t start_w = j * dW - pW; int64_t end_t = std::min(start_t + (kT - 1) * dilationT + 1, itime); int64_t end_h = std::min(start_h + (kH - 1) * dilationH + 1, iheight); int64_t end_w = std::min(start_w + (kW - 1) * dilationW + 1, iwidth); while(start_t < 0) start_t += dilationT; while(start_h < 0) start_h += dilationH; while(start_w < 0) start_w += dilationW; scalar_t *op = output_p + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j; THIndex_t *indzp = indz_p + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j; /* compute local max: */ int64_t maxindex = -1; scalar_t maxval = -THInf; int64_t x,y,z; int64_t index = 0; for (z = start_t; z < end_t; z += dilationT) { for (y = start_h; y < end_h; y += dilationH) { for (x = start_w; x < end_w; x += dilationW) { index = z * iwidth * iheight + y * iwidth + x; scalar_t val = ip[index]; if ((val > maxval) || std::isnan(val)) { maxval = val; maxindex = index; } } } } // store location of max *indzp = maxindex + TH_INDEX_BASE; /* set output to local max */ *op = maxval; } } } } } void THNN_(VolumetricDilatedMaxPooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int64_t nslices; int64_t itime; int64_t iheight; int64_t iwidth; int64_t otime; int64_t oheight; int64_t owidth; scalar_t *input_data; scalar_t *output_data; THIndex_t *indices_data; int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } THNN_(VolumetricDilatedMaxPooling_shapeCheck)( state, input, NULL, NULL, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH, ceilMode); /* sizes */ nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); otime = pooling_output_shape<int64_t>(itime, kT, pT, dT, dilationT, ceilMode); oheight = pooling_output_shape<int64_t>(iheight, kH, pH, dH, dilationH, ceilMode); owidth = pooling_output_shape<int64_t>(iwidth, kW, pW, dW, dilationW, ceilMode); /* get contiguous input */ input = THTensor_(newContiguous)(input); if (input->dim() == 4) /* non-batch mode */ { /* resize output */ THTensor_(resize4d)(output, nslices, otime, oheight, owidth); /* indices will contain ti,i,j uchar locations packed into float/double */ THIndexTensor_(resize4d)(indices, nslices, otime, oheight, owidth); input_data = input->data<scalar_t>(); output_data = output->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( input_data, output_data, indices_data, nslices, itime, iwidth, iheight, otime, owidth, oheight, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } else /* batch mode */ { int64_t p; int64_t nBatch = input->size(0); int64_t istride = nslices * itime * iwidth * iheight; int64_t ostride = nslices * otime * owidth * oheight; /* resize output */ THTensor_(resize5d)(output, nBatch, nslices, otime, oheight, owidth); /* indices will contain ti,i,j locations for each output point */ THIndexTensor_(resize5d)(indices, nBatch, nslices, otime, oheight, owidth); input_data = input->data<scalar_t>(); output_data = output->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); #pragma omp parallel for private(p) for (p=0; p < nBatch; p++) { THNN_(VolumetricDilatedMaxPooling_updateOutput_frame)( input_data + p * istride, output_data + p * ostride, indices_data + p * ostride, nslices, itime, iwidth, iheight, otime, owidth, oheight, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } } /* cleanup */ c10::raw::intrusive_ptr::decref(input); } static void THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( scalar_t *gradInput_p, scalar_t *gradOutput_p, THIndex_t *indz_p, int64_t nslices, int64_t itime, int64_t iwidth, int64_t iheight, int64_t otime, int64_t owidth, int64_t oheight, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) { int64_t k; #pragma omp parallel for private(k) for (k = 0; k < nslices; k++) { scalar_t *gradInput_p_k = gradInput_p + k * itime * iwidth * iheight; scalar_t *gradOutput_p_k = gradOutput_p + k * otime * owidth * oheight; THIndex_t *indz_p_k = indz_p + k * otime * owidth * oheight; /* calculate max points */ int64_t ti, i, j; for (ti = 0; ti < otime; ti++) { for (i = 0; i < oheight; i++) { for (j = 0; j < owidth; j++) { /* retrieve position of max */ int64_t index = ti * oheight * owidth + i * owidth + j; int64_t maxp = indz_p_k[index] - TH_INDEX_BASE; if (maxp != -1) { /* update gradient */ gradInput_p_k[maxp] += gradOutput_p_k[index]; } } } } } } void THNN_(VolumetricDilatedMaxPooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THIndexTensor *indices, int kT, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH, bool ceilMode) { int nslices; int itime; int iheight; int iwidth; int otime; int oheight; int owidth; scalar_t *gradInput_data; scalar_t *gradOutput_data; THIndex_t *indices_data; int dimN = 0; int dimt = 1; int dimh = 2; int dimw = 3; THNN_(VolumetricDilatedMaxPooling_shapeCheck)( state, input, gradOutput, indices, kT, kW, kH, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH, ceilMode); // TODO: gradOutput shape check /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->dim() == 5) { dimN++; dimt++; dimh++; dimw++; } /* sizes */ nslices = input->size(dimN); itime = input->size(dimt); iheight = input->size(dimh); iwidth = input->size(dimw); otime = gradOutput->size(dimt); oheight = gradOutput->size(dimh); owidth = gradOutput->size(dimw); /* get raw pointers */ gradInput_data = gradInput->data<scalar_t>(); gradOutput_data = gradOutput->data<scalar_t>(); indices_data = THIndexTensor_(data)(indices); /* backprop */ if (input->dim() == 4) /* non-batch mode*/ { THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( gradInput_data, gradOutput_data, indices_data, nslices, itime, iwidth, iheight, otime, owidth, oheight, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } else /* batch mode */ { int64_t p; int64_t nBatch = input->size(0); int64_t istride = nslices * itime * iwidth * iheight; int64_t ostride = nslices * otime * owidth * oheight; #pragma omp parallel for private(p) for (p = 0; p < nBatch; p++) { THNN_(VolumetricDilatedMaxPooling_updateGradInput_frame)( gradInput_data + p * istride, gradOutput_data + p * ostride, indices_data + p * ostride, nslices, itime, iwidth, iheight, otime, owidth, oheight, dT, dW, dH, pT, pW, pH, dilationT, dilationW, dilationH ); } } /* cleanup */ c10::raw::intrusive_ptr::decref(gradOutput); } #endif
jacobi_coarse.c
/* Solve the Poisson problem u_{xx} = f(x) x \in [a, b] with u(a) = alpha, u(b) = beta using Jacobi iterations and OpenMP using fine grain parallelism. */ // OpenMP library header #include <omp.h> // Standard IO libraries #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char* argv[]) { // Problem parameters double const a = 0.0, b = 1.0, alpha = 0.0, beta = 3.0; // Numerical parameters int const MAX_ITERATIONS = pow(2,16), PRINT_INTERVAL = 100; int num_points, N; double dx, tolerance, du_max, du_max_thread; // Work arrays double *x, *f, *u_old, *u; // OpenMP int num_threads, thread_ID, thread_num_points; int i, n, start_index, end_index; // File IO FILE *fp; num_threads = 1; #ifdef _OPENMP num_threads = 4; omp_set_num_threads(num_threads); printf("Using OpenMP with %d threads.\n", num_threads); #endif // Numerical discretization num_points = 100; dx = (b - a) / (num_points + 1); tolerance = 0.1 * pow(dx, 2); // Create work arrays x = malloc((num_points + 2) * sizeof(double)); u = malloc((num_points + 2) * sizeof(double)); u_old = malloc((num_points + 2) * sizeof(double)); f = malloc((num_points + 2) * sizeof(double)); // Set boundary conditions here before threads u[0] = alpha; u[num_points + 1] = beta; #pragma omp parallel private(thread_num_points, start_index, end_index, du_max_thread) { thread_ID = omp_get_thread_num(); thread_num_points = (num_points + num_threads - 1) / num_threads; start_index = thread_ID * thread_num_points + 1; end_index = fmin((thread_ID + 1) * thread_num_points, num_points); thread_num_points = end_index - start_index + 1; for (int i = start_index; i < end_index + 1; ++i) { x[i] = (double) i * dx + a; f[i] = exp(x[i]); u[i] = alpha + x[i] * (beta - alpha); } while (N < MAX_ITERATIONS) { for (int i = start_index; i < end_index + 1 + 2; ++i) u_old[i] = u[i]; du_max_thread = 0.0; for (int i = start_index; i < end_index + 1; ++i) { u[i] = 0.5 * (u_old[i-1] + u_old[i+1] - pow(dx, 2) * f[i]); du_max_thread = fmax(du_max_thread, fabs(u[i] - u_old[i])); } if (N%PRINT_INTERVAL == 0) printf("After %d iterations, du_max = %f\n", N, du_max); #pragma omp critical du_max = fmax(du_max, du_max_thread); #pragma omp barrier if (du_max < tolerance) break; N++; } } // Output Results // Check for failure if (N >= MAX_ITERATIONS) { printf("*** Jacobi failed to converge!\n"); printf("*** Reached du_max = %f\n", du_max); printf("*** Tolerance = %f\n", tolerance); return 1; } fp = fopen("jacobi_0.txt", "w"); for (int i = 0; i < num_points + 2; ++i) fprintf(fp, "%f %f\n", x[i], u[i]); fclose(fp); return 0; }
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] = 4; tile_size[1] = 4; tile_size[2] = 24; tile_size[3] = 128; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // 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,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+3,4)); ubp=min(floord(Nt+Nz-4,4),floord(2*t1+Nz-1,4)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-11,12)),ceild(4*t2-Nz-20,24));t3<=min(min(min(floord(4*t2+Ny,24),floord(Nt+Ny-4,24)),floord(2*t1+Ny+1,24)),floord(4*t1-4*t2+Nz+Ny-1,24));t3++) { for (t4=max(max(max(0,ceild(t1-63,64)),ceild(4*t2-Nz-124,128)),ceild(24*t3-Ny-124,128));t4<=min(min(min(min(floord(4*t2+Nx,128),floord(Nt+Nx-4,128)),floord(2*t1+Nx+1,128)),floord(24*t3+Nx+20,128)),floord(4*t1-4*t2+Nz+Nx-1,128));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),24*t3-Ny+2),128*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),24*t3+22),128*t4+126),4*t1-4*t2+Nz+1);t5++) { for (t6=max(max(4*t2,t5+1),-4*t1+4*t2+2*t5-3);t6<=min(min(4*t2+3,-4*t1+4*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(24*t3,t5+1);t7<=min(24*t3+23,t5+Ny-2);t7++) { lbv=max(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; }
amask_omp.c
/* Program omp_affinity reports the mask for each OMP thread, and works for nsec seconds (10). This allows one to inspect occupation through utilities like top (e.g. execute top, then hit the 1 key). Uses maskeraid utilities github.com/TACC/maskeraid map_to_procid(cpu_id): will set current thread to cpu_id amask_omp(): reports masks of the threads load_cpu_nsec(nsec): load the cpu for nsec (default 10) */ /* omp_affinity.c is a driver 1.) Get line arguments (optional): help or number of seconds for load 2.) Start OpenMP parallel region amask_omp() reports masks for each thread 3.) Set a work load on each thread 4.) Finish parallel region Kent Milfeld 12/16/15 Added cmd_line argument extraction. Kent Milfeld 2016/07/13 */ #include <stdio.h> #include <omp.h> #include "opts.h" void load_cpu_nsec(int nsec); void amask_omp(); int map_to_procid( int icore); int main(int argc, char *argv[]){ int nthrds, thrd, procid; //Thread info int nsec = 10; // Load, default time int ierr; // Error number // cmdln_get_nsec_or_help( &nsec, argc, argv); //optional, get nsec from cmd line Maskopts opts(argc,argv); #pragma omp parallel private(thrd,ierr) { thrd = omp_get_thread_num(); nthrds = omp_get_num_threads(); // procid = thrd; // set procid to thread number (thrd) // ierr = map_to_procid( procid ); // set your own affinity here amask_omp(); // Call mask reporter load_cpu_nsec( nsec ); // Load up rank process so user can watch top. } }
matrix_s.h
// // matrix.cpp // Define Class for Vector & Matrix // // Created by Yoshi Miyazaki on 2015/04/11. // #include "matrix.h" /*---------------------------------------- Vector Types Constructers ---------------------------------------*/ template<class T> Vector1d<T>::Vector1d(){ n = 0; v = 0; } template<class T> Vector1d<T>::Vector1d(int nn){ n = nn; v = new T[n]; } template<class T> Vector1d<T>::Vector1d(const T& a, int nn){ n = nn; v = new T[nn]; for (int i=0; i<nn; i++){ v[i] = a; } } template<class T> Vector1d<T>::Vector1d(const T* a, int nn){ n = nn; v = new T[n]; for (int i=0; i<nn; i++){ v[i] = *a++; } } template<class T> Vector1d<T>::Vector1d(const Vector1d<T> &copy){ n = copy.n; v = new T[n]; for (int i=0; i<n; i++){ v[i] = copy[i]; } } /*---------------------------------------- Operater ---------------------------------------*/ template<class T> // Substitution Vector1d<T>& Vector1d<T>::operator=(const Vector1d<T> &copy){ if (this != &copy){ if (n != copy.n){ if (v != 0) delete[] v; n = copy.n; v = new T[n]; } for (int i=0; i<n; i++){ v[i] = copy[i]; } } return *this; } template<class T> // i'th element Vector1d<T>& Vector1d<T>::operator=(const T &a){ for (int i=0; i<n; i++){ v[i] = a; } return *this; } template<class T> const bool Vector1d<T>::operator==(const Vector1d<T>& rhs) const{ if (n != rhs.n){ return 0; } else{ bool b = 1; for (int i=0; i<n; i++){ if (v[i] != rhs[i]){ b = 0; break; } } return b; } } template<class T> void Vector1d<T>::resize(int nn){ if (n != nn){ if (v != 0){ delete[] v; } n = nn; v = new T[n]; } } template<class T> void Vector1d<T>::resize(const T& a, int nn){ if (n != nn){ if (v != 0){ delete[] v; } n = nn; v = new T[n]; } for (int i=0; i<n; i++){ v[i] = a; } } /*---------------------------------------- Mathematical Operater ---------------------------------------*/ template<class T> const T Vector1d<T>::norm() const{ T norm = 0; for (int i=0; i<n; i++){ norm += v[i]*v[i]; } return sqrt(norm); } template<class T> const T Vector1d<T>::maxv() const{ T maxv = v[0]; for (int i=1; i<n; i++){ if (maxv < v[i]){maxv = v[i];} } return maxv; } template<class T> const T Vector1d<T>::minv() const{ T minv = v[0]; for (int i=1; i<n; i++){ if (minv > v[i]){minv = v[i];} } return minv; } template<class T> const T Vector1d<T>::average() const{ T ave = 0; for (int i=0; i<n; i++){ ave += v[i]; } return ave/double(n); } template<class T> /* maximum of abs(v[i]) */ const T Vector1d<T>::absmaxv() const{ T maxv = abs(v[0]); for (int i=1; i<n; i++){ if (maxv < abs(v[i])){maxv = abs(v[i]);} } return maxv; } template<class T> /* minimum of abs(v[i]) */ const T Vector1d<T>::absminv() const{ T minv = abs(v[0]); for (int i=1; i<n; i++){ if (minv > abs(v[i])){minv = abs(v[i]);} } return minv; } template<class T> /* minimum of abs(v[i]) */ const T Vector1d<T>::absnon0minv() const{ T minv = 1e100; for (int i=0; i<n; i++){ if ((minv > abs(v[i])) && (v[i] != 0)){minv = abs(v[i]);} } return minv; } template<class T> /* average of abs(v[i]) */ const T Vector1d<T>::absaverage() const{ T ave = 0; for (int i=0; i<n; i++){ ave += (v[i]>0 ? v[i] : -1.0*v[i]); } return ave/double(n); } template<class T> /* dot product */ const T Vector1d<T>::operator*(const Vector1d<T>& A){ int nA; nA = A.size(); T dotp = 0; if (nA != n){ cout << "size of vectors don't match. Revise your input." << endl; exit(7); } else{ for (int i=0; i<n; i++){ dotp += v[i]*A[i]; } return dotp; } } template<class T> Vector1d<T> Vector1d<T>::operator+(const Vector1d<T>& A){ int nA; nA = A.size(); if (nA != n){ cout << "size of vectors don't match. Revise your input." << endl; exit(7); } else{ Vector1d<double> sum(n); for (int i=0; i<n; i++){ sum[i] = v[i] + A[i]; } return sum; } } template<class T> Vector1d<T> Vector1d<T>::operator-(const Vector1d<T>& A){ int nA; nA = A.size(); if (nA != n){ cout << "size of vectors don't match. Revise your input." << endl; exit(7); } else{ Vector1d<double> sum(n); for (int i=0; i<n; i++){ sum[i] = v[i] - A[i]; } return sum; } } template<class T> Vector1d<T> Vector1d<T>::operator+(const T& A){ Vector1d<double> sum(n); for (int i=0; i<n; i++){ sum[i] = v[i] + A; } return sum; } template<class T> Vector1d<T> Vector1d<T>::operator-(const T& A){ Vector1d<double> sum(n); for (int i=0; i<n; i++){ sum[i] = v[i] - A; } return sum; } template<class T> Vector1d<T> Vector1d<T>::operator*(const T& A){ Vector1d<double> product(n); for (int i=0; i<n; i++){ product[i] = v[i] * A; } return product; } template<class T> Vector1d<T> Vector1d<T>::operator/(const T& A){ Vector1d<double> quotient(n); for (int i=0; i<n; i++){ quotient[i] = v[i] / A; } return quotient; } template<class T> Vector1d<T>& Vector1d<T>::operator+=(const Vector1d<T>& A){ int nA; nA = A.size(); if (nA != n){ cout << "size of vectors don't match. Revise your input." << endl; exit(7); } else{ for (int i=0; i<n; i++){ v[i] += A[i]; } return *this; } } template<class T> Vector1d<T>& Vector1d<T>::operator+=(const T& a){ for (int i=0; i<n; i++){ v[i] += a; } return *this; } template<class T> Vector1d<T>& Vector1d<T>::operator-=(const Vector1d<T>& A){ int nA; nA = A.size(); if (nA != n){ cout << "size of vectors don't match. Revise your input." << endl; exit(7); } else{ for (int i=0; i<n; i++){ v[i] -= A[i]; } return *this; } } template<class T> Vector1d<T>& Vector1d<T>::operator-=(const T& a){ for (int i=0; i<n; i++){ v[i] -= a; } return *this; } template<class T> Vector1d<T>& Vector1d<T>::operator*=(const T& a){ for (int i=0; i<n; i++){ v[i] *= a; } return *this; } template<class T> Vector1d<T>& Vector1d<T>::operator/=(const T& a){ for (int i=0; i<n; i++){ v[i] /= a; } return *this; } /*---------------------------------------- Destructers ---------------------------------------*/ template<class T> Vector1d<T>::~Vector1d<T>(){ if (v != 0){ delete[] (v); } } /*---------------------------------------- Matrix Types Constructers ---------------------------------------*/ template<class T> Matrix<T>::Matrix(){ n = 0; m = 0; v = 0; } template<class T> Matrix<T>::Matrix(int nn, int mm){ n = nn; m = mm; v = new T*[n]; v[0] = new T[m*n]; for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } } template<class T> Matrix<T>::Matrix(const T &a, int nn, int mm){ n = nn; m = mm; v = new T*[n]; v[0] = new T[m*n]; for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = a; } } } template<class T> Matrix<T>::Matrix(const T *a, int nn, int mm){ n = nn; m = mm; v = new T*[n]; v[0] = new T[m*n]; for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = *a++; } } } template<class T> Matrix<T>::Matrix(const Matrix &copy){ n = copy.n; m = copy.m; v = new T*[n]; v[0] = new T[m*n]; for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = copy[i][j]; } } } /*---------------------------------------- Operater ---------------------------------------*/ template<class T> Matrix<T>& Matrix<T>:: operator=(const Matrix<T> &copy){ if (this != &copy){ if (n != copy.n || m != copy.m){ if (v != 0){ delete v[0]; delete v; } n = copy.n; m = copy.m; v = new T*[n]; v[0] = new T[n*m]; } for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = copy[i][j]; } } } return *this; } template<class T> Matrix<T>& Matrix<T>:: operator=(const T &r){ for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = r; } } return *this; } template<class T> void Matrix<T>::resize(int nn, int mm){ if (n != nn || m != mm){ if (v != 0){ delete v[0]; delete v; } n = nn; m = mm; v = new T*[n]; v[0] = new T[n*m]; } for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } } template<class T> void Matrix<T>::resize(const T& a, int nn, int mm){ if (n != nn || m != mm){ if (v != 0){ delete v[0]; delete v; } n = nn; m = mm; v = new T*[n]; v[0] = new T[n*m]; } for (int i=1; i<n; i++){ v[i] = v[i-1] + m; } for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] = a; } } } /*---------------------------------------- Return row & column vector ---------------------------------------*/ template<class T> Vector1d<T> Matrix<T>::colvector(const int j){ Vector1d<T> rowv(n); for (int i=0; i<n; i++){ rowv[i] = v[i][j]; } return rowv; } template<class T> Vector1d<T> Matrix<T>::rowvector(const int i){ Vector1d<T> colv(m); for (int j=0; j<m; j++){ colv[j] = v[i][j]; } return colv; } /*---------------------------------------- Mathematical Operater ---------------------------------------*/ template<class T> Matrix<T> Matrix<T>::transpose(){ Matrix<T> tran(m,n); int i,j; for (i=0; i<n; i++){ for (j=0; j<m; j++){ tran[j][i] = v[i][j]; } } return tran; } template<class T> Matrix<T> Matrix<T>::lu_decomp(){ if (m != n){ cout << "unable to calculate the inverse" << endl; exit(25); } Matrix<T> lu(m,m); /* LU decomposition */ for (int i=0; i<m; i++){ /* calculate l_ij */ for (int j=i; j<m; j++){ lu[j][i] = v[j][i]; for (int k=0; k<i; k++){ lu[j][i] -= lu[k][i]*lu[j][k]; } } /* calculate u_ij */ for (int j=i+1; j<m; j++){ lu[i][j] = v[i][j]; for (int k=0; k<i; k++){ lu[i][j] -= lu[k][j]*lu[i][k]; } lu[i][j] /= lu[i][i]; } } return lu; } template<class T> void Matrix<T>::lu_linear(Vector1d<T>& A){ /* calculate solution */ for (int i=0; i<n; i++){ for (int k=0; k<i; k++){ A[i] -= v[i][k]*A[k]; } A[i] /= v[i][i]; } for (int i=n-1; i>=0; i--){ for (int k=i+1; k<n; k++){ A[i] -= v[i][k]*A[k]; } } } template<class T> Matrix<T> Matrix<T>::lu_inverse(){ /* matrix should already been LU decomposed */ if (m != n){ cout << "unable to calculate the inverse" << endl; exit(25); } /* prepare identiy matrix */ Matrix<T> inv(0.0,m,m); for (int i=0; i<m; i++){ inv[i][i] = 1.0; } /* calculate inverse */ for (int j=0; j<m; j++){ for (int i=0; i<n; i++){ for (int k=0; k<i; k++){ inv[i][j] -= v[i][k]*inv[k][j]; } inv[i][j] /= v[i][i]; } for (int i=n-1; i>=0; i--){ for (int k=i+1; k<n; k++){ inv[i][j] -= v[i][k]*inv[k][j]; } } } return inv; } template<class T> Matrix<T>& Matrix<T>::numeric0(double LIM){ /* find abs max value in matrix */ T absmaxv = 0.0; for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ if (abs(v[i][j]) > absmaxv) {absmaxv = abs(v[i][j]);} } } /* drop off all numeric error */ T eps = absmaxv*LIM*16; for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ if (abs(v[i][j]) < eps && v[i][j] != 0){ v[i][j] = 0; } } } return *this; } template<class T> Matrix<T>& Matrix<T>::operator+=(const Matrix<T>& B){ int nB = B.nrows(); int mB = B.mcols(); if ((nB != n) || (mB != m)){ cout << "size of matrixes don't match. Revise your input." << endl; exit(7); } else { for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] += B[i][j]; } } return *this; } } template<class T> Matrix<T>& Matrix<T>::operator-=(const Matrix<T>& B){ int nB = B.nrows(); int mB = B.mcols(); if ((nB != n) || (mB != m)){ cout << "size of matrixes don't match. Revise your input." << endl; exit(7); } else { for (int i=0; i<n; i++){ for (int j=0; j<m; j++){ v[i][j] -= B[i][j]; } } return *this; } } template<class T> Vector1d<T> Matrix<T>::operator*(Vector1d<T> &A){ int nA; nA = A.size(); // cout << n << m << nB << mB << endl; if (nA != m){ cout << "size of matrix & vector don't match. Revise your input. sizes: " << m << " & " << nA << endl; exit(7); } else{ Vector1d<T> product(n); for (int i=0; i<n; i++){ product[i] = 0; for (int k=0; k<m; k++){ product[i] += v[i][k]*A[k]; } } return product; } } template<class T> Matrix<T> Matrix<T>::operator*(Matrix<T> &B){ int nB, mB; nB = B.nrows(); mB = B.mcols(); // cout << n << m << nB << mB << endl; if (nB != m){ cout << "size of 2 matricies don't match. Revise your matrix." << endl; exit(7); } else{ Matrix<T> product(n,mB); int i,j,k; // int NUM_THREADS=omp_get_num_procs(); // omp_set_num_threads(NUM_THREADS); // #pragma omp parallel for private(j,k) for (i=0; i<n; i++){ for (j=0; j<mB; j++){ product[i][j] = 0; for (k=0; k<m; k++){ product[i][j] += v[i][k]*B[k][j]; } } } return product; } } /*---------------------------------------- Destructers ---------------------------------------*/ template<class T> Matrix<T>::~Matrix<T>(){ if (v!=0){ if (m!=0){ delete[] v[0]; } delete[] v; } }
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 32 #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 Cell47304 Cell47304; typedef struct Cellseq47320 Cellseq47320; typedef struct Gcheap49818 Gcheap49818; typedef struct Gcstack49816 Gcstack49816; typedef struct Memregion29485 Memregion29485; typedef struct Smallchunk29439 Smallchunk29439; typedef struct Llchunk29479 Llchunk29479; typedef struct Bigchunk29441 Bigchunk29441; typedef struct Intset29414 Intset29414; typedef struct Trunk29410 Trunk29410; typedef struct Avlnode29483 Avlnode29483; typedef struct Gcstat49814 Gcstat49814; typedef struct Cellset47316 Cellset47316; typedef struct Pagedesc47312 Pagedesc47312; 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 Basechunk29437 Basechunk29437; typedef struct Freecell29429 Freecell29429; 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 Cell47304 { NI refcount; TNimType* typ; }; struct Cellseq47320 { NI len; NI cap; Cell47304** d; }; typedef Smallchunk29439* TY29500[512]; typedef Trunk29410* Trunkbuckets29412[256]; struct Intset29414 { Trunkbuckets29412 data; }; struct Memregion29485 { NI minlargeobj; NI maxlargeobj; TY29500 freesmallchunks; Llchunk29479* llmem; NI currmem; NI maxmem; NI freemem; NI lastsize; Bigchunk29441* freechunkslist; Intset29414 chunkstarts; Avlnode29483* root; Avlnode29483* deleted; Avlnode29483* last; Avlnode29483* freeavlnodes; NIM_BOOL locked; }; struct Gcstat49814 { NI stackscans; NI cyclecollections; NI maxthreshold; NI maxstacksize; NI maxstackcells; NI cycletablesize; NI64 maxpause; }; struct Cellset47316 { NI counter; NI max; Pagedesc47312* head; Pagedesc47312** data; }; struct Gcheap49818 { Gcstack49816* stack; void* stackbottom; NI cyclethreshold; Cellseq47320 zct; Cellseq47320 decstack; Cellseq47320 tempstack; NI recgclock; Memregion29485 region; Gcstat49814 stat; Cellset47316 marked; Cellseq47320 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* TY558764[4]; typedef NimStringDesc* TY553828[42]; typedef NimStringDesc* TY553281[7]; typedef NU8 Trenderflag313004Set; typedef NimStringDesc* TY559052[2]; typedef NU8 Tclosuretypekind537679; 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 Basechunk29437 { NI prevsize; NI size; NIM_BOOL used; }; struct Smallchunk29439 { Basechunk29437 Sup; Smallchunk29439* next; Smallchunk29439* prev; Freecell29429* freelist; NI free; NI acc; NF data; }; struct Llchunk29479 { NI size; NI acc; Llchunk29479* next; }; struct Bigchunk29441 { Basechunk29437 Sup; Bigchunk29441* next; Bigchunk29441* prev; NI align; NF data; }; typedef NI TY29418[16]; struct Trunk29410 { Trunk29410* next; NI key; TY29418 bits; }; typedef Avlnode29483* TY29490[2]; struct Avlnode29483 { TY29490 link; NI key; NI upperbound; NI level; }; struct Pagedesc47312 { Pagedesc47312* next; NI key; TY29418 bits; }; struct Trunk270026 { Trunk270026* next; NI key; TY29418 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 Freecell29429 { Freecell29429* 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(Cell47304*, usrtocell_51440_1689653243)(void* usr0); static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47304* c0); N_NOINLINE(void, addzct_51417_1689653243)(Cellseq47320* s0, Cell47304* 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_565045_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)(Cell47304* c0); static N_INLINE(void, decref_53001_1689653243)(Cell47304* 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_535596_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_194264_155036129)(NI32 fileidx0); N_NIMCALL(TGenericSeq*, setLengthSeq)(TGenericSeq* seq0, NI elemsize0, NI newlen0); N_NIMCALL(NimStringDesc*, tofilename_194260_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_565204_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_340746_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_535548_839829468)(Ttype294840* rettype0); N_NIMCALL(Tctypekind531007, maptype_535393_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_535476_839829468)(Ttype294840* t0); N_NIMCALL(NIM_BOOL, needscomplexassignment_535509_839829468)(Ttype294840* typ0); N_NIMCALL(NIM_BOOL, containsgarbagecollectedref_322117_3876443242)(Ttype294840* typ0); static N_INLINE(NIM_BOOL, isobjlackingtypefield_535513_839829468)(Ttype294840* typ0); N_NIMCALL(NIM_BOOL, ispureobject_322138_3876443242)(Ttype294840* typ0); N_NIMCALL(Ropeobj180006*, gettypedescaux_535503_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_535591_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_535449_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_535609_839829468)(Tsym294834* s0); N_NIMCALL(Tctypekind531007, mapreturntype_535445_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_337227_1724185294)(Tsym294834* s0); N_NIMCALL(Ropeobj180006*, localvardecl_540532_839829468)(Tcproc531021* p0, Tsym294834* s0); N_NIMCALL(Ropeobj180006*, gettypedesc_537671_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_538549_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_538597_839829468)(Tcgen531027* m0, Ttype294840* typ0, Ropeobj180006* name0); N_NIMCALL(void, genobjectinfo_538506_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_561442_839829468)(Tlib294820* lib0); N_NIMCALL(void, loaddynamiclib_561480_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_551788_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_551750_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_299440_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_194068_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_558728_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_558666_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_557139_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_557110_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_558480_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(Ropeobj180006*, getclosuretype_537683_839829468)(Tcgen531027* m0, Ttype294840* t0, Tclosuretypekind537679 kind0); N_NIMCALL(void, genord_558474_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_557857_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_555153_839829468)(Tcproc531021* p0, Ttype294840* ty_555156_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_295678_850551059)(Tnodekind294020 kind0, NimStringDesc* strval0); N_NIMCALL(void, gencast_558537_839829468)(Tcproc531021* p0, Tnode294802* e0, Tloc294816* d0); N_NIMCALL(void, genconv_558632_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_558590_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0, NimStringDesc* magic0); N_NIMCALL(void, convstrtocstr_558642_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(void, convcstrtostr_558654_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_299323_850551059)(Tsym294834* s0); N_NIMCALL(void, genwhilestmt_547984_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_549826_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0); N_NIMCALL(void, genstringcase_549416_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_549724_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0); N_NIMCALL(NI, ifswitchsplitpoint_549615_839829468)(Tcproc531021* p0, Tnode294802* n0); N_NIMCALL(NIM_BOOL, branchhastoobigrange_549575_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_549865_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_299279_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_565152_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_535585_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 TY558764 opr_558762_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_194072_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(Cell47304*, usrtocell_51440_1689653243)(void* usr0) { Cell47304* result0; result0 = (Cell47304*)0; result0 = ((Cell47304*) ((NI)((NU32)(((NI) (usr0))) - (NU32)(((NI)sizeof(Cell47304)))))); return result0; } static N_INLINE(void, rtladdzct_52601_1689653243)(Cell47304* c0) { addzct_51417_1689653243((&gch_49858_1689653243.zct), c0); } static N_INLINE(void, asgnRefNoCycle)(void** dest0, void* src0) { { Cell47304* c0; if (!!((src0 == NIM_NIL))) goto LA3; c0 = usrtocell_51440_1689653243(src0); (*c0).refcount += ((NI) 8); } LA3: ; { Cell47304* c0; if (!!(((*dest0) == NIM_NIL))) goto LA7; c0 = usrtocell_51440_1689653243((*dest0)); { (*c0).refcount -= ((NI) 8); if (!((NU32)((*c0).refcount) < (NU32)(((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) { Cell47304* c0; c0 = usrtocell_51440_1689653243(p0); { (*c0).refcount -= ((NI) 8); if (!((NU32)((*c0).refcount) < (NU32)(((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)(Cell47304* c0) { (*c0).refcount = (NI)((NU32)((*c0).refcount) + (NU32)(((NI) 8))); } static N_INLINE(void, decref_53001_1689653243)(Cell47304* c0) { { (*c0).refcount -= ((NI) 8); if (!((NU32)((*c0).refcount) < (NU32)(((NI) 8)))) goto LA3; rtladdzct_52601_1689653243(c0); } LA3: ; } static N_INLINE(void, asgnRef)(void** dest0, void* src0) { { Cell47304* LOC5; if (!!((src0 == NIM_NIL))) goto LA3; LOC5 = (Cell47304*)0; LOC5 = usrtocell_51440_1689653243(src0); incref_53419_1689653243(LOC5); } LA3: ; { Cell47304* LOC10; if (!!(((*dest0) == NIM_NIL))) goto LA8; LOC10 = (Cell47304*)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_535596_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_535596_839829468(result0)); asgnRefNoCycle((void**) (&(*result0).nimtypesname), gettempname_535596_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_194264_155036129(((NI32) ((*module0).position))); result0 = rawnewmodule_564663_839829468(module0, LOC1); return result0; } N_NIMCALL(Tcgen531027*, newmodule_565045_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_194260_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_565115_839829468)(Tsym294834* module0) { Tpasscontext343002* result0; Tcgen531027* LOC1; result0 = (Tpasscontext343002*)0; LOC1 = (Tcgen531027*)0; LOC1 = newmodule_565045_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_565204_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_565249_839829468)(Tsym294834* module0, Trodreader334021* rd0) { Tpasscontext343002* result0; Tcgen531027* m0; NimStringDesc* LOC1; result0 = (Tpasscontext343002*)0; m0 = newmodule_565045_839829468(module0); LOC1 = (NimStringDesc*)0; LOC1 = getcfile_565204_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_194072_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_194264_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_535393_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_535393_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_535393_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_535393_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_535476_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_535509_839829468)(Ttype294840* typ0) { NIM_BOOL result0; result0 = (NIM_BOOL)0; result0 = containsgarbagecollectedref_322117_3876443242(typ0); return result0; } static N_INLINE(NIM_BOOL, isobjlackingtypefield_535513_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_535548_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_535393_839829468(rettype0); switch (LOC6) { case ((Tctypekind531007) 17): { Ttype294840* LOC8; LOC8 = (Ttype294840*)0; LOC8 = skiptypes_298099_850551059(rettype0, IL64(211106232576256)); result0 = !(((*LOC8).kind == ((Ttypekind294244) 23) || (*LOC8).kind == ((Ttypekind294244) 22) || (*LOC8).kind == ((Ttypekind294244) 21))); } 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_535476_839829468(rettype0); if (LOC12) goto LA13; LOC12 = isimportedcpptype_535476_839829468(t0); LA13: ; if (!LOC12) goto LA14; result0 = NIM_FALSE; goto BeforeRet; } LA14: ; LOC16 = (NIM_BOOL)0; LOC16 = needscomplexassignment_535509_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_535513_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_535591_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_535591_839829468((*m0).typecache, typ0); } LA8: ; } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, isimportedtype_535449_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_535591_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_535449_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_535476_839829468(etb0); if (!(LOC4)) goto LA5; LOC4 = ((*t0).kind == ((Ttypekind294244) 11)); LA5: ; if (!LOC4) goto LA6; result0 = gettypedescaux_535503_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_535503_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_535476_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_535503_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_535503_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_535503_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_535503_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_535503_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_535503_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_535503_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_535476_839829468(typ0); if (LOC20) goto LA21; LOC20 = isimportedcpptype_535476_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 (!((*etb0).kind == ((Ttypekind294244) 4) || (*etb0).kind == ((Ttypekind294244) 16) || (*etb0).kind == ((Ttypekind294244) 27) || (*etb0).kind == ((Ttypekind294244) 48))) 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_535476_839829468(etb0); if (!(LOC46)) goto LA47; LOC46 = ((*et0).kind == ((Ttypekind294244) 11)); LA47: ; if (!LOC46) goto LA48; LOC50 = (Ropeobj180006*)0; LOC50 = gettypedescaux_535503_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_535503_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_535591_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_535476_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_537648_839829468; NI LOC109; NI res_537651_839829468; i_537144_839829468 = (NI)0; HEX3Atmp_537648_839829468 = (NI)0; LOC109 = (NI)0; LOC109 = len_295081_850551059((*t0).n); HEX3Atmp_537648_839829468 = (NI)(LOC109 - ((NI) 1)); res_537651_839829468 = ((NI) 0); { while (1) { Tsym294834* field0; TY205018 LOC112; NimStringDesc* LOC113; if (!(res_537651_839829468 <= HEX3Atmp_537648_839829468)) goto LA111; i_537144_839829468 = res_537651_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_537651_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_535449_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_535585_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_535591_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_535449_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_535449_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_535503_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_535449_839829468(t_536942_839829468); if (!!(LOC177)) goto LA178; foo0 = gettypedescaux_535503_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_535476_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_535503_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_537664_839829468; NI LOC218; NI res_537667_839829468; i_537516_839829468 = (NI)0; HEX3Atmp_537664_839829468 = (NI)0; LOC218 = (NI)0; LOC218 = len_297339_850551059(typ0); HEX3Atmp_537664_839829468 = (NI)(LOC218 - ((NI) 2)); res_537667_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC225; if (!(res_537667_839829468 <= HEX3Atmp_537664_839829468)) goto LA220; i_537516_839829468 = res_537667_839829468; { if (!(((NI) 1) < i_537516_839829468)) goto LA223; add_180487_2381377266(&result0, ((NimStringDesc*) &T839829468_83)); } LA223: ; LOC225 = (Ropeobj180006*)0; LOC225 = gettypedescaux_535503_839829468(m0, (*typ0).sons->data[i_537516_839829468], check0); add_180482_2381377266(&result0, LOC225); res_537667_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_535591_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_535449_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_535449_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_535449_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_535503_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 = ((*t0).kind == ((Ttypekind294244) 8) || (*t0).kind == ((Ttypekind294244) 59)); 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 (!!(((*LOC3).kind == ((Ttypekind294244) 16) || (*LOC3).kind == ((Ttypekind294244) 27) || (*LOC3).kind == ((Ttypekind294244) 48) || (*LOC3).kind == ((Ttypekind294244) 4)))) goto LA4; result0 = ((Tstorageloc294812) 2); } goto LA1; LA4: ; { result0 = ((Tstorageloc294812) 0); } LA1: ; return result0; } N_NIMCALL(NIM_BOOL, ccgintroducedptr_535609_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_535445_839829468)(Ttype294840* typ0) { Tctypekind531007 result0; result0 = (Tctypekind531007)0; result0 = maptype_535393_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_535548_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_535503_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_535609_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_535503_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 (!((*arr0).kind == ((Ttypekind294244) 27) || (*arr0).kind == ((Ttypekind294244) 48))) 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_535548_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_535445_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_535503_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_535585_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_537671_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_535503_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_537671_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_535513_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_537671_839829468(m0, origtype0); } goto LA7; LA14: ; { size0 = gettypedesc_537671_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_538549_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_535596_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_538571_839829468; NI HEX3Atmp_538590_839829468; NI res_538593_839829468; i_538571_839829468 = (NI)0; HEX3Atmp_538590_839829468 = (NI)0; HEX3Atmp_538590_839829468 = (NI)(length0 - ((NI) 1)); res_538593_839829468 = ((NI) 0); { while (1) { Ttype294840* a0; Ropeobj180006* tmp20; TY537238 LOC10; TY537235 LOC11; if (!(res_538593_839829468 <= HEX3Atmp_538590_839829468)) goto LA9; i_538571_839829468 = res_538593_839829468; a0 = (*typ0).sons->data[i_538571_839829468]; tmp20 = getnimnode_537945_839829468(m0); memset((void*)LOC10, 0, sizeof(LOC10)); LOC10[0] = tmp0; LOC10[1] = rope_180401_2381377266(((NI64) (i_538571_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_537671_839829468(m0, typ0); LOC11[2] = rope_180401_2381377266(((NI64) (i_538571_839829468))); LOC11[3] = gentypeinfo_537941_839829468(m0, a0); addf_181205_2381377266(&(*m0).s[(((Tcfilesection531005) 14))- 0], ((NimStringDesc*) &T839829468_141), LOC11, 4); res_538593_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 = ((*t0).kind == ((Ttypekind294244) 16) || (*t0).kind == ((Ttypekind294244) 4) || (*t0).kind == ((Ttypekind294244) 19) || (*t0).kind == ((Ttypekind294244) 18) || (*t0).kind == ((Ttypekind294244) 17)); 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_535393_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_537671_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_535476_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_537671_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_535596_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_537671_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_537671_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_549676_839829468; NI HEX3Atmp_549717_839829468; NI res_549720_839829468; j_549676_839829468 = (NI)0; HEX3Atmp_549717_839829468 = (NI)0; HEX3Atmp_549717_839829468 = (NI)(length0 - ((NI) 2)); res_549720_839829468 = ((NI) 0); { while (1) { if (!(res_549720_839829468 <= HEX3Atmp_549717_839829468)) goto LA3; j_549676_839829468 = res_549720_839829468; { Tnode294802* LOC6; LOC6 = (Tnode294802*)0; LOC6 = HEX5BHEX5D_295238_850551059(branch0, j_549676_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_549676_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_549676_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_549676_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_549676_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_549676_839829468); LOC27[0] = genliteral_541273_839829468(p0, LOC28); linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_180), LOC27, 1); } LA4: ; res_549720_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_535596_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_537671_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 (!((*LOC14).kind == ((Ttypekind294244) 4) || (*LOC14).kind == ((Ttypekind294244) 16))) 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_538597_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_535596_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_538622_839829468; NI HEX3Atmp_538860_839829468; NI res_538863_839829468; i_538622_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_538622_839829468 = res_538863_839829468; field0 = (*(*(*typ0).n).kindU.S6.sons->data[i_538622_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_538622_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_538622_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_535596_839829468(m0); counter0 = gettempname_535596_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_535596_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_537671_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_538499_839829468; NI LOC21; NI res_538502_839829468; i_538421_839829468 = (NI)0; HEX3Atmp_538499_839829468 = (NI)0; LOC21 = (NI)0; LOC21 = sonslen_297351_850551059(n0); HEX3Atmp_538499_839829468 = (NI)(LOC21 - ((NI) 1)); res_538502_839829468 = ((NI) 1); { while (1) { Tnode294802* b0; Ropeobj180006* tmp20; Tnode294802* LOC24; if (!(res_538502_839829468 <= HEX3Atmp_538499_839829468)) goto LA23; i_538421_839829468 = res_538502_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_538492_839829468; NI LOC32; NI res_538495_839829468; j_538436_839829468 = (NI)0; HEX3Atmp_538492_839829468 = (NI)0; LOC32 = (NI)0; LOC32 = sonslen_297351_850551059(b0); HEX3Atmp_538492_839829468 = (NI)(LOC32 - ((NI) 2)); res_538495_839829468 = ((NI) 0); { while (1) { if (!(res_538495_839829468 <= HEX3Atmp_538492_839829468)) goto LA34; j_538436_839829468 = res_538495_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_538495_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_538502_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_537671_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_538506_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_535476_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_538549_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_538597_839829468(m0, t0, result0); } break; case ((Ttypekind294244) 17): { genobjectinfo_538506_839829468(m0, t0, origtype0, result0); } break; case ((Ttypekind294244) 18): { gentupleinfo_538549_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 (!((*LOC7).kind == ((Ttypekind294244) 27) || (*LOC7).kind == ((Ttypekind294244) 48))) 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_535609_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_535445_839829468((*param0).typ); LOC5 = !((LOC6 == ((Tctypekind531007) 17))); if (!(LOC5)) goto LA7; LOC5 = isinvalidreturntype_535548_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_537671_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_535548_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_337227_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_337227_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_561442_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 = ((*(*n0).typ).kind == ((Ttypekind294244) 26) || (*(*n0).typ).kind == ((Ttypekind294244) 25)); 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_561480_839829468)(Tcgen531027* m0, Tlib294820* lib0) { { Ropeobj180006* tmp0; TY180507 LOC5; if (!!((*lib0).generated)) goto LA3; (*lib0).generated = NIM_TRUE; tmp0 = gettempname_535596_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_561442_839829468(lib0); extname0 = (*sym0).loc.r; { if (!!(iscall0)) goto LA3; loaddynamiclib_561480_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_537671_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_537671_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_537671_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_537671_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_537671_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_537671_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_340746_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_537671_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_537671_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_551788_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_551788_839829468(dest0, t0, field0, (&LOC15)); memset((void*)(&LOC16), 0, sizeof(LOC16)); optasgnloc_551788_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_551750_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_551767_839829468; t_551767_839829468 = (Tnode294802*)0; { NI i_551781_839829468; NI HEX3Atmp_551783_839829468; NI LOC10; NI res_551785_839829468; i_551781_839829468 = (NI)0; HEX3Atmp_551783_839829468 = (NI)0; LOC10 = (NI)0; LOC10 = len_295081_850551059(n0); HEX3Atmp_551783_839829468 = (LOC10 - 1); res_551785_839829468 = ((NI) 0); { while (1) { NI LOC13; if (!(res_551785_839829468 <= HEX3Atmp_551783_839829468)) goto LA12; i_551781_839829468 = res_551785_839829468; t_551767_839829468 = (*n0).kindU.S6.sons->data[i_551781_839829468]; LOC13 = (NI)0; LOC13 = asgncomplexity_551750_839829468(t_551767_839829468); result0 += LOC13; res_551785_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_551788_839829468(dest0, (*field0).typ, (*field0).loc.r, (&LOC14)); memset((void*)(&LOC15), 0, sizeof(LOC15)); optasgnloc_551788_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_535509_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_551788_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_551788_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_535509_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_535476_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_535513_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_535509_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_551750_839829468((*ty0).n); LOC85 = (LOC87 <= ((NI) 4)); LA86: ; if (!LOC85) goto LA88; LOC90 = (Ropeobj180006*)0; LOC90 = gettypedesc_537671_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_535509_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_537671_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_535509_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_535393_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 = !(((*t0).kind == ((Ttypekind294244) 18) || (*t0).kind == ((Ttypekind294244) 17) || (*t0).kind == ((Ttypekind294244) 16) || (*t0).kind == ((Ttypekind294244) 4) || (*t0).kind == ((Ttypekind294244) 19) || (*t0).kind == ((Ttypekind294244) 24))); 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_535596_839829468((*p0).module); memset((void*)LOC18, 0, sizeof(LOC18)); LOC18[0] = gettypedesc_537671_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_537671_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_537671_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_537671_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_299440_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 = ((*t0).kind == ((Ttypekind294244) 62) || (*t0).kind == ((Ttypekind294244) 7)); 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_194068_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_194264_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_194260_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_558728_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_558762_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_537671_839829468((*p0).module, t0); } LA1: ; result0 = gettempname_535596_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 = ((*t0).kind == ((Ttypekind294244) 20) || (*t0).kind == ((Ttypekind294244) 14)); 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_537671_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_537671_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_537671_839829468((*p0).module, LOC9); LOC8[2] = gettypedesc_537671_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_558666_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_557139_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 (!((*t0).kind == ((Ttypekind294244) 23) || (*t0).kind == ((Ttypekind294244) 21) || (*t0).kind == ((Ttypekind294244) 22))) 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_535513_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_557139_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_557139_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_537671_839829468((*p0).module, LOC6); sizeexpr0 = HEX25_180905_2381377266(((NimStringDesc*) &T839829468_419), LOC5, 1); } LA3: ; memset((void*)args0, 0, sizeof(args0)); args0[0] = gettypedesc_537671_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_557110_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_537671_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_537671_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_537671_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_537671_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_537683_839829468)(Tcgen531027* m0, Ttype294840* t0, Tclosuretypekind537679 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_535596_839829468(m0); rettype0 = (Ropeobj180006*)0; desc0 = (Ropeobj180006*)0; genprocparams_536115_839829468(m0, t0, &rettype0, &desc0, (&check0), !((kind0 == ((Tclosuretypekind537679) 0))), NIM_FALSE); { NIM_BOOL LOC3; LOC3 = (NIM_BOOL)0; LOC3 = isimportedtype_535449_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 == ((Tclosuretypekind537679) 2))); LA9: ; if (!LOC8) goto LA10; memset((void*)LOC12, 0, sizeof(LOC12)); LOC12[0] = rope_180277_2381377266(Callingconvtostr_535585_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_558480_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 = ((*etyp0).kind == ((Ttypekind294244) 18) || (*etyp0).kind == ((Ttypekind294244) 17) || (*etyp0).kind == ((Ttypekind294244) 16) || (*etyp0).kind == ((Ttypekind294244) 27) || (*etyp0).kind == ((Ttypekind294244) 48) || (*etyp0).kind == ((Ttypekind294244) 4)); 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_537671_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_537683_839829468((*p0).module, etyp0, ((Tclosuretypekind537679) 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_537671_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_558474_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_537671_839829468((*p0).module, t0); LOC8[3] = gettypedesc_537671_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_557857_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 (!((*LOC13).kind == ((Ttypekind294244) 31) || (*LOC13).kind >= ((Ttypekind294244) 33) && (*LOC13).kind <= ((Ttypekind294244) 35))) 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_557857_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_557857_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_557857_839829468(p0, e0, d0, ((NimStringDesc*) &T839829468_473)); } break; case ((Tmagic294524) 40): { binarystmtinexcl_557857_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 (!((*LOC6).kind == ((Ttypekind294244) 27) || (*LOC6).kind == ((Ttypekind294244) 48))) 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_535609_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_537683_839829468((*p0).module, t0, ((Tclosuretypekind537679) 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_535476_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_535548_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_537671_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_535548_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_535548_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_557103_839829468; NI res_557106_839829468; i_557090_839829468 = (NI)0; HEX3Atmp_557103_839829468 = (NI)0; HEX3Atmp_557103_839829468 = (NI)(L0 - ((NI) 1)); res_557106_839829468 = ((NI) 0); { while (1) { Ttype294840* LOC14; Ttype294840* LOC15; TY534811 LOC16; Ttype294840* LOC17; Ttype294840* LOC18; TY534811 LOC19; if (!(res_557106_839829468 <= HEX3Atmp_557103_839829468)) goto LA13; i_557090_839829468 = res_557106_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_557106_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_535393_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_558728_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 = ((*underlying0).kind >= ((Ttypekind294244) 40) && (*underlying0).kind <= ((Ttypekind294244) 44)); 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_537671_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_558666_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_557110_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_537671_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_558480_839829468(p0, e0, d0); } break; case ((Tmagic294524) 28): { genord_558474_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_537671_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_537671_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_537671_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 (!!(((*t0).kind == ((Ttypekind294244) 24) || (*t0).kind == ((Ttypekind294244) 28)))) 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_537671_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_537671_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_537671_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_555153_839829468)(Tcproc531021* p0, Ttype294840* ty_555156_839829468, Tsym294834* field0, Ropeobj180006** r0) { Tsym294834* result0; Ttype294840* ty0; result0 = (Tsym294834*)0; ty0 = ty_555156_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_555153_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_295678_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_537671_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_555153_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_558537_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 = ((*destt0).kind >= ((Ttypekind294244) 36) && (*destt0).kind <= ((Ttypekind294244) 39) || (*destt0).kind == ((Ttypekind294244) 18) || (*destt0).kind == ((Ttypekind294244) 17) || (*destt0).kind == ((Ttypekind294244) 16) || (*destt0).kind == ((Ttypekind294244) 4)); if (LOC3) goto LA4; LOC3 = ((*srct0).kind >= ((Ttypekind294244) 36) && (*srct0).kind <= ((Ttypekind294244) 39) || (*srct0).kind == ((Ttypekind294244) 18) || (*srct0).kind == ((Ttypekind294244) 17) || (*srct0).kind == ((Ttypekind294244) 16) || (*srct0).kind == ((Ttypekind294244) 4)); 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_537671_839829468((*p0).module, srct0); LOC8[1] = gettypedesc_537671_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_558480_839829468(p0, e0, d0); } LA1: ; } N_NIMCALL(void, genconv_558632_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_558480_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 (!((*LOC3).kind == ((Ttypekind294244) 22) || (*LOC3).kind == ((Ttypekind294244) 21))) 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_535393_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 (!((*ty0).kind == ((Ttypekind294244) 22) || (*ty0).kind == ((Ttypekind294244) 21))) 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 (!((*LOC23).kind == ((Ttypekind294244) 22) || (*LOC23).kind == ((Ttypekind294244) 21))) 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_537671_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 (!((*ty0).kind == ((Ttypekind294244) 22) || (*ty0).kind == ((Ttypekind294244) 21))) 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_535393_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_537671_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_555153_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_555153_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_299440_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_299440_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_299440_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 = ((*LOC10).kind == ((Ttypekind294244) 22) || (*LOC10).kind == ((Ttypekind294244) 21) || (*LOC10).kind == ((Ttypekind294244) 23)); { 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 = ((*LOC28).kind == ((Ttypekind294244) 22) || (*LOC28).kind == ((Ttypekind294244) 21) || (*LOC28).kind == ((Ttypekind294244) 23)); 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_535513_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 (!((*t0).kind == ((Ttypekind294244) 23) || (*t0).kind == ((Ttypekind294244) 21) || (*t0).kind == ((Ttypekind294244) 22))) 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_537671_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_537671_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_558590_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 = ((*LOC5).kind >= ((Ttypekind294244) 40) && (*LOC5).kind <= ((Ttypekind294244) 44)); 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_537671_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_537671_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_558642_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_558654_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_299323_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_299323_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_537671_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_547933_839829468; NI LOC2; NI res_547936_839829468; i_547768_839829468 = (NI)0; HEX3Atmp_547933_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_295081_850551059(n0); HEX3Atmp_547933_839829468 = (LOC2 - 1); res_547936_839829468 = ((NI) 0); { while (1) { Tnode294802* it0; if (!(res_547936_839829468 <= HEX3Atmp_547933_839829468)) goto LA4; i_547768_839829468 = res_547936_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_547936_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_547941_839829468; NI res_547944_839829468; i_547819_839829468 = (NI)0; HEX3Atmp_547941_839829468 = (NI)0; HEX3Atmp_547941_839829468 = (NI)(arraysize0 - ((NI) 1)); res_547944_839829468 = ((NI) 1); { while (1) { TY180507 LOC32; if (!(res_547944_839829468 <= HEX3Atmp_547941_839829468)) goto LA31; i_547819_839829468 = res_547944_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_547944_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_547949_839829468; NI HEX3Atmp_547950_839829468; NI LOC35; NI res_547953_839829468; j_547854_839829468 = (NI)0; HEX3Atmp_547949_839829468 = (NI)0; HEX3Atmp_547950_839829468 = (NI)0; HEX3Atmp_547949_839829468 = (NI)(casepos0 + ((NI) 1)); LOC35 = (NI)0; LOC35 = len_295081_850551059(n0); HEX3Atmp_547950_839829468 = (LOC35 - 1); res_547953_839829468 = HEX3Atmp_547949_839829468; { while (1) { if (!(res_547953_839829468 <= HEX3Atmp_547950_839829468)) goto LA37; j_547854_839829468 = res_547953_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[j_547854_839829468]); res_547953_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_547958_839829468; NI res_547961_839829468; j_547866_839829468 = (NI)0; HEX3Atmp_547958_839829468 = (NI)0; HEX3Atmp_547958_839829468 = (NI)(casepos0 - ((NI) 1)); res_547961_839829468 = ((NI) 0); { while (1) { if (!(res_547961_839829468 <= HEX3Atmp_547958_839829468)) goto LA40; j_547866_839829468 = res_547961_839829468; genstmts_541244_839829468(p0, (*n0).kindU.S6.sons->data[j_547866_839829468]); res_547961_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_547977_839829468; NI LOC43; NI res_547980_839829468; i_547894_839829468 = (NI)0; HEX3Atmp_547977_839829468 = (NI)0; LOC43 = (NI)0; LOC43 = len_295081_850551059(casestmt0); HEX3Atmp_547977_839829468 = (LOC43 - 1); res_547980_839829468 = ((NI) 1); { while (1) { TY535289 LOC46; NI LOC47; Tnode294802* it0; Tnode294802* LOC57; Ropeobj180006** LOC58; Ropeobj180006** LOC59; Tloc294816 a0; TY534811 LOC60; if (!(res_547980_839829468 <= HEX3Atmp_547977_839829468)) goto LA45; i_547894_839829468 = res_547980_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_547969_839829468; NI LOC49; NI res_547972_839829468; j_547910_839829468 = (NI)0; HEX3Atmp_547969_839829468 = (NI)0; LOC49 = (NI)0; LOC49 = len_295081_850551059(it0); HEX3Atmp_547969_839829468 = (NI)(LOC49 - ((NI) 2)); res_547972_839829468 = ((NI) 0); { while (1) { NI64 val0; TY180507 LOC56; if (!(res_547972_839829468 <= HEX3Atmp_547969_839829468)) goto LA51; j_547910_839829468 = res_547972_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_547972_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_547980_839829468 += ((NI) 1); } LA45: ; } } }BeforeRet: ; } N_NIMCALL(void, genwhilestmt_547984_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_561480_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_537671_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_537671_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_537671_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_535596_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_535548_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 = ((*(*c0).typ).kind == ((Ttypekind294244) 4) || (*(*c0).typ).kind == ((Ttypekind294244) 16) || (*(*c0).typ).kind == ((Ttypekind294244) 19) || (*(*c0).typ).kind == ((Ttypekind294244) 18) || (*(*c0).typ).kind == ((Ttypekind294244) 24)); 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_549409_839829468; NI res_549412_839829468; i_549122_839829468 = (NI)0; HEX3Atmp_549409_839829468 = (NI)0; HEX3Atmp_549409_839829468 = (NI)(length0 - ((NI) 2)); res_549412_839829468 = ((NI) 0); { while (1) { NI j0; NI64 LOC4; TY537238 LOC5; if (!(res_549412_839829468 <= HEX3Atmp_549409_839829468)) goto LA3; i_549122_839829468 = res_549412_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_549412_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_299440_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_549416_839829468)(Tcproc531021* p0, Tnode294802* t0, Tloc294816* d0) { NI strings0; strings0 = ((NI) 0); { NI i_549434_839829468; NI HEX3Atmp_549549_839829468; NI LOC2; NI res_549552_839829468; i_549434_839829468 = (NI)0; HEX3Atmp_549549_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(t0); HEX3Atmp_549549_839829468 = (NI)(LOC2 - ((NI) 1)); res_549552_839829468 = ((NI) 1); { while (1) { if (!(res_549552_839829468 <= HEX3Atmp_549549_839829468)) goto LA4; i_549434_839829468 = res_549552_839829468; { NI LOC9; if (!((*(*t0).kindU.S6.sons->data[i_549434_839829468]).kind == ((Tnodekind294020) 85))) goto LA7; LOC9 = (NI)0; LOC9 = sonslen_297351_850551059((*t0).kindU.S6.sons->data[i_549434_839829468]); strings0 += (NI)(LOC9 - ((NI) 1)); } LA7: ; res_549552_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_549483_839829468; NI HEX3Atmp_549559_839829468; NI LOC16; NI res_549562_839829468; i_549483_839829468 = (NI)0; HEX3Atmp_549559_839829468 = (NI)0; LOC16 = (NI)0; LOC16 = sonslen_297351_850551059(t0); HEX3Atmp_549559_839829468 = (NI)(LOC16 - ((NI) 1)); res_549562_839829468 = ((NI) 1); { while (1) { if (!(res_549562_839829468 <= HEX3Atmp_549559_839829468)) goto LA18; i_549483_839829468 = res_549562_839829468; (*p0).labels += ((NI) 1); { Ropeobj180006* LOC23; Ropeobj180006* LOC24; if (!((*(*t0).kindU.S6.sons->data[i_549483_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_549483_839829468], a0, LOC24, branches0->data, branches0->Sup.len); } goto LA19; LA21: ; { } LA19: ; res_549562_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_549517_839829468; NI HEX3Atmp_549567_839829468; NI res_549570_839829468; j_549517_839829468 = (NI)0; HEX3Atmp_549567_839829468 = (NI)0; HEX3Atmp_549567_839829468 = (branches0 ? (branches0->Sup.len-1) : -1); res_549570_839829468 = ((NI) 0); { while (1) { if (!(res_549570_839829468 <= HEX3Atmp_549567_839829468)) goto LA29; j_549517_839829468 = res_549570_839829468; { TY534811 LOC34; if (!!((branches0->data[j_549517_839829468] == NIM_NIL))) goto LA32; memset((void*)LOC34, 0, sizeof(LOC34)); LOC34[0] = intliteral_541270_839829468(((NI64) (j_549517_839829468))); LOC34[1] = branches0->data[j_549517_839829468]; linef_534700_839829468(p0, ((Tcprocsection531011) 2), ((NimStringDesc*) &T839829468_597), LOC34, 2); } LA32: ; res_549570_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_549575_839829468)(Tnode294802* b0) { NIM_BOOL result0; { result0 = (NIM_BOOL)0; { NI i_549590_839829468; NI HEX3Atmp_549608_839829468; NI LOC2; NI res_549611_839829468; i_549590_839829468 = (NI)0; HEX3Atmp_549608_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = sonslen_297351_850551059(b0); HEX3Atmp_549608_839829468 = (NI)(LOC2 - ((NI) 2)); res_549611_839829468 = ((NI) 0); { while (1) { if (!(res_549611_839829468 <= HEX3Atmp_549608_839829468)) goto LA4; i_549590_839829468 = res_549611_839829468; { NIM_BOOL LOC7; LOC7 = (NIM_BOOL)0; LOC7 = ((*(*b0).kindU.S6.sons->data[i_549590_839829468]).kind == ((Tnodekind294020) 44)); if (!(LOC7)) goto LA8; LOC7 = (IL64(256) < (NI64)((*(*(*b0).kindU.S6.sons->data[i_549590_839829468]).kindU.S6.sons->data[((NI) 1)]).kindU.S1.intval - (*(*(*b0).kindU.S6.sons->data[i_549590_839829468]).kindU.S6.sons->data[((NI) 0)]).kindU.S1.intval)); LA8: ; if (!LOC7) goto LA9; result0 = NIM_TRUE; goto BeforeRet; } LA9: ; res_549611_839829468 += ((NI) 1); } LA4: ; } } }BeforeRet: ; return result0; } N_NIMCALL(NI, ifswitchsplitpoint_549615_839829468)(Tcproc531021* p0, Tnode294802* n0) { NI result0; result0 = (NI)0; { NI i_549630_839829468; NI HEX3Atmp_549654_839829468; NI LOC2; NI res_549657_839829468; i_549630_839829468 = (NI)0; HEX3Atmp_549654_839829468 = (NI)0; LOC2 = (NI)0; LOC2 = len_295081_850551059(n0); HEX3Atmp_549654_839829468 = (NI)(LOC2 - ((NI) 1)); res_549657_839829468 = ((NI) 1); { while (1) { Tnode294802* branch0; Tnode294802* stmtblock0; if (!(res_549657_839829468 <= HEX3Atmp_549654_839829468)) goto LA4; i_549630_839829468 = res_549657_839829468; branch0 = HEX5BHEX5D_295238_850551059(n0, i_549630_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_549630_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_549575_839829468(branch0); LA16: ; if (!LOC15) goto LA17; result0 = i_549630_839829468; } LA17: ; } goto LA5; LA11: ; LA5: ; res_549657_839829468 += ((NI) 1); } LA4: ; } } return result0; } N_NIMCALL(void, genordinalcase_549724_839829468)(Tcproc531021* p0, Tnode294802* n0, Tloc294816* d0) { NI splitpoint0; Tloc294816 a0; Ropeobj180006* lend0; splitpoint0 = ifswitchsplitpoint_549615_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_549757_839829468; NI HEX3Atmp_549816_839829468; NI HEX3Atmp_549817_839829468; NI LOC13; NI res_549820_839829468; i_549757_839829468 = (NI)0; HEX3Atmp_549816_839829468 = (NI)0; HEX3Atmp_549817_839829468 = (NI)0; HEX3Atmp_549816_839829468 = (NI)(splitpoint0 + ((NI) 1)); LOC13 = (NI)0; LOC13 = len_295081_850551059(n0); HEX3Atmp_549817_839829468 = (LOC13 - 1); res_549820_839829468 = HEX3Atmp_549816_839829468; { while (1) { Tnode294802* branch0; Tnode294802* LOC28; TY535289 LOC29; if (!(res_549820_839829468 <= HEX3Atmp_549817_839829468)) goto LA15; i_549757_839829468 = res_549820_839829468; { NIM_BOOL LOC18; LOC18 = (NIM_BOOL)0; LOC18 = ((*d0).k == ((Tlockind294808) 1)); if (!(LOC18)) goto LA19; LOC18 = isemptytype_299440_850551059((*n0).typ); LA19: ; if (!LOC18) goto LA20; (*d0).k = ((Tlockind294808) 0); } LA20: ; branch0 = HEX5BHEX5D_295238_850551059(n0, i_549757_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_549820_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_549826_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_299440_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_549416_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_549724_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_537671_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_549865_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_299440_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_535596_839829468((*p0).module); { Tsym294834* LOC10; Ropeobj180006* LOC13; LOC10 = (Tsym294834*)0; LOC10 = getcompilerproc_340746_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_299440_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_549978_839829468; NI HEX3Atmp_550101_839829468; NI res_550104_839829468; j_549978_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_549978_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_549978_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_299440_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_535596_839829468((*p0).module); { Tsym294834* LOC11; Ropeobj180006* LOC14; LOC11 = (Tsym294834*)0; LOC11 = getcompilerproc_340746_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_299440_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_194260_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_299440_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_558537_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 58): case ((Tnodekind294020) 59): case ((Tnodekind294020) 60): { genconv_558632_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_558590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_563)); } break; case ((Tnodekind294020) 69): { genrangechck_558590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_564)); } break; case ((Tnodekind294020) 70): { genrangechck_558590_839829468(p0, n0, d0, ((NimStringDesc*) &T839829468_565)); } break; case ((Tnodekind294020) 71): { convstrtocstr_558642_839829468(p0, n0, d0); } break; case ((Tnodekind294020) 72): { convcstrtostr_558654_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_547984_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_549826_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_549865_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_299279_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_337227_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_537671_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_537671_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_565204_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_565204_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_565152_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_565174_839829468; NI res_565200_839829468; i_565174_839829468 = (Tcfilesection531005)0; res_565200_839829468 = ((NI) 1); { while (1) { Ropeobj180006* LOC7; Ropeobj180006* LOC8; if (!(res_565200_839829468 <= ((NI) 10))) goto LA6; i_565174_839829468 = ((Tcfilesection531005) (res_565200_839829468)); LOC7 = (Ropeobj180006*)0; LOC7 = gensectionstart_532015_2760143328(i_565174_839829468); add_180482_2381377266(&result0, LOC7); add_180482_2381377266(&result0, (*m0).s[(i_565174_839829468)- 0]); LOC8 = (Ropeobj180006*)0; LOC8 = gensectionend_532050_2760143328(i_565174_839829468); add_180482_2381377266(&result0, LOC8); res_565200_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_565152_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_535596_839829468(m0)); asgnRefNoCycle((void**) (&(*m0).nimtypesname), gettempname_535596_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) { }
main.c
void foo(int N, int *restrict A); void baz(int M, int *restrict T, int N, int *restrict A) { #pragma omp parallel default(shared) { #pragma omp for for (int I = 0; I < N; ++I) { for (int J = 0; J < M; ++J) A[I] = A[I] + T[J]; } } } void bar(int M, int *restrict T, int N, int *restrict A) { baz(M, T, N, A); #pragma spf region { if (N > 0 && A[0] < 0) foo(N, A); } } void foo(int N, int *A) { int TSize = 4; int T[4]; for (int I = 0; I < TSize; ++I) T[I] = I; bar(TSize, T, N, A); }
cudanetworkexecutor.h
#pragma once #include "networkexecutor.h" #include "cudanetworkbatch.h" namespace NEAT { //--- //--- CLASS CudaNetworkExecutor //--- template<typename Evaluator> class CudaNetworkExecutor : public NetworkExecutor<Evaluator> { std::vector<class CudaNetworkBatch<Evaluator> *> batches; public: CudaNetworkExecutor() { int ndevices; xcuda( cudaGetDeviceCount(&ndevices) ); errif(ndevices == 0, "No Cuda devices found!"); batches.resize(ndevices); for(int i = 0; i < ndevices; i++) { batches[i] = new CudaNetworkBatch<Evaluator>(i); } } virtual ~CudaNetworkExecutor() { for(size_t i = 0; i < batches.size(); i++) { delete batches[i]; } } virtual void configure(const typename Evaluator::Config *config, size_t len) { for(size_t i = 0; i < batches.size(); i++) { batches[i]->configure(config, len); } } virtual void execute(class Network **nets_, OrganismEvaluation *results, size_t nnets) { CudaNetwork **nets = (CudaNetwork **)nets_; size_t nbatches = batches.size(); uint batch_size = nnets / nbatches; #pragma omp parallel for for(size_t ibatch = 0; ibatch < nbatches; ibatch++) { size_t inet = ibatch * batch_size; size_t n = batch_size; if(ibatch == nbatches - 1) n += nnets % batch_size; batches[ibatch]->activate(nets + inet, results + inet, n, NACTIVATES_PER_INPUT); } } }; template<typename Evaluator> inline NetworkExecutor<Evaluator> *NetworkExecutor<Evaluator>::create() { return new CudaNetworkExecutor<Evaluator>(); } } // namespace NEAT
hmacMD5_fmt_plug.c
/* * This software is Copyright (c) 2010 bartavelle, <bartavelle at bandecon.com> * and (c) magnum 2011-2015, * 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_hmacMD5; #elif FMT_REGISTERS_H john_register_one(&fmt_hmacMD5); #else #include <string.h> #include "arch.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 // tuned for i7 using SSE2 and w/o HT #endif #endif #include "misc.h" #include "common.h" #include "formats.h" #include "md5.h" #include "aligned.h" #include "johnswap.h" #include "simd-intrinsics.h" #include "base64_convert.h" #include "memdbg.h" #define FORMAT_LABEL "HMAC-MD5" #define FORMAT_NAME "" #ifdef SIMD_COEF_32 #define MD5_N (SIMD_PARA_MD5 * SIMD_COEF_32) #endif #define ALGORITHM_NAME "password is key, MD5 " MD5_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define PAD_SIZE 64 #define PAD_SIZE_W (PAD_SIZE/4) #define BINARY_SIZE 16 #define BINARY_ALIGN sizeof(uint32_t) #ifdef SIMD_COEF_32 #define SALT_LIMBS 3 /* 3 limbs, 183 bytes */ #define SALT_LENGTH (SALT_LIMBS * PAD_SIZE - 9) #define SALT_ALIGN MEM_ALIGN_SIMD #else #define SALT_LENGTH 1023 #define SALT_ALIGN 1 #endif #define CIPHERTEXT_LENGTH (2 * SALT_LENGTH + 2 * BINARY_SIZE) #define HEXCHARS "0123456789abcdef" #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT MD5_N #define MAX_KEYS_PER_CRYPT MD5_N #if ARCH_LITTLE_ENDIAN==1 #define GETPOS(i, index) ((index & (SIMD_COEF_32 - 1)) * 4 + ((i&63) & (0xffffffff - 3)) * SIMD_COEF_32 + ((i&63) & 3) + (unsigned int)index/SIMD_COEF_32 * PAD_SIZE * SIMD_COEF_32) #else #define GETPOS(i, index) ((index & (SIMD_COEF_32 - 1)) * 4 + ((i&63) & (0xffffffff - 3)) * SIMD_COEF_32 + (3-((i&63)&3)) + (unsigned int)index/SIMD_COEF_32 * PAD_SIZE * SIMD_COEF_32) #endif #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { {"what do ya want for nothing?#750c783e6ab0b503eaa86e310a5db738", "Jefe"}, {"YT1m11GDMm3oze0EdqO3FZmATSrxhquB#6c97850b296b34719b7cea5c0c751e22", ""}, {"2shXeqDlLdZ2pSMc0CBHfTyA5a9TKuSW#dfeb02c6f8a9ce89b554be60db3a2333", "magnum"}, {"#74e6f7298a9c2d168935f58c001bad88", ""}, {"The quick brown fox jumps over the lazy dog#80070713463e7749b90c2dc24911e275", "key"}, {"Beppe Grillo#F8457C3046C587BBCBD6D7036BA42C81", "Io credo nella reincarnazione e sono di Genova; per cui ho fatto testamento e mi sono lasciato tutto a me."}, {"$cram_md5$PG5vLXJlcGx5QGhhc2hjYXQubmV0Pg==$dXNlciA0NGVhZmQyMmZlNzY2NzBmNmIyODc5MDgxYTdmNWY3MQ==", "hashcat"}, {"MEaEObR2JNXgchVn93GLLH1Ud4qTzuC0#9a80bea0acd72231ea043210a173ec7f", "123"}, {"d2BbCbiSXTlglEstbFFlrRgPhR1KUa2s#7a553738bc4997e656329c1b1ef99e4f", "123456789"}, {"dBTmX1AdmnWyVkMKp7BEt4O3eBktdN2S#f6af0afd4f397504c3bfa3836bc04a0f", "passWOrd"}, {"0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789#050a9dee01b2302914b2a78346721d9b", "magnum"}, {"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123#e4d0097fdc52f6fc50545d832784232d", "MaxLenSaltUsed"}, {NULL} }; #ifdef SIMD_COEF_32 static unsigned char *crypt_key; static unsigned char *ipad, *prep_ipad; static unsigned char *opad, *prep_opad; typedef struct cur_salt_t { unsigned char salt[SALT_LIMBS][PAD_SIZE * MAX_KEYS_PER_CRYPT]; int salt_len; } cur_salt_t; static cur_salt_t *cur_salt; static int bufsize; #define SALT_SIZE sizeof(cur_salt_t) #else static uint32_t (*crypt_key)[BINARY_SIZE / sizeof(uint32_t)]; static unsigned char (*ipad)[PAD_SIZE]; static unsigned char (*opad)[PAD_SIZE]; static unsigned char cur_salt[SALT_LENGTH+1]; static MD5_CTX *ipad_ctx; static MD5_CTX *opad_ctx; #define SALT_SIZE sizeof(cur_salt) #endif static char (*saved_plain)[PLAINTEXT_LENGTH + 1]; static int new_keys; #ifdef SIMD_COEF_32 static void clear_keys(void) { memset(ipad, 0x36, bufsize); memset(opad, 0x5C, bufsize); } #endif static void init(struct fmt_main *self) { #ifdef SIMD_COEF_32 unsigned int i; #endif #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 #ifdef SIMD_COEF_32 bufsize = sizeof(*opad) * self->params.max_keys_per_crypt * PAD_SIZE; crypt_key = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); ipad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); opad = mem_calloc_align(1, bufsize, MEM_ALIGN_SIMD); prep_ipad = mem_calloc_align(self->params.max_keys_per_crypt, BINARY_SIZE, MEM_ALIGN_SIMD); prep_opad = mem_calloc_align(self->params.max_keys_per_crypt, BINARY_SIZE, MEM_ALIGN_SIMD); for (i = 0; i < self->params.max_keys_per_crypt; ++i) { crypt_key[GETPOS(BINARY_SIZE, i)] = 0x80; ((unsigned int*)crypt_key)[14 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + (i/SIMD_COEF_32) * PAD_SIZE_W * SIMD_COEF_32] = (BINARY_SIZE + PAD_SIZE) << 3; } clear_keys(); #else crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); ipad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*ipad)); opad = mem_calloc(self->params.max_keys_per_crypt, sizeof(*opad)); ipad_ctx = mem_calloc(self->params.max_keys_per_crypt, sizeof(*ipad_ctx)); opad_ctx = mem_calloc(self->params.max_keys_per_crypt, sizeof(*opad_ctx)); #endif saved_plain = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_plain)); } static void done(void) { MEM_FREE(saved_plain); #ifdef SIMD_COEF_32 MEM_FREE(prep_opad); MEM_FREE(prep_ipad); #else MEM_FREE(opad_ctx); MEM_FREE(ipad_ctx); #endif MEM_FREE(opad); MEM_FREE(ipad); MEM_FREE(crypt_key); } /* Convert from Base64 format with tag to our legacy format */ static char *prepare(char *split_fields[10], struct fmt_main *self) { char *p = split_fields[1]; if (!strncmp(p, "$cram_md5$", 10)) { static char out[256]; int len, len2; char *d, *o = out; p += 10; memset(out, 0, sizeof(out)); if (!(d = strchr(p, '$'))) return split_fields[1]; len = base64_convert(p, e_b64_mime, (int)(d - p - 1), o, e_b64_raw, sizeof(out), flg_Base64_MIME_TRAIL_EQ, 0); if (len > sizeof(out)-2) return split_fields[1]; o += len; *o++ = '#'; d++; len2 = base64_convert(d, e_b64_mime, strlen(d), o, e_b64_raw, sizeof(out) - len - 2, flg_Base64_MIME_TRAIL_EQ, 0); if (len2 > sizeof(out) - len - 3) return split_fields[1]; len = len2; if (!(p = strchr(o, ' '))) return split_fields[1]; p++; if (p-o >= len) return split_fields[1]; memmove(o, p, len - (p - o) + 1); if (strlen(o) == BINARY_SIZE * 2) return out; } return p; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[CIPHERTEXT_LENGTH + 1]; if (strstr(ciphertext, "$SOURCE_HASH$")) return ciphertext; strnzcpy(out, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(strrchr(out, '#')); return out; } static int valid(char *ciphertext, struct fmt_main *self) { int pos, i; char *p; if (!strncmp(ciphertext, "$cram_md5$", 10)) { char *f[10]; f[1] = ciphertext; ciphertext = prepare(f, self); } p = strrchr(ciphertext, '#'); // allow # in salt if (!p || p > &ciphertext[strlen(ciphertext) - 1]) return 0; i = (int)(p - ciphertext); if (i > SALT_LENGTH) return 0; pos = i + 1; if (strlen(ciphertext+pos) != BINARY_SIZE * 2) return 0; for (i = pos; i < BINARY_SIZE*2+pos; i++) { if (!((('0' <= ciphertext[i])&&(ciphertext[i] <= '9')) || (('a' <= ciphertext[i])&&(ciphertext[i] <= 'f')) || (('A' <= ciphertext[i])&&(ciphertext[i] <= 'F')))) return 0; } return 1; } static void set_salt(void *salt) { #ifdef SIMD_COEF_32 cur_salt = salt; #else strcpy((char*)cur_salt, (char*)salt); #endif } static void set_key(char *key, int index) { int len; #ifdef SIMD_COEF_32 #if ARCH_LITTLE_ENDIAN==1 uint32_t *ipadp = (uint32_t*)&ipad[GETPOS(0, index)]; uint32_t *opadp = (uint32_t*)&opad[GETPOS(0, index)]; #else uint32_t *ipadp = (uint32_t*)&ipad[GETPOS(3, index)]; uint32_t *opadp = (uint32_t*)&opad[GETPOS(3, index)]; #endif const uint32_t *keyp = (uint32_t*)key; unsigned int temp; len = strlen(key); memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; if (len > PAD_SIZE) { unsigned char k0[BINARY_SIZE]; MD5_CTX ctx; int i; MD5_Init(&ctx); MD5_Update(&ctx, key, len); MD5_Final(k0, &ctx); keyp = (unsigned int*)k0; for (i = 0; i < BINARY_SIZE / 4; i++, ipadp += SIMD_COEF_32, opadp += SIMD_COEF_32) { #if ARCH_LITTLE_ENDIAN==1 temp = *keyp++; #else temp = JOHNSWAP(*keyp++); #endif *ipadp ^= temp; *opadp ^= temp; } } else { #if ARCH_LITTLE_ENDIAN==1 while((unsigned char)(temp = *keyp++)) { if (!(temp & 0xff00) || !(temp & 0xff0000)) { *ipadp ^= (unsigned short)temp; *opadp ^= (unsigned short)temp; break; } *ipadp ^= temp; *opadp ^= temp; if (!(temp & 0xff000000)) break; ipadp += SIMD_COEF_32; opadp += SIMD_COEF_32; } #else while((temp = *keyp++) & 0xff000000) { if (!(temp & 0xff0000) || !(temp & 0xff00)) { *ipadp ^= (unsigned short)JOHNSWAP(temp); *opadp ^= (unsigned short)JOHNSWAP(temp); break; } *ipadp ^= JOHNSWAP(temp); *opadp ^= JOHNSWAP(temp); if (!(temp & 0xff)) break; ipadp += SIMD_COEF_32; opadp += SIMD_COEF_32; } #endif } #else int i; len = strlen(key); memcpy(saved_plain[index], key, len); saved_plain[index][len] = 0; memset(ipad[index], 0x36, PAD_SIZE); memset(opad[index], 0x5C, PAD_SIZE); if (len > PAD_SIZE) { MD5_CTX ctx; unsigned char k0[BINARY_SIZE]; MD5_Init(&ctx); MD5_Update(&ctx, key, len); MD5_Final(k0, &ctx); len = BINARY_SIZE; for (i = 0; i < len; i++) { ipad[index][i] ^= k0[i]; opad[index][i] ^= k0[i]; } } else for (i = 0; i < len; i++) { ipad[index][i] ^= key[i]; opad[index][i] ^= key[i]; } #endif new_keys = 1; } static char *get_key(int index) { return saved_plain[index]; } static int cmp_all(void *binary, int count) { #ifdef SIMD_COEF_32 unsigned int x, y = 0; for (; y < (unsigned int)(count + SIMD_COEF_32 - 1) / SIMD_COEF_32; y++) for (x = 0; x < SIMD_COEF_32; x++) { // NOTE crypt_key is in input format (PAD_SIZE * SIMD_COEF_32) if (((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[x + y * SIMD_COEF_32 * PAD_SIZE_W]) return 1; } return 0; #else int index = 0; #if defined(_OPENMP) || (MAX_KEYS_PER_CRYPT > 1) for (index = 0; index < count; index++) #endif if (((uint32_t*)binary)[0] == crypt_key[index][0]) return 1; return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 int i; for (i = 0; i < (BINARY_SIZE/4); i++) // NOTE crypt_key is in input format (PAD_SIZE * SIMD_COEF_32) if (((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[i * SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32 * PAD_SIZE_W * SIMD_COEF_32]) return 0; return 1; #else return !memcmp(binary, crypt_key[index], BINARY_SIZE); #endif } static int cmp_exact(char *source, int index) { return (1); } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #if _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_32 int i; if (new_keys) { SIMDmd5body(&ipad[index * PAD_SIZE], (unsigned int*)&prep_ipad[index * BINARY_SIZE], NULL, SSEi_MIXED_IN); SIMDmd5body(&opad[index * PAD_SIZE], (unsigned int*)&prep_opad[index * BINARY_SIZE], NULL, SSEi_MIXED_IN); } SIMDmd5body(cur_salt->salt[0], (unsigned int*)&crypt_key[index * PAD_SIZE], (unsigned int*)&prep_ipad[index * BINARY_SIZE], SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT); for (i = 1; i <= (cur_salt->salt_len + 8) / PAD_SIZE; i++) { SIMDmd5body(cur_salt->salt[i], (unsigned int*)&crypt_key[index * PAD_SIZE], (unsigned int*)&crypt_key[index * PAD_SIZE], SSEi_MIXED_IN|SSEi_RELOAD_INP_FMT|SSEi_OUTPUT_AS_INP_FMT); } SIMDmd5body(&crypt_key[index * PAD_SIZE], (unsigned int*)&crypt_key[index * PAD_SIZE], (unsigned int*)&prep_opad[index * BINARY_SIZE], SSEi_MIXED_IN|SSEi_RELOAD|SSEi_OUTPUT_AS_INP_FMT); #else MD5_CTX ctx; if (new_keys) { MD5_Init(&ipad_ctx[index]); MD5_Update(&ipad_ctx[index], ipad[index], PAD_SIZE); MD5_Init(&opad_ctx[index]); MD5_Update(&opad_ctx[index], opad[index], PAD_SIZE); } memcpy(&ctx, &ipad_ctx[index], sizeof(ctx)); MD5_Update(&ctx, cur_salt, strlen((char*)cur_salt)); MD5_Final((unsigned char*) crypt_key[index], &ctx); memcpy(&ctx, &opad_ctx[index], sizeof(ctx)); MD5_Update(&ctx, crypt_key[index], BINARY_SIZE); MD5_Final((unsigned char*) crypt_key[index], &ctx); #endif } new_keys = 0; return count; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; uint32_t dummy; } buf; unsigned char *out = buf.c; char *p; int i; // allow # in salt p = strrchr(ciphertext, '#') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #if !ARCH_LITTLE_ENDIAN alter_endianity(out, BINARY_SIZE); #endif return (void*)out; } static void *get_salt(char *ciphertext) { static unsigned char salt[SALT_LENGTH+1]; int len; #ifdef SIMD_COEF_32 unsigned int i = 0; static JTR_ALIGN(MEM_ALIGN_SIMD) cur_salt_t cur_salt; int salt_len = 0; #endif // allow # in salt len = strrchr(ciphertext, '#') - ciphertext; memset(salt, 0, sizeof(salt)); memcpy(salt, ciphertext, len); #ifdef SIMD_COEF_32 memset(&cur_salt, 0, sizeof(cur_salt)); while(((unsigned char*)salt)[salt_len]) { for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) cur_salt.salt[salt_len / PAD_SIZE][GETPOS(salt_len, i)] = ((unsigned char*)salt)[salt_len]; ++salt_len; } cur_salt.salt_len = salt_len; for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { cur_salt.salt[salt_len / PAD_SIZE][GETPOS(salt_len, i)] = 0x80; ((unsigned int*)cur_salt.salt[(salt_len + 8) / PAD_SIZE])[14 * SIMD_COEF_32 + (i&(SIMD_COEF_32-1)) + i/SIMD_COEF_32 * PAD_SIZE_W * SIMD_COEF_32] = (salt_len + PAD_SIZE) << 3; } return &cur_salt; #else return salt; #endif } struct fmt_main fmt_hmacMD5 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE | FMT_HUGE_INPUT, { NULL }, { NULL }, tests }, { init, done, fmt_default_reset, prepare, valid, split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, set_key, get_key, #ifdef SIMD_COEF_32 clear_keys, #else fmt_default_clear_keys, #endif crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
declare-variant-14.c
/* { dg-do compile { target vect_simd_clones } } */ /* { dg-additional-options "-fdump-tree-gimple -fdump-tree-optimized" } */ /* { dg-additional-options "-mno-sse3" { target { i?86-*-* x86_64-*-* } } } */ int f01 (int); int f02 (int); int f03 (int); #pragma omp declare variant (f01) match (device={isa("avx512f")}) /* 4 or 8 */ #pragma omp declare variant (f02) match (implementation={vendor(score(3):gnu)},device={kind(cpu)}) /* (1 or 2) + 3 */ #pragma omp declare variant (f03) match (implementation={vendor(score(5):gnu)},device={kind(host)}) /* (1 or 2) + 5 */ int f04 (int); #pragma omp declare simd int test1 (int x) { /* At gimplification time, we can't decide yet which function to call. */ /* { dg-final { scan-tree-dump-times "f04 \\\(x" 2 "gimple" } } */ /* After simd clones are created, the original non-clone test1 shall call f03 (score 6), the sse2/avx/avx2 clones too, but avx512f clones shall call f01 with score 8. */ /* { dg-final { scan-tree-dump-not "f04 \\\(x" "optimized" } } */ /* { dg-final { scan-tree-dump-times "f03 \\\(x" 14 "optimized" } } */ /* { dg-final { scan-tree-dump-times "f01 \\\(x" 4 "optimized" } } */ int a = f04 (x); int b = f04 (x); return a + b; }
wpapsk.h
/* * This software is Copyright (c) 2012 Lukas Odzioba <lukas dot odzioba at gmail dot com> * and Copyright (c) 2012-2014 magnum * 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. * * hccap format was introduced by oclHashcat-plus, and it is described here: http://hashcat.net/wiki/hccap * Code is based on Aircrack-ng source */ #ifndef _WPAPSK_H #define _WPAPSK_H #include "arch.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "stdint.h" #include <assert.h> #include <openssl/hmac.h> #define HCCAP_SIZE sizeof(hccap_t) #define BINARY_SIZE sizeof(mic_t) #define BINARY_ALIGN 4 #define PLAINTEXT_LENGTH 63 /* We can do 64 but spec. says 63 */ #define SALT_SIZE (sizeof(hccap_t) - sizeof(mic_t)) #define SALT_ALIGN MEM_ALIGN_NONE #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define FORMAT_TAG "$WPAPSK$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) /** if you want to change hccap_t structure is also defined in hccap2john.c **/ typedef struct { char essid[36]; unsigned char mac1[6]; unsigned char mac2[6]; unsigned char nonce1[32]; unsigned char nonce2[32]; unsigned char eapol[256]; int eapol_size; int keyver; unsigned char keymic[16]; } hccap_t; typedef struct { unsigned char keymic[16]; } mic_t; typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH + 1]; } wpapsk_password; typedef struct { uint32_t v[8]; } wpapsk_hash; typedef struct { uint32_t length; #ifdef JOHN_OCL_WPAPSK uint8_t eapol[256 + 64]; uint32_t eapol_size; // blocks uint8_t data[64 + 12]; #endif uint8_t salt[36]; // essid } wpapsk_salt; #ifndef _WPAPSK_CUDA_KERNEL static struct fmt_tests tests[] = { /* WPA2 testcase from http://wiki.wireshark.org/SampleCaptures */ {"$WPAPSK$Coherer#..l/Uf7J..qHUXMunTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosMyXdNxfBZUAYmgKqeb6GBPxLiIZr56NtWTGR/Cp5ldAk61.5I0.Ec.2...........nTE3nfbMWSwxv27Ua0XutIOrfRSuv9gOCIugIVGlosM.................................................................3X.I.E..1uk0.E..1uk2.E..1uk0....................................................................................................................................................................................../t.....U...8FWdk8OpPckhewBwt4MXYI", "Induction"}, {"$WPAPSK$Harkonen#./FgTY0../B4zX6AKFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL.WK3GkF2rXfkPFGGi38MHkHDMbH.sm49Vc3pO4HPSUJE21.5I0.Ec.2........../KFO9kuLT4BQSyqEXwo.6XOiS4u8vlMNNs5grN91SVL..................................................................3X.I.E..1uk2.E..1uk2.E..1uk0.E..................................................................................................................................................................................../t.....U...BIpIs8sePU4r8yNnOxKHfM", "12345678"}, /* WPA, from aircrack-ng tests */ {"$WPAPSK$test#..qHuv0A..ZPYJBRzZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsRIfQN2Zar6EXp2BYcRuSkWEJIWjEJJvb4DWZCspbZ51.21.3zy.EY.6........../zZwAKpEXUJwpza/b69itFaq4.OWoGHfonpc13zCAUsQ..................................................................BoK.31m.E2..31m.U2..31m.U2..31m.U................................................................................................................................................................................/X.....E...AkkDQmDg9837LBHG.dGlKA", "biscotte"}, /* Maximum length, 63 characters */ {"$WPAPSK$Greased Lighting#kA5.CDNB.07cofsOMXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGqgvfcXnuF1f7L5fgn4fQMLmDrKjdBNjb6LClRmfLiTYk21.5I0.Ec............7MXEEUwFTkO/RX2sQUaW9eteI8ynpFMwRgFZC6kk7bGo.................................................................3X.I.E..1uk2.E..1uk2.E..1uk00...................................................................................................................................................................................../t.....U...D06LUdWVfGPaP1Oa3AV9Hg", "W*A5z&1?op2_L&Hla-OA$#5i_Lu@F+6d?je?u5!6+6766eluu7-l+jOEkIwLe90"}, {NULL} }; #endif /** Below are common variables used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/ static hccap_t hccap; ///structure with hccap data static wpapsk_salt currentsalt; ///structure for essid static mic_t *mic; ///table for MIC keys #ifndef JOHN_OCL_WPAPSK static wpapsk_password *inbuffer; ///table for candidate passwords static wpapsk_hash *outbuffer; ///table for PMK calculated by GPU #endif static int new_keys = 1; static char last_ssid[sizeof(hccap.essid)]; /** Below are common functions used by wpapsk_fmt.c cuda_wpapsk_fmt.c and opencl_wpapsk_fmt.c **/ static hccap_t *decode_hccap(char *ciphertext) { static hccap_t hccap; char *essid = ciphertext + FORMAT_TAG_LEN; char *hash = strrchr(ciphertext, '#'); char *d = hccap.essid; char *cap = hash + 1; unsigned char tbuf[sizeof(hccap_t)]; unsigned char *dst = tbuf; int i; memset(&hccap, 0, sizeof(hccap)); if (hash == NULL) return &hccap; while (essid != hash) { ///copy essid to hccap *d++ = *essid++; } *d = '\0'; assert(*essid == '#'); for (i = 0; i < 118; i++) { dst[0] = (atoi64[ARCH_INDEX(cap[0])] << 2) | (atoi64[ARCH_INDEX(cap[1])] >> 4); dst[1] = (atoi64[ARCH_INDEX(cap[1])] << 4) | (atoi64[ARCH_INDEX(cap[2])] >> 2); dst[2] = (atoi64[ARCH_INDEX(cap[2])] << 6) | (atoi64[ARCH_INDEX(cap[3])]); dst += 3; cap += 4; } dst[0] = (atoi64[ARCH_INDEX(cap[0])] << 2) | (atoi64[ARCH_INDEX(cap[1])] >> 4); dst[1] = (atoi64[ARCH_INDEX(cap[1])] << 4) | (atoi64[ARCH_INDEX(cap[2])] >> 2); /* This emits warnings on some compilers */ //memcpy(&hccap.mac1,tbuf,sizeof(hccap_t)-36); memcpy(((char*)&hccap) + 36, tbuf, sizeof(hccap_t) - 36); #if !ARCH_LITTLE_ENDIAN hccap.eapol_size = JOHNSWAP(hccap.eapol_size); hccap.keyver = JOHNSWAP(hccap.keyver); #endif return &hccap; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD_32 dummy; } binary; hccap_t *hccap = decode_hccap(ciphertext); memcpy(binary.c, hccap->keymic, BINARY_SIZE); return binary.c; } static void *get_salt(char *ciphertext) { static hccap_t s; memcpy(&s, decode_hccap(ciphertext), SALT_SIZE); return &s; } static int valid(char *ciphertext, struct fmt_main *self) { char *hash; int hashlength = 0; hccap_t *hccap; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN) != 0) return 0; hash = strrchr(ciphertext, '#'); if (hash == NULL || hash - (ciphertext + FORMAT_TAG_LEN) > 32) return 0; hash++; while (hash < ciphertext + strlen(ciphertext)) { if (atoi64[ARCH_INDEX(*hash++)] == 0x7f) return 0; hashlength++; } if (hashlength != 475) return 0; hccap = decode_hccap(ciphertext); if (strlen(hccap->essid) > 32) /* real life limit */ return 0; if(hccap->eapol_size > 256) return 0; if(hccap->eapol_size < 0) return 0; return 1; } #ifndef JOHN_OCL_WPAPSK static MAYBE_INLINE void prf_512(uint32_t * key, uint8_t * data, uint32_t * ret) { HMAC_CTX ctx; char *text = (char*)"Pairwise key expansion"; unsigned char buff[100]; memcpy(buff, text, 22); memcpy(buff + 23, data, 76); buff[22] = 0; buff[76 + 23] = 0; HMAC_Init(&ctx, key, 32, EVP_sha1()); HMAC_Update(&ctx, buff, 100); HMAC_Final(&ctx, (unsigned char *) ret, NULL); HMAC_CTX_cleanup(&ctx); } #endif static void insert_mac(uint8_t * data) { int k = memcmp(hccap.mac1, hccap.mac2, 6); if (k > 0) { memcpy(data, hccap.mac2, 6); memcpy(data + 6, hccap.mac1, 6); } else { memcpy(data, hccap.mac1, 6); memcpy(data + 6, hccap.mac2, 6); } } static void insert_nonce(uint8_t * data) { int k = memcmp(hccap.nonce1, hccap.nonce2, 32); if (k > 0) { memcpy(data, hccap.nonce2, 32); memcpy(data + 32, hccap.nonce1, 32); } else { memcpy(data, hccap.nonce1, 32); memcpy(data + 32, hccap.nonce2, 32); } } #ifdef WPAPSK_DEBUG static char *tomac(unsigned char *p) { static char buf[48]; sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", p[0], p[1], p[2], p[3], p[4], p[5]); return buf; } static char *hex(unsigned char *p, int len) { static char buf[1024]; char *op=buf; int i; if (len > 32) { do { for (i = 0; i < 32; ++i) { op += sprintf (op, "%02X", p[i]); if (i<31&&i%4==3) op += sprintf (op, " "); if (i==15) op += sprintf (op, ": "); } len -= 32; p += 32; op += sprintf (op, "\n "); } while (len > 32); } for (i = 0; i < len; ++i) { op += sprintf (op, "%02X", p[i]); if (i<31&&i%4==3) op += sprintf (op, " "); if (i==15) op += sprintf (op, ": "); } return buf; } static void Debug_hccap() { printf("essid: %s\n", hccap.essid); printf("mac1: %s\n", tomac(hccap.mac1)); printf("mac2: %s\n", tomac(hccap.mac2)); printf("nonce1: %s\n", hex(hccap.nonce1, 32)); printf("nonce2: %s\n", hex(hccap.nonce2, 32)); printf("eapol: %s\n", hex(hccap.eapol, 256)); printf("epol_sz: %d (0x%02X)\n", hccap.eapol_size, hccap.eapol_size); printf("keyver: %d\n", hccap.keyver); printf("keymic: %s\n", hex(hccap.keymic, 16)); } #endif static void set_salt(void *salt) { memcpy(&hccap, salt, SALT_SIZE); strncpy((char*)currentsalt.salt, hccap.essid, sizeof(currentsalt.salt)); currentsalt.length = strlen(hccap.essid); #ifdef JOHN_OCL_WPAPSK currentsalt.eapol_size = 1 + (hccap.eapol_size + 8) / 64; memcpy(currentsalt.eapol, hccap.eapol, hccap.eapol_size); memset(currentsalt.eapol + hccap.eapol_size, 0x80, 1); memset(currentsalt.eapol + hccap.eapol_size + 1, 0, 256 + 64 - hccap.eapol_size - 1); if (hccap.keyver != 1) alter_endianity(currentsalt.eapol, 256+56); ((unsigned int*)currentsalt.eapol)[16 * ((hccap.eapol_size + 8) / 64) + ((hccap.keyver == 1) ? 14 : 15)] = (64 + hccap.eapol_size) << 3; insert_mac(currentsalt.data); insert_nonce(currentsalt.data + 12); alter_endianity(currentsalt.data, 64 + 12); HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(wpapsk_salt), &currentsalt, 0, NULL, NULL), "Copy setting to gpu"); #endif //Debug_hccap(); } #ifndef JOHN_OCL_WPAPSK static void clear_keys(void) { new_keys = 1; } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static void wpapsk_postprocess(int keys) { int i; uint8_t data[64 + 12]; insert_mac(data); insert_nonce(data + 12); if (hccap.keyver == 1) { #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic) #endif for (i = 0; i < keys; i++) { uint32_t prf[20/4]; prf_512(outbuffer[i].v, data, prf); HMAC(EVP_md5(), prf, 16, hccap.eapol, hccap.eapol_size, mic[i].keymic, NULL); } } else { #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(keys, outbuffer, data, hccap, mic) #endif for (i = 0; i < keys; i++) { uint32_t prf[20/4]; unsigned char keymic[20]; prf_512(outbuffer[i].v, data, prf); HMAC(EVP_sha1(), prf, 16, hccap.eapol, hccap.eapol_size, keymic, NULL); memcpy(mic[i].keymic, keymic, 16); } } } #endif static int binary_hash_0(void *binary) { #ifdef WPAPSK_DEBUG puts("binary"); uint32_t i, *b = binary; for (i = 0; i < 4; i++) printf("%08x ", b[i]); puts(""); #endif return ((uint32_t *) binary)[0] & PH_MASK_0; } static int get_hash_0(int index) { #ifdef WPAPSK_DEBUG int i; puts("get_hash"); uint32_t *b = (uint32_t *)mic[index].keymic; for (i = 0; i < 4; i++) printf("%08x ", b[i]); puts(""); #endif uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_0; } static int get_hash_1(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_1; } static int get_hash_2(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_2; } static int get_hash_3(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_3; } static int get_hash_4(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_4; } static int get_hash_5(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_5; } static int get_hash_6(int index) { uint32_t *h = (uint32_t *) mic[index].keymic; return h[0] & PH_MASK_6; } static int cmp_all(void *binary, int count) { uint32_t i, b = ((uint32_t *) binary)[0]; for (i = 0; i < count; i++) { uint32_t *m = (uint32_t*) mic[i].keymic; if (b == m[0]) return 1; } return 0; } static int cmp_one(void *binary, int index) { uint8_t i; uint32_t *b = (uint32_t*) binary; uint32_t *m = (uint32_t*) mic[index].keymic; for (i = 0; i < BINARY_SIZE / 4; i++) if (b[i] != m[i]) return 0; return 1; } static int cmp_exact(char *source, int index) { return 1; } static int salt_compare(const void *x, const void *y) { int c = strncmp((const char*)x, (const char*)y, 36); if (c) return c; return memcmp((const char*)x, (const char*)y, SALT_SIZE); } #endif
magsac.h
#pragma once #include <limits> #include <chrono> #include <memory> #include "model.h" #include "model_score.h" #include "sampler.h" #include "uniform_sampler.h" #include <math.h> #include "gamma_values.cpp" #ifdef _WIN32 #include <ppl.h> #endif template <class DatumType, class ModelEstimator> class MAGSAC { public: enum Version { // The original version of MAGSAC. It works well, however, can be quite slow in many cases. MAGSAC_ORIGINAL, // The recently proposed MAGSAC++ algorithm which keeps the accuracy of the original MAGSAC but is often orders of magnitude faster. MAGSAC_PLUS_PLUS }; MAGSAC(const Version magsac_version_ = Version::MAGSAC_PLUS_PLUS) : time_limit(std::numeric_limits<double>::max()), // desired_fps(-1), iteration_limit(std::numeric_limits<size_t>::max()), maximum_threshold(10.0), apply_post_processing(true), mininum_iteration_number(50), partition_number(5), core_number(1), number_of_irwls_iters(1), interrupting_threshold(1.0), last_iteration_number(0), log_confidence(0), point_number(0), magsac_version(magsac_version_) { } ~MAGSAC() {} // A function to run MAGSAC. bool run( const cv::Mat &points_, // The input data points const double confidence_, // The required confidence in the results ModelEstimator& estimator_, // The model estimator gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, // The sampler used gcransac::Model &obtained_model_, // The estimated model parameters int &iteration_number_, // The number of iterations done ModelScore &model_score_); // The score of the estimated model // A function to set the maximum inlier-outlier threshold void setMaximumThreshold(const double maximum_threshold_) { maximum_threshold = maximum_threshold_; } // A function to set the inlier-outlier threshold used for speeding up the procedure // and for determining the required number of iterations. void setReferenceThreshold(const double threshold_) { interrupting_threshold = threshold_; } double getReferenceThreshold() { return interrupting_threshold; } // Setting the flag determining if post-processing is needed void applyPostProcessing(bool value_) { apply_post_processing = value_; } // A function to set the maximum number of iterations void setIterationLimit(size_t iteration_limit_) { iteration_limit = iteration_limit_; } // A function to set the minimum number of iterations void setMinimumIterationNumber(size_t mininum_iteration_number_) { mininum_iteration_number = mininum_iteration_number_; } // A function to set the number of cores used in the original MAGSAC algorithm. // In MAGSAC++, it is not used. Note that when multiple MAGSACs run in parallel, // it is beneficial to keep the core number one for each independent MAGSAC. // Otherwise, the threads will act weirdly. void setCoreNumber(size_t core_number_) { if (magsac_version == MAGSAC_PLUS_PLUS) fprintf(stderr, "Setting the core number for MAGSAC++ is deprecated."); core_number = core_number_; } // Setting the number of partitions used in the original MAGSAC algorithm // to speed up the procedure. In MAGSAC++, this parameter is not used. void setPartitionNumber(size_t partition_number_) { if (magsac_version == MAGSAC_PLUS_PLUS) fprintf(stderr, "Setting the partition number for MAGSAC++ is deprecated."); partition_number = partition_number_; } // A function to set a desired minimum frames-per-second (FPS) value. void setFPS(int fps_) { desired_fps = fps_; // The required FPS. // The time limit which the FPS implies time_limit = fps_ <= 0 ? std::numeric_limits<double>::max() : 1.0 / fps_; } // The post-processing algorithm applying sigma-consensus to the input model once. bool postProcessing( const cv::Mat &points, // All data points const gcransac::Model &so_far_the_best_model, // The input model to be improved gcransac::Model &output_model, // The improved model parameters ModelScore &output_score, // The score of the improved model const ModelEstimator &estimator); // The model estimator // The function determining the quality/score of a model using the original MAGSAC // criterion. Note that this function is significantly slower than the quality // function of MAGSAC++. void getModelQuality( const cv::Mat& points_, // All data points const gcransac::Model& model_, // The input model const ModelEstimator& estimator_, // The model estimator double& marginalized_iteration_number_, // The required number of iterations marginalized over the noise scale double& score_); // The score/quality of the model // The function determining the quality/score of a // model using the MAGSAC++ criterion. void getModelQualityPlusPlus( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &score_, // The score to be calculated const double &previous_best_score_); // The score of the previous so-far-the-best model // The function to extract inliers mask of a model // for a given threshold void getModelInliersMask( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, const double trehshold_, // Inlier/outlier threshold std::vector<bool> &inliers_mask_); size_t number_of_irwls_iters; protected: Version magsac_version; // The version of MAGSAC used size_t iteration_limit; // Maximum number of iterations allowed size_t mininum_iteration_number; // Minimum number of iteration before terminating double maximum_threshold; // The maximum sigma value size_t core_number; // Number of core used in sigma-consensus double time_limit; // A time limit after the algorithm is interrupted int desired_fps; // The desired FPS (TODO: not tested with MAGSAC) bool apply_post_processing; // Decides if the post-processing step should be applied int point_number; // The current point number int last_iteration_number; // The iteration number implied by the last run of sigma-consensus double log_confidence; // The logarithm of the required confidence size_t partition_number; // Number of partitions used to speed up sigma-consensus double interrupting_threshold; // A threshold to speed up MAGSAC by interrupting the sigma-consensus procedure whenever there is no chance of being better than the previous so-far-the-best model bool sigmaConsensus( const cv::Mat& points_, const gcransac::Model& model_, gcransac::Model& refined_model_, ModelScore& score_, const ModelEstimator& estimator_, const ModelScore& best_score_); bool sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model& model_, gcransac::Model& refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_); }; template <class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::run( const cv::Mat& points_, const double confidence_, ModelEstimator& estimator_, gcransac::sampler::Sampler<cv::Mat, size_t> &sampler_, gcransac::Model& obtained_model_, int& iteration_number_, ModelScore &model_score_) { // Initialize variables std::chrono::time_point<std::chrono::system_clock> start, end; // Variables for time measuring: start and end times std::chrono::duration<double> elapsed_seconds; // Variables for time measuring: elapsed time log_confidence = log(1.0 - confidence_); // The logarithm of 1 - confidence point_number = points_.rows; // Number of points const int sample_size = estimator_.sampleSize(); // The sample size required for the estimation size_t max_iteration = iteration_limit; // The maximum number of iterations initialized to the iteration limit int iteration = 0; // Current number of iterations gcransac::Model so_far_the_best_model; // Current best model ModelScore so_far_the_best_score; // The score of the current best model std::unique_ptr<size_t[]> minimal_sample(new size_t[sample_size]); // The sample used for the estimation std::vector<size_t> pool(points_.rows); for (size_t point_idx = 0; point_idx < point_number; ++point_idx) pool[point_idx] = point_idx; if (points_.rows < sample_size) { fprintf(stderr, "There are not enough points for applying robust estimation. Minimum is %d; while %d are given.\n", sample_size, points_.rows); return false; } // Set the start time variable if there is some time limit set if (desired_fps > -1) start = std::chrono::system_clock::now(); constexpr size_t max_unsuccessful_model_generations = 50; // Main MAGSAC iteration while (mininum_iteration_number > iteration || iteration < max_iteration) { // Increase the current iteration number ++iteration; // Sample a minimal subset std::vector<gcransac::Model> models; // The set of estimated models size_t unsuccessful_model_generations = 0; // The number of unsuccessful model generations // Try to select a minimal sample and estimate the implied model parameters while (++unsuccessful_model_generations < max_unsuccessful_model_generations) { // Get a minimal sample randomly if (!sampler_.sample(pool, // The index pool from which the minimal sample can be selected minimal_sample.get(), // The minimal sample sample_size)) // The size of a minimal sample continue; // Check if the selected sample is valid before estimating the model // parameters which usually takes more time. if (!estimator_.isValidSample(points_, // All points minimal_sample.get())) // The current sample continue; // Estimate the model from the minimal sample if (estimator_.estimateModel(points_, // All data points minimal_sample.get(), // The selected minimal sample &models)) // The estimated models break; } // If the method was not able to generate any usable models, break the cycle. iteration += unsuccessful_model_generations - 1; // Select the so-far-the-best from the estimated models for (const auto &model : models) { ModelScore score; // The score of the current model gcransac::Model refined_model; // The refined model parameters // Apply sigma-consensus to refine the model parameters by marginalizing over the noise level sigma bool success; if (magsac_version == Version::MAGSAC_ORIGINAL) success = sigmaConsensus(points_, model, refined_model, score, estimator_, so_far_the_best_score); else success = sigmaConsensusPlusPlus(points_, model, refined_model, score, estimator_, so_far_the_best_score); // Continue if the model was rejected if (!success || score.score == -1) continue; // Save the iteration number when the current model is found score.iteration = iteration; // Update the best model parameters if needed if (so_far_the_best_score < score) { so_far_the_best_model = refined_model; // Update the best model parameters so_far_the_best_score = score; // Update the best model's score max_iteration = MIN(max_iteration, last_iteration_number); // Update the max iteration number, but do not allow to increase } } // Update the time parameters if a time limit is set if (desired_fps > -1) { end = std::chrono::system_clock::now(); elapsed_seconds = end - start; // Interrupt if the time limit is exceeded if (elapsed_seconds.count() > time_limit) break; } } // Apply sigma-consensus as a post processing step if needed and the estimated model is valid if (apply_post_processing) { // TODO } obtained_model_ = so_far_the_best_model; iteration_number_ = iteration; model_score_ = so_far_the_best_score; return so_far_the_best_score.score > 0; } template <class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::postProcessing( const cv::Mat &points_, const gcransac::Model &model_, gcransac::Model &refined_model_, ModelScore &refined_score_, const ModelEstimator &estimator_) { fprintf(stderr, "Sigma-consensus++ is not implemented yet as post-processing.\n"); return false; } template <class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensus( const cv::Mat &points_, const gcransac::Model& model_, gcransac::Model& refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_) { // Set up the parameters constexpr double L = 1.05; constexpr double k = ModelEstimator::getSigmaQuantile(); constexpr double threshold_to_sigma_multiplier = 1.0 / k; constexpr size_t sample_size = estimator_.sampleSize(); static auto comparator = [](std::pair<double, int> left, std::pair<double, int> right) { return left.first < right.first; }; const int point_number = points_.rows; double current_maximum_sigma = this->maximum_threshold; // Calculating the residuals std::vector< std::pair<double, size_t> > all_residuals; all_residuals.reserve(point_number); // If it is not the first run, consider the previous best and interrupt the validation when there is no chance of being better if (best_score_.inlier_number > 0) { // Number of inliers which should be exceeded int points_remaining = best_score_.inlier_number; // Collect the points which are closer than the threshold which the maximum sigma implies for (int point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index all_residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) --points_remaining; } // Interrupt if there is no chance of being better // TODO: replace this part by SPRT test if (point_number - point_idx < points_remaining) return false; } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = best_score_.inlier_number - points_remaining; } else { // The number of really close points size_t points_close = 0; // Collect the points which are closer than the threshold which the maximum sigma implies for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index all_residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; } std::vector<gcransac::Model> sigma_models; std::vector<size_t> sigma_inliers; std::vector<double> final_weights; // The number of possible inliers const size_t possible_inlier_number = all_residuals.size(); // Sort the residuals in ascending order std::sort(all_residuals.begin(), all_residuals.end(), comparator); // The maximum threshold is set to be slightly bigger than the distance of the // farthest possible inlier. current_maximum_sigma = all_residuals.back().first + std::numeric_limits<double>::epsilon(); const double sigma_step = current_maximum_sigma / partition_number; last_iteration_number = 10000; score_.score = 0; // The weights calculated by each parallel process std::vector<std::vector<double>> point_weights_par(partition_number, std::vector<double>(possible_inlier_number, 0)); // If OpenMP is used, calculate things in parallel #ifdef USE_OPENMP #pragma omp parallel for num_threads(core_number) for (int partition_idx = 0; partition_idx < partition_number; ++partition_idx) { // The maximum sigma value in the current partition const double max_sigma = (partition_idx + 1) * sigma_step; // Find the last element which has smaller distance than 'max_threshold' // Since the vector is ordered binary search can be used to find that particular element. const auto &last_element = std::upper_bound(all_residuals.begin(), all_residuals.end(), std::make_pair(max_sigma, 0), comparator); const size_t sigma_inlier_number = last_element - all_residuals.begin(); // Put the indices into a vector std::vector<size_t> sigma_inliers; sigma_inliers.reserve(sigma_inlier_number); // Store the points which are closer than the current sigma limit for (size_t relative_point_idx = 0; relative_point_idx < sigma_inlier_number; ++relative_point_idx) sigma_inliers.emplace_back(all_residuals[relative_point_idx].second); // Check if there are enough inliers to fit a model if (sigma_inliers.size() > sample_size) { // Estimating the model which the current set of inliers imply std::vector<gcransac::Model> sigma_models; estimator_.estimateModelNonminimal(points_, &(sigma_inliers)[0], sigma_inlier_number, &sigma_models); // If the estimation was successful calculate the implied probabilities if (sigma_models.size() == 1) { const double max_sigma_squared_2 = 2 * max_sigma * max_sigma; double residual_i_2, // The residual of the i-th point probability_i; // The probability of the i-th point // Iterate through all points to estimate the related probabilities for (size_t relative_point_idx = 0; relative_point_idx < sigma_inliers.size(); ++relative_point_idx) { // TODO: Replace with Chi-square instead of normal distribution const size_t &point_idx = sigma_inliers[relative_point_idx]; // Calculate the residual of the current point residual_i_2 = estimator_.squaredResidual(points_.row(point_idx), sigma_models[0]); // Calculate the probability of the i-th point assuming Gaussian distribution // TODO: replace by Chi-square distribution probability_i = exp(-residual_i_2 / max_sigma_squared_2); // Store the probability of the i-th point coming from the current partition point_weights_par[partition_idx][relative_point_idx] += probability_i; } } } } #else fprintf(stderr, "Not implemented yet.\n"); #endif // The weights used for the final weighted least-squares fitting final_weights.reserve(possible_inlier_number); // Collect all points which has higher probability of being inlier than zero sigma_inliers.reserve(possible_inlier_number); for (size_t point_idx = 0; point_idx < possible_inlier_number; ++point_idx) { // Calculate the weight of the current point double weight = 0.0; for (size_t partition_idx = 0; partition_idx < partition_number; ++partition_idx) weight += point_weights_par[partition_idx][point_idx]; // If the weight is approx. zero, continue. if (weight < std::numeric_limits<double>::epsilon()) continue; // Store the index and weight of the current point sigma_inliers.emplace_back(all_residuals[point_idx].second); final_weights.emplace_back(weight); } // If there are fewer inliers than the size of the minimal sample interupt the procedure if (sigma_inliers.size() < sample_size) return false; // Estimate the model parameters using weighted least-squares fitting if (!estimator_.estimateModelNonminimal( points_, // All input points &(sigma_inliers)[0], // Points which have higher than 0 probability of being inlier static_cast<int>(sigma_inliers.size()), // Number of possible inliers &sigma_models, // Estimated models &(final_weights)[0])) // Weights of points return false; bool is_model_updated = false; if (sigma_models.size() == 1 && // If only a single model is estimated estimator_.isValidModel(sigma_models.back(), points_, sigma_inliers, &(sigma_inliers)[0], interrupting_threshold, is_model_updated)) // and it is valid { // Return the refined model refined_model_ = sigma_models.back(); // Calculate the score of the model and the implied iteration number double marginalized_iteration_number; getModelQuality(points_, // All the input points refined_model_, // The estimated model estimator_, // The estimator marginalized_iteration_number, // The marginalized inlier ratio score_.score); // The marginalized score if (marginalized_iteration_number < 0 || std::isnan(marginalized_iteration_number)) last_iteration_number = std::numeric_limits<int>::max(); else last_iteration_number = static_cast<int>(round(marginalized_iteration_number)); return true; } return false; } template <class DatumType, class ModelEstimator> bool MAGSAC<DatumType, ModelEstimator>::sigmaConsensusPlusPlus( const cv::Mat &points_, const gcransac::Model& model_, gcransac::Model& refined_model_, ModelScore &score_, const ModelEstimator &estimator_, const ModelScore &best_score_) { // The degrees of freedom of the data from which the model is estimated. // E.g., for models coming from point correspondences (x1,y1,x2,y2), it is 4. constexpr size_t degrees_of_freedom = ModelEstimator::getDegreesOfFreedom(); // A 0.99 quantile of the Chi^2-distribution to convert sigma values to residuals constexpr double k = ModelEstimator::getSigmaQuantile(); // A multiplier to convert residual values to sigmas constexpr double threshold_to_sigma_multiplier = 1.0 / k; // Calculating k^2 / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double squared_k_per_2 = k * k / 2.0; // Calculating (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_minus_one_per_two = (degrees_of_freedom - 1.0) / 2.0; // TODO: check constexpr double C = ModelEstimator::getC(); // The size of a minimal sample used for the estimation constexpr size_t sample_size = estimator_.sampleSize(); // Calculating 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof = std::pow(2.0, dof_minus_one_per_two); // Calculating C * 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double C_times_two_ad_dof = C * two_ad_dof; // Calculating the gamma value of (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double gamma_value = tgamma(dof_minus_one_per_two); // Calculating the upper incomplete gamma value of (DoF - 1) / 2 with k^2 / 2. constexpr double gamma_k = ModelEstimator::getUpperIncompleteGammaOfK(); // Calculating the lower incomplete gamma value of (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double gamma_difference = gamma_value - gamma_k; // The number of points provided const int point_number = points_.rows; // The manually set maximum inlier-outlier threshold double current_maximum_sigma = this->maximum_threshold; // Calculating the pairs of (residual, point index). std::vector< std::pair<double, size_t> > residuals; // Occupy the maximum required memory to avoid doing it later. residuals.reserve(point_number); // If it is not the first run, consider the previous best and interrupt the validation when there is no chance of being better if (best_score_.inlier_number > 0) { // Number of points close to the previous so-far-the-best model. // This model should have more inliers. int points_remaining = best_score_.inlier_number; // Collect the points which are closer than the threshold which the maximum sigma implies for (int point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // all_residuals.emplace_back(std::make_pair(residual * threshold_to_sigma_multiplier, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) --points_remaining; } // Interrupt if there is no chance of being better // TODO: replace this part by SPRT test if (point_number - point_idx < points_remaining) return false; } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = best_score_.inlier_number - points_remaining; } else { // The number of really close points size_t points_close = 0; // Collect the points which are closer than the threshold which the maximum sigma implies for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), model_); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; } // Models fit by weighted least-squares fitting std::vector<gcransac::Model> sigma_models; // Points used in the weighted least-squares fitting std::vector<size_t> sigma_inliers; // Weights used in the the weighted least-squares fitting std::vector<double> sigma_weights; // Number of points considered in the fitting const size_t possible_inlier_number = residuals.size(); // Occupy the memory to avoid doing it inside the calculation possibly multiple times sigma_inliers.reserve(possible_inlier_number); // Occupy the memory to avoid doing it inside the calculation possibly multiple times sigma_weights.reserve(possible_inlier_number); // Calculate 2 * \sigma_{max}^2 a priori const double squared_sigma_max_2 = current_maximum_sigma * current_maximum_sigma * 2.0; // Divide C * 2^(DoF - 1) by \sigma_{max} a priori const double one_over_sigma = C_times_two_ad_dof / current_maximum_sigma; // Calculate the weight of a point with 0 residual (i.e., fitting perfectly) a priori const double weight_zero = one_over_sigma * gamma_difference; // Initialize the polished model with the initial one gcransac::Model polished_model = model_; // A flag to determine if the initial model has been updated bool updated = false; // Do the iteratively re-weighted least squares fitting for (size_t iterations = 0; iterations < number_of_irwls_iters; ++iterations) { // If the current iteration is not the first, the set of possibly inliers // (i.e., points closer than the maximum threshold) have to be recalculated. if (iterations > 0) { // The number of points close to the model size_t points_close = 0; // Remove everything from the residual vector residuals.clear(); // Collect the points which are closer than the maximum threshold for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residual(points_.row(point_idx), polished_model); if (current_maximum_sigma > residual) { // Store the residual of the current point and its index residuals.emplace_back(std::make_pair(residual, point_idx)); // Count points which are closer than a reference threshold to speed up the procedure if (residual < interrupting_threshold) ++points_close; } } // Store the number of really close inliers just to speed up the procedure // by interrupting the next verifications. score_.inlier_number = points_close; // Number of points closer than the threshold const size_t possible_inlier_number = residuals.size(); // Clear the inliers and weights sigma_inliers.clear(); sigma_weights.clear(); // Occupy the memory for the inliers and weights sigma_inliers.reserve(possible_inlier_number); sigma_weights.reserve(possible_inlier_number); } // Calculate the weight of each point //IS: C++11 compatible part //for (const auto &[residual, idx] : residuals) //{ for (const auto residualAndIdx : residuals) { double residual = std::get<0>(residualAndIdx); size_t idx = std::get<1>(residualAndIdx); // The weight double weight = 0.0; // If the residual is ~0, the point fits perfectly and it is handled differently if (residual < std::numeric_limits<double>::epsilon()) weight = weight_zero; else { // Calculate the squared residual const double squared_residual = residual * residual; // Get the position of the gamma value in the lookup table size_t x = round(precision_of_stored_gammas * squared_residual / squared_sigma_max_2); // Put the index of the point into the vector of points used for the least squares fitting sigma_inliers.emplace_back(idx); // If the sought gamma value is not stored in the lookup, return the closest element if (stored_gamma_number < x) x = stored_gamma_number; // Calculate the weight of the point weight = one_over_sigma * (stored_gamma_values[x] - gamma_k); } // Store the weight of the point sigma_weights.emplace_back(weight); } // If there are fewer than the minimum point close to the model, // terminate. if (sigma_inliers.size() < sample_size) return false; // Estimate the model parameters using weighted least-squares fitting if (!estimator_.estimateModelNonminimal( points_, // All input points &(sigma_inliers)[0], // Points which have higher than 0 probability of being inlier static_cast<int>(sigma_inliers.size()), // Number of possible inliers &sigma_models, // Estimated models &(sigma_weights)[0])) // Weights of points { // If the estimation failed and the iteration was never successfull, // terminate with failure. if (iterations == 0) return false; // Otherwise, if the iteration was successfull at least one, // simply break it. break; } // Update the model parameters polished_model = sigma_models[0]; // Clear the vector of models and keep only the best sigma_models.clear(); // The model has been updated updated = true; } bool is_model_updated = false; if (updated && // If the model has been updated estimator_.isValidModel(polished_model, points_, sigma_inliers, &(sigma_inliers[0]), interrupting_threshold, is_model_updated)) // and it is valid { // Return the refined model refined_model_ = polished_model; // Calculate the score of the model and the implied iteration number double marginalized_iteration_number; getModelQualityPlusPlus(points_, // All the input points refined_model_, // The estimated model estimator_, // The estimator score_.score, // The marginalized score best_score_.score); // The score of the previous so-far-the-best model // Update the iteration number last_iteration_number = log_confidence / log(1.0 - std::pow(static_cast<double>(score_.inlier_number) / point_number, sample_size)); return true; } return false; } template <class DatumType, class ModelEstimator> void MAGSAC<DatumType, ModelEstimator>::getModelQualityPlusPlus( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &score_, // The score to be calculated const double &previous_best_score_) // The score of the previous so-far-the-best model { // The degrees of freedom of the data from which the model is estimated. // E.g., for models coming from point correspondences (x1,y1,x2,y2), it is 4. constexpr size_t degrees_of_freedom = ModelEstimator::getDegreesOfFreedom(); // A 0.99 quantile of the Chi^2-distribution to convert sigma values to residuals constexpr double k = ModelEstimator::getSigmaQuantile(); // A multiplier to convert residual values to sigmas constexpr double threshold_to_sigma_multiplier = 1.0 / k; // Calculating k^2 / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double squared_k_per_2 = k * k / 2.0; // Calculating (DoF - 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_minus_one_per_two = (degrees_of_freedom - 1.0) / 2.0; // Calculating (DoF + 1) / 2 which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. constexpr double dof_plus_one_per_two = (degrees_of_freedom + 1.0) / 2.0; // TODO: check constexpr double C = 0.25; // Calculating 2^(DoF - 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof_minus_one = std::pow(2.0, dof_minus_one_per_two); // Calculating 2^(DoF + 1) which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. static const double two_ad_dof_plus_one = std::pow(2.0, dof_plus_one_per_two); // Calculate the gamma value of k constexpr double gamma_value_of_k = ModelEstimator::getUpperIncompleteGammaOfK(); // Calculate the lower incomplete gamma value of k constexpr double lower_gamma_value_of_k = ModelEstimator::getLowerIncompleteGammaOfK(); // The number of points provided const int point_number = points_.rows; // The previous best loss const double previous_best_loss = 1.0 / previous_best_score_; // Convert the maximum threshold to a sigma value const double maximum_sigma = threshold_to_sigma_multiplier * maximum_threshold; // Calculate the squared maximum sigma const double maximum_sigma_2 = maximum_sigma * maximum_sigma; // Calculate \sigma_{max}^2 / 2 const double maximum_sigma_2_per_2 = maximum_sigma_2 / 2.0; // Calculate 2 * \sigma_{max}^2 const double maximum_sigma_2_times_2 = maximum_sigma_2 * 2.0; // Calculate the loss implied by an outlier const double outlier_loss = maximum_sigma * two_ad_dof_minus_one * lower_gamma_value_of_k; // Calculating 2^(DoF + 1) / \sigma_{max} which will be used for the estimation and, // due to being constant, it is better to calculate it a priori. const double two_ad_dof_plus_one_per_maximum_sigma = two_ad_dof_plus_one / maximum_sigma; // The loss which a point implies double loss = 0.0, // The total loss regarding the current model total_loss = 0.0; // Iterate through all points to calculate the implied loss for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); // If the residual is smaller than the maximum threshold, consider it outlier // and add the loss implied to the total loss. if (maximum_threshold < residual) loss = outlier_loss; else // Otherwise, consider the point inlier, and calculate the implied loss { // Calculate the squared residual const double squared_residual = residual * residual; // Divide the residual by the 2 * \sigma^2 const double squared_residual_per_sigma = squared_residual / maximum_sigma_2_times_2; // Get the position of the gamma value in the lookup table size_t x = round(precision_of_stored_incomplete_gammas * squared_residual_per_sigma); // If the sought gamma value is not stored in the lookup, return the closest element if (stored_incomplete_gamma_number < x) x = stored_incomplete_gamma_number; // Calculate the loss implied by the current point loss = maximum_sigma_2_per_2 * stored_lower_incomplete_gamma_values[x] + squared_residual / 4.0 * (stored_complete_gamma_values[x] - gamma_value_of_k); loss = loss * two_ad_dof_plus_one_per_maximum_sigma; } // Update the total loss total_loss += loss; // Break the validation if there is no chance of being better than the previous // so-far-the-best model. if (previous_best_loss < total_loss) break; } // Calculate the score of the model from the total loss score_ = 1.0 / total_loss; } template <class DatumType, class ModelEstimator> void MAGSAC<DatumType, ModelEstimator>::getModelQuality( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, // The model estimator class double &marginalized_iteration_number_, // The marginalized iteration number to be calculated double &score_) // The score to be calculated { // Set up the parameters constexpr size_t sample_size = estimator_.sampleSize(); const size_t point_number = points_.rows; // Getting the inliers std::vector<std::pair<double, size_t>> all_residuals; all_residuals.reserve(point_number); double max_distance = 0; for (size_t point_idx = 0; point_idx < point_number; ++point_idx) { // Calculate the residual of the current point const double residual = estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); // If the residual is smaller than the maximum threshold, add it to the set of possible inliers if (maximum_threshold > residual) { max_distance = MAX(max_distance, residual); all_residuals.emplace_back(std::make_pair(residual, point_idx)); } } // Set the maximum distance to be slightly bigger than that of the farthest possible inlier max_distance = max_distance + std::numeric_limits<double>::epsilon(); // Number of possible inliers const size_t possible_inlier_number = all_residuals.size(); // The extent of a partition const double threshold_step = max_distance / partition_number; // The maximum threshold considered in each partition std::vector<double> thresholds(partition_number); std::vector<double> thresholds_squared(partition_number); std::vector<double> thresholds_2_squared(partition_number); // Calculating the thresholds for each partition for (size_t i = 0; i < partition_number; ++i) { thresholds[i] = (i + 1) * threshold_step; thresholds_squared[i] = thresholds[i] * thresholds[i]; thresholds_2_squared[i] = 2 * thresholds_squared[i]; } double residual_i, // Residual of the i-th point residual_i_squared, // Squared residual of the i-th poin probability_i; // Probability of the i-th point given the model std::vector<double> inliers(partition_number, 0), // RANSAC score for each partition probabilities(partition_number, 1); // Probabilities for each partition for (size_t point_idx = 0; point_idx < possible_inlier_number; ++point_idx) { residual_i = all_residuals[point_idx].first; residual_i_squared = residual_i * residual_i; for (size_t i = 0; i < partition_number; ++i) { if (residual_i < thresholds[i]) { probability_i = 1.0 - residual_i_squared / thresholds_squared[i]; ++inliers[i]; probabilities[i] += probability_i; } } } score_ = 0; marginalized_iteration_number_ = 0.0; for (auto i = 0; i < partition_number; ++i) { score_ += probabilities[i]; marginalized_iteration_number_ += log_confidence / log(1.0 - std::pow(inliers[i] / point_number, sample_size)); } marginalized_iteration_number_ = marginalized_iteration_number_ / partition_number; } // The function to extract inliers mask of a model // for a given threshold template <class DatumType, class ModelEstimator> void MAGSAC<DatumType, ModelEstimator>::getModelInliersMask( const cv::Mat &points_, // All data points const gcransac::Model &model_, // The model parameter const ModelEstimator &estimator_, const double threshold_, // Inlier/outlier threshold std::vector<bool> &inliers_mask_) { if (inliers_mask_.size() != points_.rows) inliers_mask_.resize(points_.rows); // Iterate through all points to calculate the implied loss // TODO: Remove after debugging //int cnt = 0; for (size_t point_idx = 0; point_idx < points_.rows; ++point_idx) { // Compare with threshold to set a flag inliers_mask_[point_idx] = threshold_ > estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); } //printf("\t\tTotal inliers by epipolar error: %d\n", std::count(inliers_mask_.begin(), inliers_mask_.end(), true)); // TODO: Right for (size_t point_idx = 0; point_idx < points_.rows; ++point_idx) { // Compare with threshold to set a flag //inliers_mask_[point_idx] = threshold_ > estimator_.residualForScoring(points_.row(point_idx), model_.descriptor); inliers_mask_[point_idx] = threshold_ > estimator_.residualOtherForScoring(points_.row(point_idx), model_.descriptor); } //printf("\t\tTotal inliers by sampson error: %d\n", std::count(inliers_mask_.begin(), inliers_mask_.end(), true)); }
DRB092-threadprivatemissing2-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* A file-scope variable used within a function called by a parallel region. No threadprivate is used to avoid data races. This is the case for a variable referenced within a construct. Data race pairs sum0@68:7 vs. sum0@68:12 sum0@68:7 vs. sum0@68:7 */ #include <stdio.h> #include <assert.h> int sum0=0, sum1=0; //#pragma omp threadprivate(sum0) int main() { int i, sum=0; { for (i=1;i<=1000;i++) { sum0=sum0+i; } } sum= sum+sum0; /* reference calculation */ for (i=1;i<=1000;i++) { sum1=sum1+i; } printf("sum=%d; sum1=%d\n",sum,sum1); // assert(sum==sum1); return 0; }
GB_unaryop__lnot_fp32_fp32.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_fp32_fp32 // op(A') function: GB_tran__lnot_fp32_fp32 // C type: float // A type: float // cast: float cij = (float) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ float #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ float z = (float) 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_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp32_fp32 ( float *Cx, // Cx and Ax may be aliased float *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_fp32_fp32 ( 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
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 FAU_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 inline virtual void to_json(json &j) const {}; //!< json output inline virtual void sync(Energybase*, Change&) {} }; void to_json(json &j, const Energybase &base) { assert(!base.name.empty()); if (!base.cite.empty()) j[base.name]["reference"] = base.cite; base.to_json( j[base.name] ); } //!< 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) { L = box; int kcc = std::ceil(kc); check_k2_zero = 0.1*std::pow(2*pc::pi/L.maxCoeff(), 2); int kVectorsLength = (2*kcc+1) * (2*kcc+1) * (2*kcc+1) - 1; if (kVectorsLength == 0) { kVectors.resize(3,1); Aks.resize(1); kVectors.col(0) = Point(1,0,0); // Just so it is not the zero-vector Aks[0] = 0; kVectorsInUse = 1; Qion.resize(1); Qdip.resize(1); } else { double kc2 = kc*kc; kVectors.resize(3, kVectorsLength); Aks.resize(kVectorsLength); kVectorsInUse = 0; kVectors.setZero(); Aks.setZero(); int startValue = 1 - int(ipbc); for (int kx = 0; kx <= kcc; kx++) { double dkx2 = double(kx*kx); for (int ky = -kcc*startValue; ky <= kcc; ky++) { double dky2 = double(ky*ky); for (int kz = -kcc*startValue; kz <= kcc; kz++) { double factor = 1.0; if(kx > 0) factor *= 2; if(ky > 0 && ipbc) factor *= 2; if(kz > 0 && ipbc) factor *= 2; double dkz2 = double(kz*kz); Point kv = 2*pc::pi*Point(kx/L.x(),ky/L.y(),kz/L.z()); double k2 = kv.dot(kv); if (k2 < check_k2_zero) // Check if k2 != 0 continue; if (spherical_sum) if( (dkx2/kc2) + (dky2/kc2) + (dkz2/kc2) > 1) continue; kVectors.col(kVectorsInUse) = kv; Aks[kVectorsInUse] = factor*std::exp(-k2/(4*alpha*alpha))/k2; kVectorsInUse++; } } } Qion.resize(kVectorsInUse); Qdip.resize(kVectorsInUse); Aks.conservativeResize(kVectorsInUse); kVectors.conservativeResize(3,kVectorsInUse); } } }; void from_json(const json &j, EwaldData &d) { d.alpha = j.at("alpha"); d.rc = j.at("cutoff"); d.kc = j.at("kcutoff"); d.ipbc = j.value("ipbc", false); d.spherical_sum = j.value("spherical_sum", true); d.lB = pc::lB( j.at("epsr") ); d.eps_surf = j.value("epss", 0.0); d.const_inf = (d.eps_surf < 1) ? 0 : 1; // if unphysical (<1) use epsr infinity for surrounding medium } void to_json(json &j, const EwaldData &d) { j = {{"lB", d.lB}, {"ipbc", d.ipbc}, {"epss", d.eps_surf}, {"alpha", d.alpha}, {"cutoff", d.rc}, {"kcutoff", d.kc}, {"wavefunctions", d.kVectors.cols()}, {"spherical_sum", d.spherical_sum}}; } #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; public: Tspace& spc; Ewald(const json &j, Tspace &spc) : policy(spc), spc(spc) { name = "ewald"; data = j; 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); } }; 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 dummy; dummy.pos = g.cm; u = func(dummy); } 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 || 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 || COM) // check all atoms in group u += _energy(g); 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 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 || 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 || 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<Potential::BondData> BondVector; BondVector inter; // inter-molecular bonds std::map<int,BondVector> intra; // intra-molecular bonds void update() { intra.clear(); for (size_t i=0; i<spc.groups.size(); i++) { if (!spc.groups.empty()) { auto &g = spc.groups[i]; intra[i] = molecules<Tpvec>.at(g.id).bonds; for (auto &b : intra[i]) b.shift( std::distance(spc.p.begin(), g.begin()) ); } } } // finds and adds all intra-molecular bonds of active molecules double sum( const BondVector &v ) const { double u=0; for (auto &b : v) u += b.energy(spc.p, 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>(); } 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`. */ virtual double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index=std::vector<int>()) { double u = 0; if (!cut(g1,g2)) { if (index.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) u += i2i( *(g1.begin()+i), 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); } 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) { 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; } 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; double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index=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) { base::name += "EM"; 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; } } } 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=1; 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); 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 || 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()=="charge") 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 (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(2,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 (!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() << endl; if (f2) f2 << histo << endl; // 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 (!rcvec[i]->inRange(coord[i])) return pc::infty; } penalty.to_index(coord); u = penalty[coord]; } return (nodrift) ? u - udelta : u; } virtual void update(const std::vector<double> &c) { if (++cnt % nupdate == 0 && f0>0) { bool b = histo.minCoeff() >= (int)samplings; if (b && f0>0) { double min = penalty.minCoeff(); penalty = penalty.array() - min; if (!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); other->update(other->coord); } // @todo: this double 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; 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 && 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 += double(weights[i]) * Eigen::Map<Eigen::MatrixXd>( buffer.data()+i*penalty.size(), penalty.rows(), penalty.cols() ); penalty = ( penalty.array() - penalty.minCoeff() ) / double(weights.sum()); } MPI_Bcast(penalty.data(), penalty.size(), MPI_DOUBLE, 0, mpi.comm); 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 FAU_POWERSASA template<class Tspace> class SASAEnergy : public Energybase { typedef typename Tspace::Tparticle Tparticle; typedef typename Tspace::Tpvec Tpvec; Tspace& spc; std::vector<float> sasa, radii; std::vector<Point> coords; 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; void updateSASA(const Tpvec &p) { radii.resize(p.size()); coords.resize(p.size()); std::transform(p.begin(), p.end(), coords.begin(), [](auto &a){ return a.pos;}); std::transform(p.begin(), p.end(), radii.begin(), [this](auto &a){ return atoms<Tparticle>[a.id].sigma*0.5 + this->probe;}); ps->update_coords(coords, 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); } 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.value("molarity", conc) * 1.0_molar; radii.resize(spc.p.size()); coords.resize(spc.p.size()); std::transform(spc.p.begin(), spc.p.end(), coords.begin(), [](auto &a){ return a.pos;}); std::transform(spc.p.begin(), spc.p.end(), radii.begin(), [this](auto &a){ return atoms<Tparticle>[a.id].sigma*0.5 + this->probe;}); ps = std::make_shared<POWERSASA::PowerSasa<float,Point>>(coords,radii); } double energy(Change &change) override { double u=0, A=0; updateSASA(spc.p); for (size_t i=0; i<sasa.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 { double s=1+std::sin(2*pc::pi*i.x())+std::cos(2*pc::pi*i.y()); if (i.x()>=-2.00 && i.x()<=-1.25) return 1*s; if (i.x()>=-1.25 && i.x()<=-0.25) return 2*s; if (i.x()>=-0.25 && i.x()<= 0.75) return 3*s; if (i.x()>= 0.75 && i.x()<= 1.75) return 4*s; if (i.x()>= 1.75 && i.x()<= 2.00) return 5*s; return 1e10; } }; template<typename Tspace> class Hamiltonian : public Energybase, public BasePointerVector<Energybase> { protected: 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 (vec.size()==oldsize) std::cerr << "warning: ignoring unknown energy '" << it.key() << "'" << endl; } 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); } return du; } //!< Energy due to changes void sync(Energybase* basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); if (other!=NULL) { if (other->size()==size()) for (size_t i=0; i<size(); i++) this->vec[i]->sync( other->vec[i].get(), change); } else throw std::runtime_error("hamiltonian mismatch"); } }; //!< Aggregates and sum energy terms }//namespace }//namespace
spmv_double.c
////Example of sparse matrix-vector multiply, using CSR (compressed sparse row format). #include <stdio.h> #include <stdlib.h> #include <string.h> // Add timing support #include <sys/timeb.h> double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //#define DEFAULT_DIMSIZE 256 void print_array(char *title, char *name, double *A, int n, int m) { printf("%s:\n", title); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%s[%d][%d]:%f ", name, i, j, A[i * m + j]); } printf("\n"); } printf("\n"); } /* subroutine error_check (n,m,alpha,dx,dy,u,f) implicit none ************************************************************ * Checks error between numerical and exact solution * ************************************************************/ int main(int argc, char *argv[]) { int *ia, *ja; double *a, *x, *y; int row, i, j, idx, n, nnzMax, nnz, nrows; double ts, t, rate; n = 10240; //n = 24; if (argc > 1) n = atoi(argv[1]); nrows = n * n; nnzMax = nrows * 5; ia = (int*)malloc(nrows*sizeof(int)); ja = (int*)malloc(nnzMax*sizeof(int)); a = (double*)malloc(nnzMax*sizeof(double)); /* Allocate the source and result vectors */ x = (double*)malloc(nrows*sizeof(double)); y = (double*)malloc(nrows*sizeof(double)); row = 0; nnz = 0; for (i=0; i<n; i++) { for (j=0; j<n; j++) { ia[row] = nnz; if (i>0) { ja[nnz] = row - n; a[nnz] = -1.0; nnz++; } if (j>0) { ja[nnz] = row - 1; a[nnz] = -1.0; nnz++; } ja[nnz] = row; a[nnz] = 4.0; nnz++; if (j<n-1) { ja[nnz] = row + 1; a[nnz] = -1.0; nnz++; } if (i<n-1) { ja[nnz] = row + n; a[nnz] = -1.0; nnz++; } row++; } } ia[row] = nnz; /* Create the source (x) vector */ for (i=0; i<nrows; i++) x[i] = 1.0; double elapsed = read_timer(); int flops = 0; for (row=0; row<nrows; row++) { double sum = 0.0; #pragma omp simd reduction(+:sum,flops) simdlen(8) for (idx=ia[row]; idx<ia[row+1]; idx++) { sum += a[idx] * x[ja[idx]]; flops += 2; } y[row] = sum; } elapsed = read_timer() - elapsed; double gflops = flops / (1.0e9 * elapsed); printf("seq elasped time(s): %.4f\n", elapsed); printf("GFlops: %.4f\n", gflops); for (row=0; row<nrows; row++) { if (y[row] < 0) { fprintf(stderr,"y[%d]=%f, fails consistency test\n", row, y[row]); } } free(ia); free(ja); free(a); free(x); free(y); return 0; }
DRB010-lastprivatemissing-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. */ /* This loop has loop-carried output-dependence due to x=... at line 63. The problem can be solved by using lastprivate(x) . Data race pair: x@63:5 vs. x@63:5 */ #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc,char *argv[]) { int i; int x; int len = 10000; if (argc > 1) len = atoi(argv[1]); #pragma omp parallel for private (i) lastprivate (x) firstprivate (len) for (i = 0; i <= len - 1; i += 1) { x = i; } printf("x=%d",x); return 0; }
axpy_float_avx2.c
//axpy.c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #define N_RUNS 20 #define N 102400000 // read timer in second double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //Create a matrix and a vector and fill with random numbers void init(float *X, float *Y) { for (int i = 0; i<N; i++) { X[i] = (float)rand()/(float)(RAND_MAX/10.0); Y[i] = (float)rand()/(float)(RAND_MAX/10.0); } } //Our sum function- what it does is pretty straight-forward. void axpy(float *X, float *Y, float a) { #pragma omp simd simdlen(8) for (int i = 0; i<N; i++) { Y[i] += a * X[i]; } } // Debug functions void axpy_serial(float *X, float *Y, float a) { for (int i = 0; i<N; i++) { Y[i] += a * X[i]; } } void print_vector(float *vector) { printf("["); for (int i = 0; i<8; i++) { printf("%.2f ", vector[i]); } puts("]"); } float check(float *A, float *B){ float difference = 0; for(int i = 0;i<N; i++){ difference += A[i]- B[i]; } return difference; } int main(int argc, char **argv) { //Set everything up float *X = malloc(sizeof(float)*N); float *Y = malloc(sizeof(float)*N); float *Y_serial = malloc(sizeof(float)*N); float a = 3.14; srand(time(NULL)); init(X, Y); for (int i = 0; i<N; i++) Y_serial[i] = Y[i]; print_vector(Y); print_vector(X); printf("%.2f\n", a); puts("=\n"); //warming up axpy(X, Y, a); axpy_serial(X, Y_serial, a); init(X, Y); for (int i = 0; i<N; i++) Y_serial[i] = Y[i]; double t = 0; double start = read_timer(); for (int i = 0; i<N_RUNS; i++) axpy(X, Y, a); t += (read_timer() - start); double t_serial = 0; double start_serial = read_timer(); for (int i = 0; i<N_RUNS; i++) axpy_serial(X, Y_serial, a); t_serial += (read_timer() - start_serial); print_vector(Y); puts("---------------------------------"); print_vector(Y_serial); double gflops = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t); double gflops_serial = ((2.0 * N) * N * N_RUNS) / (1.0e9 * t_serial); printf("==================================================================\n"); printf("Performance:\t\t\tRuntime (s)\t GFLOPS\n"); printf("------------------------------------------------------------------\n"); printf("AXPY (SIMD):\t\t%4f\t%4f\n", t/N_RUNS, gflops); printf("AXPY (Serial):\t\t%4f\t%4f\n", t_serial/N_RUNS, gflops_serial); printf("Correctness check: %f\n", check(Y,Y_serial)); free(X); free(Y); free(Y_serial); return 0; }
dragonfly3_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * based on rawSHA256_fmt.c code * * This software is Copyright (c) 2012 magnum, 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. * * The DragonFly BSD 2.10.1-REL crypt-sha2 hashes are seriously broken. See * http://www.openwall.com/lists/john-dev/2012/01/16/1 * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_dragonfly3_32; extern struct fmt_main fmt_dragonfly3_64; #elif FMT_REGISTERS_H john_register_one(&fmt_dragonfly3_32); john_register_one(&fmt_dragonfly3_64); #else #include "sha2.h" #include <string.h> #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #ifdef _OPENMP #define OMP_SCALE 256 #include <omp.h> #endif #include "memdbg.h" #define FORMAT_LABEL_32 "dragonfly3-32" #define FORMAT_LABEL_64 "dragonfly3-64" #define FORMAT_NAME_32 "DragonFly BSD $3$ w/ bug, 32-bit" #define FORMAT_NAME_64 "DragonFly BSD $3$ w/ bug, 64-bit" #define ALGORITHM_NAME "SHA256 32/" ARCH_BITS_STR " " SHA2_LIB #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define CIPHERTEXT_LENGTH 44 #define BINARY_SIZE 32 #define BINARY_ALIGN 4 #define SALT_SIZE_32 (1+4+8) // 1st char is length #define SALT_SIZE_64 (1+8+8) #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests_32[] = { {"$3$z$EBG66iBCGfUfENOfqLUH/r9xQxI1cG373/hRop6j.oWs", "magnum"}, {"$3$f6daU5$Xf/u8pKp.sb4VCLKz7tTZMUKJ3J4oOfZgUSHYOFL.M0n", ""}, {"$3$PNPA2tJ$ppD4bXqPMYFVdYVYrxXGMWeYB6Xv8e6jmXbvrB5V.okl", "password"}, {"$3$jWhDSrS$bad..Dy7UAyabPyfrEi3fgQ2qtT.5fE7C5EMNo/n.Qk5", "John the Ripper"}, {"$3$SSYEHO$hkuDmUQHT2Tr0.ai.lUVyb9bCC875Up.CZVa6UJZ.Muv", "DragonFly BSD"}, {NULL} }; static struct fmt_tests tests_64[] = { {"$3$z$sNV7KLtLxvJRsj2MfBtGZFuzXP3CECITaFq/rvsy.Y.Q", "magnum"}, {"$3$f6daU5$eV2SX9vUHTMsoy3Ic7cWiQ4mOxyuyenGjYQWkJmy.AF3", ""}, {"$3$PNPA2tJ$GvXjg6zSge3YDh5I35JlYZHoQS2r0/.vn36fQzSY.A0d", "password"}, {"$3$jWhDSrS$5yBH7KFPmsg.PhPeDMj1MY4fv9061zdbYumPe2Ve.Y5J", "John the Ripper"}, {"$3$SSYEHO$AMYLyanRYs8F2U07FsBrSFuOIygJ4kgqvpBB17BI.61N", "DragonFly BSD"}, {NULL} }; static int (*saved_key_length); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out) [(BINARY_SIZE + sizeof(ARCH_WORD_32) - 1) / sizeof(ARCH_WORD_32)]; static char *cur_salt; static int salt_len; static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt = omp_t * MIN_KEYS_PER_CRYPT; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt = omp_t * MAX_KEYS_PER_CRYPT; #endif saved_key_length = mem_calloc_tiny(sizeof(*saved_key_length) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); crypt_out = mem_calloc_tiny(sizeof(*crypt_out) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); } static int valid(char *ciphertext, struct fmt_main *self) { char *pos, *start; if (strncmp(ciphertext, "$3$", 3)) return 0; ciphertext += 3; for (pos = ciphertext; *pos && *pos != '$'; pos++); if (!*pos || pos < ciphertext || pos > &ciphertext[8]) return 0; start = ++pos; while (atoi64[ARCH_INDEX(*pos)] != 0x7F) pos++; if (*pos || pos - start != CIPHERTEXT_LENGTH) return 0; return 1; } #define TO_BINARY(b1, b2, b3) \ value = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) | \ ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18); \ pos += 4; \ out[b1] = value >> 16; \ out[b2] = value >> 8; \ out[b3] = value; static void *get_binary(char *ciphertext) { static ARCH_WORD_32 outbuf[BINARY_SIZE/4]; ARCH_WORD_32 value; char *pos; unsigned char *out = (unsigned char*)outbuf; int i; pos = strrchr(ciphertext, '$') + 1; for (i = 0; i < 10; i++) { TO_BINARY(i, i + 11, i + 21); } value = (ARCH_WORD_32)atoi64[ARCH_INDEX(pos[0])] | ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[1])] << 6) | ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[2])] << 12) | ((ARCH_WORD_32)atoi64[ARCH_INDEX(pos[3])] << 18); out[10] = value >> 16; out[31] = value >> 8; return (void *)out; } static int get_hash_0(int index) { return crypt_out[index][0] & 0xf; } static int get_hash_1(int index) { return crypt_out[index][0] & 0xff; } static int get_hash_2(int index) { return crypt_out[index][0] & 0xfff; } static int get_hash_3(int index) { return crypt_out[index][0] & 0xffff; } static int get_hash_4(int index) { return crypt_out[index][0] & 0xfffff; } static int get_hash_5(int index) { return crypt_out[index][0] & 0xffffff; } static int get_hash_6(int index) { return crypt_out[index][0] & 0x7ffffff; } static void set_key(char *key, int index) { int len = strlen(key); saved_key_length[index] = len; if (len > PLAINTEXT_LENGTH) len = saved_key_length[index] = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, len); } static char *get_key(int index) { saved_key[index][saved_key_length[index]] = 0; return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { SHA256_CTX ctx; SHA256_Init(&ctx); /* First the password */ SHA256_Update(&ctx, saved_key[index], saved_key_length[index]); /* Then the salt, including the $3$ magic */ SHA256_Update(&ctx, cur_salt, salt_len); SHA256_Final((unsigned char*)crypt_out[index], &ctx); } return count; } static void set_salt(void *salt) { salt_len = (int)*(char*)salt; cur_salt = (char*)salt + 1; } // For 32-bit version of the bug, our magic is "$3$\0" len 4 static void *get_salt_32(char *ciphertext) { static char *out; int len; if (!out) out = mem_alloc_tiny(SALT_SIZE_32, MEM_ALIGN_WORD); memset(out, 0, SALT_SIZE_32); ciphertext += 3; strcpy(&out[1], "$3$"); for (len = 0; ciphertext[len] != '$'; len++); memcpy(&out[5], ciphertext, len); out[0] = len + 4; return out; } // For 64-bit version of the bug, our magic is "$3$\0sha5" len 8 static void *get_salt_64(char *ciphertext) { static char *out; int len; if (!out) out = mem_alloc_tiny(SALT_SIZE_64, MEM_ALIGN_WORD); memset(out, 0, SALT_SIZE_64); ciphertext += 3; memcpy(&out[1], "$3$\0sha5", 8); for (len = 0; ciphertext[len] != '$'; len++); memcpy(&out[9], ciphertext, len); out[0] = len + 8; return out; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], BINARY_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } // Public domain hash function by DJ Bernstein static int salt_hash(void *salt) { unsigned char *s = (unsigned char*)salt + 1; unsigned int hash = 5381; unsigned int i; for (i = 0; i < *(unsigned char*)salt; i++) hash = ((hash << 5) + hash) ^ s[i]; return hash & (SALT_HASH_SIZE - 1); } struct fmt_main fmt_dragonfly3_32 = { { FORMAT_LABEL_32, FORMAT_NAME_32, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE_32, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests_32 }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt_32, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, 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 } }; struct fmt_main fmt_dragonfly3_64 = { { FORMAT_LABEL_64, FORMAT_NAME_64, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE_64, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, #if FMT_MAIN_VERSION > 11 { NULL }, #endif tests_64 }, { init, fmt_default_done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt_64, #if FMT_MAIN_VERSION > 11 { NULL }, #endif fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, 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 */
queue.h
// -*- C++ -*- // Copyright (C) 2007-2014 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/queue.h * @brief Lock-free double-ended queue. * This file is a GNU parallel extension to the Standard C++ Library. */ // Written by Johannes Singler. #ifndef _GLIBCXX_PARALLEL_QUEUE_H #define _GLIBCXX_PARALLEL_QUEUE_H 1 #include <parallel/types.h> #include <parallel/base.h> #include <parallel/compatibility.h> /** @brief Decide whether to declare certain variable volatile in this file. */ #define _GLIBCXX_VOLATILE volatile namespace __gnu_parallel { /**@brief Double-ended queue of bounded size, allowing lock-free * atomic access. push_front() and pop_front() must not be called * concurrently to each other, while pop_back() can be called * concurrently at all times. * @c empty(), @c size(), and @c top() are intentionally not provided. * Calling them would not make sense in a concurrent setting. * @param _Tp Contained element type. */ template<typename _Tp> class _RestrictedBoundedConcurrentQueue { private: /** @brief Array of elements, seen as cyclic buffer. */ _Tp* _M_base; /** @brief Maximal number of elements contained at the same time. */ _SequenceIndex _M_max_size; /** @brief Cyclic __begin and __end pointers contained in one atomically changeable value. */ _GLIBCXX_VOLATILE _CASable _M_borders; public: /** @brief Constructor. Not to be called concurrent, of course. * @param __max_size Maximal number of elements to be contained. */ _RestrictedBoundedConcurrentQueue(_SequenceIndex __max_size) { _M_max_size = __max_size; _M_base = new _Tp[__max_size]; _M_borders = __encode2(0, 0); #pragma omp flush } /** @brief Destructor. Not to be called concurrent, of course. */ ~_RestrictedBoundedConcurrentQueue() { delete[] _M_base; } /** @brief Pushes one element into the queue at the front end. * Must not be called concurrently with pop_front(). */ void push_front(const _Tp& __t) { _CASable __former_borders = _M_borders; int __former_front, __former_back; __decode2(__former_borders, __former_front, __former_back); *(_M_base + __former_front % _M_max_size) = __t; #if _GLIBCXX_ASSERTIONS // Otherwise: front - back > _M_max_size eventually. _GLIBCXX_PARALLEL_ASSERT(((__former_front + 1) - __former_back) <= _M_max_size); #endif __fetch_and_add(&_M_borders, __encode2(1, 0)); } /** @brief Pops one element from the queue at the front end. * Must not be called concurrently with pop_front(). */ bool pop_front(_Tp& __t) { int __former_front, __former_back; #pragma omp flush __decode2(_M_borders, __former_front, __former_back); while (__former_front > __former_back) { // Chance. _CASable __former_borders = __encode2(__former_front, __former_back); _CASable __new_borders = __encode2(__former_front - 1, __former_back); if (__compare_and_swap(&_M_borders, __former_borders, __new_borders)) { __t = *(_M_base + (__former_front - 1) % _M_max_size); return true; } #pragma omp flush __decode2(_M_borders, __former_front, __former_back); } return false; } /** @brief Pops one element from the queue at the front end. * Must not be called concurrently with pop_front(). */ bool pop_back(_Tp& __t) //queue behavior { int __former_front, __former_back; #pragma omp flush __decode2(_M_borders, __former_front, __former_back); while (__former_front > __former_back) { // Chance. _CASable __former_borders = __encode2(__former_front, __former_back); _CASable __new_borders = __encode2(__former_front, __former_back + 1); if (__compare_and_swap(&_M_borders, __former_borders, __new_borders)) { __t = *(_M_base + __former_back % _M_max_size); return true; } #pragma omp flush __decode2(_M_borders, __former_front, __former_back); } return false; } }; } //namespace __gnu_parallel #undef _GLIBCXX_VOLATILE #endif /* _GLIBCXX_PARALLEL_QUEUE_H */
convolutiondepthwise_3x3_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // Copyright (C) 2019 BUG1989. 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 inline signed char float2int8(float v) { int int32 = round(v); if (int32 > 127) return 127; if (int32 < -128) return -128; return (signed char)int32; } static void convdw3x3s1_int8_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const signed char *kernel = _kernel; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); out.fill(0); const signed char *kernel0 = (const signed char *)kernel + p * 9; int *outptr = out; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr += sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const signed char *kernel = _kernel; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); out.fill(0); const signed char *kernel0 = (const signed char *)kernel + p * 9; int *outptr = out; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr += sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } static void convdw3x3s1_int8_dequant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_dequant, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const signed char *kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); float *outptr = out; const float bias0 = bias ? bias[p] : 0.f; const float scale_dequant = scales_dequant[p]; out.fill(bias0); const signed char *kernel0 = (const signed char *)kernel + p * 9; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr += (float)sum * scale_dequant; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_dequant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_dequant, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const signed char *kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); float *outptr = out; const float bias0 = bias ? bias[p] : 0.f; const float scale_dequant = scales_dequant[p]; out.fill(bias0); const signed char *kernel0 = (const signed char *)kernel + p * 9; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr += (float)sum * scale_dequant; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } static void convdw3x3s1_int8_requant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const signed char *kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); signed char *outptr = out; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; const signed char *kernel0 = (const signed char *)kernel + p * 9; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr = float2int8(((float)sum * scale_requant_in + bias0) * scale_requant_out); r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_int8_requant_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; //int h = bottom_blob.h; //int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2 * outw + w; const signed char *kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { Mat out = top_blob.channel(p); signed char *outptr = out; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; const signed char *kernel0 = (const signed char *)kernel + p * 9; const signed char *img0 = bottom_blob.channel(p); const signed char *r0 = img0; const signed char *r1 = img0 + w; const signed char *r2 = img0 + w * 2; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { int sum = 0; sum += (int)r0[0] * (int)kernel0[0]; sum += (int)r0[1] * (int)kernel0[1]; sum += (int)r0[2] * (int)kernel0[2]; sum += (int)r1[0] * (int)kernel0[3]; sum += (int)r1[1] * (int)kernel0[4]; sum += (int)r1[2] * (int)kernel0[5]; sum += (int)r2[0] * (int)kernel0[6]; sum += (int)r2[1] * (int)kernel0[7]; sum += (int)r2[2] * (int)kernel0[8]; *outptr = float2int8(((float)sum * scale_requant_in + bias0) * scale_requant_out); r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
GB_unaryop__minv_fp32_uint64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_fp32_uint64 // op(A') function: GB_tran__minv_fp32_uint64 // C type: float // A type: uint64_t // cast: float cij = (float) aij // unaryop: cij = (1.0F)/aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ float // 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 = (1.0F)/x ; // casting #define GB_CASTING(z, x) \ float z = (float) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_FP32 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp32_uint64 ( float *restrict Cx, const uint64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_fp32_uint64 ( 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
test.c
#include <omp.h> #include <stdio.h> #define N 1024 #define EXPLICIT_TARGET_TASK 0 #pragma omp requires unified_shared_memory int A[N]; int B[N]; int C[N]; int D[N]; int Z[N+1]; #if EXPLICIT_TARGET_TASK #define LOMP_TASK_DEP_40 1 #define LOMP_TARGET_40 1 #define LOMP_PROC_BIND_40 1 #define LOMP_OS_LINUX 1 #define LOMP_CANCEL_40 1 #include "/gsa/yktgsa-h1/00/eichen/new-tlomp/lomp/include/omp_interface.h" void _of1(lomp_Handle handle, char *fparg, char *sharg) { #pragma omp target nowait map(A) { int i; for(i=0; i<N; i++) A[i]++; } } void _of2(lomp_Handle handle, char *fparg, char *sharg) { #pragma omp target nowait map(A, B) { int i; for(i=0; i<N; i++) B[i] += A[i]; } } void _of3(lomp_Handle handle, char *fparg, char *sharg) { #pragma omp target nowait map(A, C) { int i; for(i=0; i<N; i++) C[i] += A[i]; } } void _of4(lomp_Handle handle, char *fparg, char *sharg) { #pragma omp target nowait map(A, B, C) { int i; for(i=0; i<N; i++) A[i] = B[i] + C[i]; } } #endif int main() { int i, errors; for(i=0; i<N; i++) { A[i] = i; B[i] = i+1; C[i] = i+2; D[i] = i+3; Z[i] = 1; } // set this to zero for fast computation, large number for bigger number Z[N] = 1024; #pragma omp target data map(A, B, C, D, Z) { #if EXPLICIT_TARGET_TASK lomp_Handle h = _lomp_GetHandle(); // 1 lomp_TaskDep_Public *taskDepArray1; void *fpagr1 = _lomp_Task_AllocateFirstPrivate_WithDeps(h, 0, 1, &taskDepArray1); // set dependences taskDepArray1[0].addr = &A[0]; taskDepArray1[0].status = LOMP_TASK_DEP_STATUS_OUT; // launch target task _lomp_TargetTask_Setup_WithDep(0, h, _of1, fpagr1, NULL, 0, 1, taskDepArray1, 0); // 2 lomp_TaskDep_Public *taskDepArray2; void *fpagr2 = _lomp_Task_AllocateFirstPrivate_WithDeps(h, 0, 2, &taskDepArray2); // set dependences taskDepArray2[0].addr = &A[0]; taskDepArray2[0].status = LOMP_TASK_DEP_STATUS_IN; taskDepArray2[1].addr = &B[0]; taskDepArray2[1].status = LOMP_TASK_DEP_STATUS_OUT; // launch target task _lomp_TargetTask_Setup_WithDep(0, h, _of2, fpagr2, NULL, 0, 2, taskDepArray2, 0); // 3 lomp_TaskDep_Public *taskDepArray3; void *fpagr3 = _lomp_Task_AllocateFirstPrivate_WithDeps(h, 0, 2, &taskDepArray3); // set dependences taskDepArray3[0].addr = &A[0]; taskDepArray3[0].status = LOMP_TASK_DEP_STATUS_IN; taskDepArray3[1].addr = &C[0]; taskDepArray3[1].status = LOMP_TASK_DEP_STATUS_OUT; // launch target task _lomp_TargetTask_Setup_WithDep(0, h, _of3, fpagr3, NULL, 0, 2, taskDepArray3, 0); // 4 lomp_TaskDep_Public *taskDepArray4; void *fpagr4 = _lomp_Task_AllocateFirstPrivate_WithDeps(h, 0, 2, &taskDepArray4); // set dependences taskDepArray4[0].addr = &B[0]; taskDepArray4[0].status = LOMP_TASK_DEP_STATUS_OUT; taskDepArray4[1].addr = &C[0]; taskDepArray4[1].status = LOMP_TASK_DEP_STATUS_OUT; // launch target task _lomp_TargetTask_Setup_WithDep(0, h, _of4, fpagr4, NULL, 0, 2, taskDepArray4, 0); #else // 1 #pragma omp target map(A, Z) depend(out: A[0]) nowait { int i, z; for(i=0; i<N; i++) A[i]++; for(z=0; z<Z[N]; z++) { for(i=0; i<N; i++) A[i] = A[i] / Z[i]; } } // 2 #pragma omp target map(A, B, Z) depend(in: A[0]) depend(inout: B[0]) nowait { int i, z; for(i=0; i<N; i++) B[i] += A[i]; for(z=0; z<Z[N]; z++) { for(i=0; i<N; i++) A[i] = A[i] / Z[i]; } } // 3 #pragma omp target map(A, C, Z) depend(in: A[0]) depend(inout: C[0]) nowait { int i, z; for(i=0; i<N; i++) C[i] += A[i]; for(z=0; z<Z[N]; z++) { for(i=0; i<N; i++) A[i] = A[i] / Z[i]; } } // 4 #pragma omp target map(A, B, C, Z) depend(inout: B[0], C[0]) nowait { int i, z; for(i=0; i<N; i++) A[i] = B[i]+ C[i]; for(z=0; z<Z[N]; z++) { for(i=0; i<N; i++) A[i] = A[i] / Z[i]; } } #endif #pragma omp taskwait } errors = 0; for(i=0; i<N; i++) { int a, b, c, d; a = i; b = i + 1; c = i + 2; d = i + 3; // a++; b += a; c += a; a = b + c; if (A[i] != a) printf("%d: got %d, expected %d; error %d\n", i, A[i], a, ++errors); if (errors>25) break; } printf("completed with %d errors\n", errors); return 1; }
oyranos_convert.c
/** @file oyranos_convert.c * * Oyranos is an open source Color Management System * * @par Copyright: * 2012-2018 (C) Kai-Uwe Behrmann * * @brief ICC conversion - on the command line * @internal * @author Kai-Uwe Behrmann <ku.b@gmx.de> * @par License: * new BSD <http://www.opensource.org/licenses/BSD-3-Clause> * @since 2012/02/19 * * The program uses ICC profiles to perform color transforms. * * cc -Wall -g oyranos_convert.c -o oyranos-icc `pkg-config --libs --cflags oyranos` -I../../ -I../build_11.4 -I ../../API_generated/ -I ../../oforms/ */ #include "oyConversion_s.h" #include "oyProfiles_s.h" #include "oyranos.h" #include "oyranos_debug.h" #include "oyranos_helper.h" #include "oyranos_helper_macros.h" #include "oyranos_internal.h" #include "oyranos_io.h" #include "oyranos_config.h" #include "oyranos_sentinel.h" #include "oyranos_string.h" #include "oyranos_version.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include "oyranos_forms.h" void* oyAllocFunc(size_t size) {return malloc (size);} void printfHelp (int argc OY_UNUSED, char** argv) { char * version = oyVersionString(1,0); char * id = oyVersionString(2,0); char * cfg_date = oyVersionString(3,0); char * devel_time = oyVersionString(4,0); fprintf( stderr, "\n"); fprintf( stderr, "oyranos-icc %s - the arguments and interface will change\n", _("is a ICC color conversion tool")); fprintf( stderr, " Oyranos v%s config: %s devel period: %s\n", oyNoEmptyName_m_(version), oyNoEmptyName_m_(cfg_date), oyNoEmptyName_m_(devel_time) ); if(id) fprintf( stderr, " Oyranos git id %s\n", oyNoEmptyName_m_(id) ); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Hint: search paths are influenced by the XDG_CONFIG_HOME shell variable.")); fprintf( stderr, "\n"); fprintf( stderr, "%s\n", _("Usage")); fprintf( stderr, " %s\n", _("Convert Image:")); fprintf( stderr, " %s -p %s [-o %s] [-n MODULE] -i %s\n", argv[0], _("ICC_FILE_NAME"),_("FILE_NAME"), _("FILE_NAME")); fprintf( stderr, " -i %s\t%s\n", _("FILE_NAME"), _("read from file")); fprintf( stderr, " --device-link %s\t%s\n", _("ICC_FILE_NAME"),_("Conversion")); fprintf( stderr, " -p %s\t%s\n", _("ICC_FILE_NAME"), _("Output Color Space")); fprintf( stderr, " -s %s\t%s\n", _("ICC_FILE_NAME"), _("Simulation/Proof Color Space")); fprintf( stderr, " -e %s\t%s\n", _("ICC_FILE_NAME"), _("Effect abtract Color Space")); fprintf( stderr, " -o %s\t%s\n", _("FILE_NAME"), _("write to file, currently only PPM and PNG formats")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Generate CLUT Image:")); fprintf( stderr, " %s -f clut -p %s [-i %s] [-o %s] [-n %s]\n", argv[0], _("ICC_FILE_NAME"), _("ICC_FILE_NAME"), _("FILE_NAME"), _("MODULE_NAME")); fprintf( stderr, " -f %s\t%s\n", _("FORMAT"), _("select format, currently only clut")); fprintf( stderr, " -i %s\t%s\n", _("ICC_FILE_NAME"), _("Input Color Space")); fprintf( stderr, " -p %s\t%s\n", _("ICC_FILE_NAME"), _("Output Color Space")); fprintf( stderr, " -s %s\t%s\n", _("ICC_FILE_NAME"), _("Simulation/Proof Color Space")); fprintf( stderr, " -e %s\t%s\n", _("ICC_FILE_NAME"), _("Effect abtract Color Space")); fprintf( stderr, " -o %s\t%s\n", _("FILE_NAME"), _("write to file, currently only PPM format")); fprintf( stderr, " %s\n", _("CLUT is a levels x levels*levels sized PPM, --levels defaults for clut to 64")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Generate Device Link Profile:")); fprintf( stderr, " %s -f icc -p %s -i %s [-o %s] [-n %s]\n", argv[0], _("ICC_FILE_NAME"), _("ICC_FILE_NAME"), _("ICC_FILE_NAME"), _("MODULE_NAME")); fprintf( stderr, " -f %s\t%s\n", _("FORMAT"), _("select format, currently only icc")); fprintf( stderr, " --uint8\t%s\n", _("select unsigned integer 8-bit precision data format")); fprintf( stderr, " --uint16\t%s\n", _("select unsigned integer 16-bit precision data format")); fprintf( stderr, " --half\t%s\n", _("select floating point 16-bit precision data format")); fprintf( stderr, " --float\t%s\n", _("select floating point 32-bit precision data format")); fprintf( stderr, " --double\t%s\n", _("select floating point 64-bit precision data format")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Extract ICC profile:")); fprintf( stderr, " %s -f icc [-o %s] [-n %s] -i %s\n", argv[0], _("ICC_FILE_NAME"), _("MODULE_NAME"), _("FILE_NAME")); fprintf( stderr, " -o %s\t%s\n", _("ICC_FILE_NAME"), _("write to file")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Generate Image:")); fprintf( stderr, " %s -f [hald|slice|lab] [-o %s] --levels 8\n", argv[0], _("FILE_NAME")); fprintf( stderr, " -o %s\t%s\n", _("FILE_NAME"), _("write to file")); fprintf( stderr, " --levels %s\t%s\n", _("NUMBER"), _("levels from 4-16 make sense")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("Print a help text:")); fprintf( stderr, " %s -h [-n %s] [-d]\n", argv[0], _("MODULE_NAME")); fprintf( stderr, "\n"); fprintf( stderr, " %s\n", _("General options:")); fprintf( stderr, " -v %s\n", _("verbose")); fprintf( stderr, " -n %s\t%s\n", _("MODULE_NAME"), _("module name")); fprintf( stderr, " -d %s\n", _("enable simple defaults")); fprintf( stderr, "\n"); fprintf( stderr, " %s:\n", _("Example")); fprintf( stderr, " %s:\n", _("Get ICC profile")); fprintf( stderr, " oyranos-icc -f icc -i image.png | iccexamin -g -i\n"); fprintf( stderr, "\n"); fprintf( stderr, " %s:\n", _("Convert image to ICC Color Space")); fprintf( stderr, " oyranos-icc -i image.png -n lcm2 -p Lab.icc -o image.ppm\n"); fprintf( stderr, "\n"); fprintf( stderr, " %s:\n", _("Convert image through ICC device link profile")); fprintf( stderr, " oyranos-icc -i image.png --device-link deviceLink.icc -o image.ppm\n"); fprintf( stderr, "\n"); fprintf( stderr, " %s:\n", _("Get Conversion")); fprintf( stderr, " oyranos-icc -f icc -i input.icc -n lcm2 -p sRGB.icc -o device_link.icc\n"); fprintf( stderr, "\n"); fprintf( stderr, " %s:\n", _("Create 3D CLUT")); fprintf( stderr, " oyranos-icc -f clut -i Lab.icc -n lcm2 -p sRGB.icc -o clut.ppm\n"); fprintf( stderr, "\n"); fprintf( stderr, "\n"); if(version) oyDeAllocateFunc_(version); if(id) oyDeAllocateFunc_(id); if(cfg_date) oyDeAllocateFunc_(cfg_date); if(devel_time) oyDeAllocateFunc_(devel_time); } int main( int argc , char** argv ) { int error = 0; char * format = 0; char * output = 0; char * input = 0; char * device_link = 0; char * node_name = 0; int help = 0; int verbose = 0; int icc_defaults_simple = 0; oyDATATYPE_e data_type = oyUINT16; char * output_profile = 0; char * simulation_profile = 0; char * effect_profile = 0; uint32_t icc_profile_flags = 0; oyProfiles_s * proofing = oyProfiles_New(0), * effects = oyProfiles_New(0); oyProfile_s * p = NULL; oyOptions_s * module_options = 0; int levels = 0; char ** other_args = 0; int other_args_n = 0; char * text = 0, * t = 0; oyOptions_s * opts = 0; oyImage_s * image = 0; #ifdef USE_GETTEXT setlocale(LC_ALL,""); #endif oyExportStart_(EXPORT_CHECK_NO); if(argc >= 2) { int pos = 1; unsigned i; char *wrong_arg = 0; DBG_PROG1_S("argc: %d\n", argc); while(pos < argc) { switch(argv[pos][0]) { case '-': for(i = 1; pos < argc && i < strlen(argv[pos]); ++i) switch (argv[pos][i]) { case 'd': icc_defaults_simple = 1; break; case 'f': OY_PARSE_STRING_ARG(format); break; case 'o': OY_PARSE_STRING_ARG(output); break; case 'p': OY_PARSE_STRING_ARG(output_profile); break; case 's': OY_PARSE_STRING_ARG(simulation_profile); p = oyProfile_FromName( simulation_profile, icc_profile_flags, 0 ); if(!p) wrong_arg = effect_profile; oyProfiles_MoveIn( proofing, &p, -1 ); break; case 'e': OY_PARSE_STRING_ARG(effect_profile); p = oyProfile_FromName( effect_profile, icc_profile_flags, 0 ); if(!p) wrong_arg = effect_profile; oyProfiles_MoveIn( effects, &p, -1 ); break; case 'i': OY_PARSE_STRING_ARG(input); break; case 'n': OY_PARSE_STRING_ARG(node_name); oyOptions_SetFromString( &module_options, OY_DEFAULT_CMM_CONTEXT, node_name, OY_CREATE_NEW ); icc_profile_flags = oyICCProfileSelectionFlagsFromOptions( OY_CMM_STD, "//" OY_TYPE_STD "/icc_color", module_options, 0 ); break; case 'v': if(verbose) oy_debug += 1; verbose = 1; break; case 'h': help = 1; break; case '-': if(OY_IS_ARG("help")) { help = 1; i=100; break; } else if(OY_IS_ARG("levels")) { OY_PARSE_INT_ARG2(levels, "levels"); break; } else if(OY_IS_ARG("output")) { OY_PARSE_STRING_ARG2(output, "output"); break; } else if(OY_IS_ARG("device-link")) { OY_PARSE_STRING_ARG2(device_link, "device-link"); break; } else if(OY_IS_ARG("uint8")) { data_type = oyUINT8; i=100; break; } else if(OY_IS_ARG("uint16")) { data_type = oyUINT16; i=100; break; } else if(OY_IS_ARG("half")) { data_type = oyHALF; i=100; break; } else if(OY_IS_ARG("float")) { data_type = oyFLOAT; i=100; break; } else if(OY_IS_ARG("double")) { data_type = oyDOUBLE; i=100; break; } else if(strcmp(&argv[pos][2],"verbose") == 0) { oy_debug += 1; i=100; break; } else if(argv[pos][2]) { STRING_ADD( t, &argv[pos][2] ); text = oyStrrchr_(t, '='); /* get the key only */ if(text) text[0] = 0; oyStringListAddStaticString( &other_args,&other_args_n, t, oyAllocateFunc_,oyDeAllocateFunc_ ); if(text) oyStringListAddStaticString( &other_args,&other_args_n, oyStrrchr_(&argv[pos][2], '=') + 1, oyAllocateFunc_,oyDeAllocateFunc_ ); else { if(argv[pos+1]) { oyStringListAddStaticString( &other_args, &other_args_n, argv[pos+1], oyAllocateFunc_,oyDeAllocateFunc_ ); ++pos; } else wrong_arg = argv[pos]; } if(t) oyDeAllocateFunc_( t ); t = 0; i=100; break; } else { wrong_arg = argv[pos]; } break; default: printfHelp(argc, argv); exit (0); break; } break; default: printfHelp(argc, argv); exit (0); break; } if( wrong_arg ) { fprintf(stderr, "%s %s\n", _("wrong argument to option:"), wrong_arg); printfHelp(argc, argv); exit(1); } ++pos; } } else { printfHelp(argc, argv); exit (0); } if(help) { printfHelp(argc, argv); if(node_name) { int r OY_UNUSED; char * t = 0; STRING_ADD( t, "oyranos-xforms-modules -n " ); STRING_ADD( t, node_name ); if(!icc_defaults_simple) STRING_ADD( t, " -f" ); if(verbose) STRING_ADD( t, " -v" ); STRING_ADD( t, " | oyranos-xforms" ); if(verbose) STRING_ADD( t, " -lh" ); if(oy_debug) fprintf(stderr, "%s\n", t); r = system(t); exit(0); } } if(verbose) fprintf( stderr, " Oyranos v%s\n", oyNoEmptyName_m_(oyVersionString(1,0))); #if 1 if(other_args) { const char * result_xml = 0; const char * opt_names = 0; oyFormsArgs_s * forms_args = oyFormsArgs_New( 0 ); const char * data = 0, * ct = 0; int i; oyOption_s * o = 0; forms_args->print = 0; /* TODO */ error = oyXFORMsRenderUi( text, oy_ui_cmd_line_handlers, forms_args ); result_xml = oyFormsArgs_ModelGet( forms_args ); if(result_xml) { opts = oyOptions_FromText( result_xml, 0,0 ); data = oyOptions_GetText( opts, oyNAME_NAME ); opt_names = oyOptions_GetText( opts, oyNAME_DESCRIPTION ); for( i = 0; i < other_args_n; i += 2 ) { /* check for wrong args */ if(opt_names && strstr( opt_names, other_args[i] ) == NULL) { fprintf(stderr, "Unknown option: %s", other_args[i]); printfHelp( argc, argv ); exit( 1 ); } else { o = oyOptions_Find( opts, other_args[i], oyNAME_PATTERN ); if(i + 1 < other_args_n) { ct = oyOption_GetText( o, oyNAME_NICK ); if(oy_debug) fprintf( stderr, "%s => ", ct?ct:"---" ); ct = 0; oyOption_SetFromString( o, other_args[i + 1], 0 ); data = oyOption_GetText( o, oyNAME_NICK ); if(oy_debug) fprintf( stderr, "%s\n", data?oyStrchr_(data, ':') + 1:"" ); data = 0; } else { fprintf( stderr, "%s: --%s argument missed\n", _("Option"), other_args[i] ); exit( 1 ); } oyOption_Release( &o ); } } } else /* handle the options as if they are commandline switches */ for( i = 0; i+1 < other_args_n; i += 2 ) { oyOptions_SetFromString( &module_options, other_args[i], other_args[i+1], OY_CREATE_NEW ); } } #endif icc_profile_flags = oyICCProfileSelectionFlagsFromOptions( OY_CMM_STD, "//" OY_TYPE_STD "/icc_color", module_options, 0 ); if(output_profile || device_link) { uint32_t flags = 0; oyPixel_t pixel_layout; oyConversion_s * cc; if(!output) WARNc_S("No output file name provided"); if(!icc_defaults_simple) flags |= oyOPTIONATTRIBUTE_ADVANCED; if(oyProfiles_Count(effects)) error = oyOptions_MoveInStruct( &module_options, OY_PROFILES_EFFECT, (oyStruct_s**) &effects, OY_CREATE_NEW ); if(oyProfiles_Count(proofing)) error = oyOptions_MoveInStruct( &module_options, OY_PROFILES_SIMULATION, (oyStruct_s**) &proofing, OY_CREATE_NEW ); if(format && strcmp(format,"clut") == 0) { int width = levels, size, l,a,b,j; uint16_t * buf = 0; uint16_t in[3]; char comment[80]; if(!width) width = 64; size = width*width; if(!output) WARNc_S("No output file name provided"); buf = calloc(sizeof(uint16_t), size*width*3); #pragma omp parallel for private(in,a,b,j) for(l = 0; l < width; ++l) { in[0] = floor((double) l / (width - 1) * 65535.0 + 0.5); for(a = 0; a < width; ++a) { in[1] = floor((double) a / (width - 1) * 65535.0 + 0.5); for(b = 0; b < width; ++b) { in[2] = floor((double) b / (width - 1) * 65535.0 + 0.5); for(j = 0; j < 3; ++j) /* BGR */ buf[b*size*3+a*+width*3+l*3+j] = in[j]; } } } if(input) { p = oyProfile_FromName( input, icc_profile_flags, 0 ); if(!p) WARNc1_S("Could not open profile: %s", input); error = 1; } else p = oyProfile_FromStd( oyASSUMED_WEB, icc_profile_flags, 0 ); image = oyImage_Create( width,width*width, buf, OY_TYPE_123_16, p, 0 ); oyProfile_Release( &p ); sprintf( comment, "clut with %d levels", width ); pixel_layout = oyImage_GetPixelLayout( image, oyLAYOUT ); data_type = oyToDataType_m(pixel_layout); p = oyProfile_FromName(output_profile, icc_profile_flags, 0); cc = oyConversion_CreateFromImage ( image, module_options, p, data_type, flags, 0 ); error = oyConversion_RunPixels( cc, 0 ); image = oyConversion_GetImage( cc, OY_OUTPUT ); error = oyImage_WritePPM( image, output, comment); oyImage_Release( &image ); } else if(format && strcmp(format,"icc") == 0) { double buf[24]; oyImage_s * in; oyFilterGraph_s * graph = NULL; oyFilterNode_s * icc = NULL; oyBlob_s * blob = NULL; int error = 0; int n=0; const char* node_name = "///icc_color"; if(input) { p = oyProfile_FromName( input, icc_profile_flags, 0 ); if(!p) { WARNc1_S("Could not open profile: %s", input); error = 1; } } else p = oyProfile_FromStd( oyASSUMED_WEB, icc_profile_flags, 0 ); n = oyProfile_GetChannelsCount(p); pixel_layout = oyChannels_m(n) | oyDataType_m(data_type); in = oyImage_Create( 2, 2, buf, pixel_layout, p, 0 ); oyProfile_Release( &p ); p = oyProfile_FromName(output_profile, icc_profile_flags, 0); cc = oyConversion_CreateFromImage ( in, module_options, p, data_type, 0, 0 ); oyProfile_Release( &p ); memset( buf, 0, sizeof(double)*24); if(cc) graph = oyConversion_GetGraph( cc ); if(graph) icc = oyFilterGraph_GetNode( graph, -1, node_name, NULL ); if(icc) { blob = oyFilterNode_ToBlob( icc, 0 ); if(blob && oyBlob_GetSize( blob )) { size_t size = oyBlob_GetSize( blob); char * data = oyBlob_GetPointer( blob ); if(output) { error = oyWriteMemToFile_ ( output, data, size ); if(error) { WARNc_S("Could not write to profile"); } } else { fwrite( data, sizeof(char), size, stdout ); } } oyBlob_Release( &blob ); oyFilterNode_Release( &icc ); } else WARNc1_S("Could not open node: %s", node_name); oyFilterGraph_Release( &graph ); } else { char * comment = 0; error = oyImage_FromFile( input, icc_profile_flags, &image, NULL ); pixel_layout = oyImage_GetPixelLayout( image,oyLAYOUT ); if(device_link) { p = oyProfile_FromName(device_link, icc_profile_flags, 0); if(!p) { WARNc1_S("Could not open profile: %s", device_link); error = 1; } else { const char * t; char * dln = NULL; oyProfile_s * dl = NULL; oyProfileTag_s * psid = oyProfile_GetTagById( p, icSigProfileSequenceIdentifierTag ); int32_t texts_n = 0; char ** texts = oyProfileTag_GetText( psid, &texts_n, 0,0,0,0); int count = (texts_n-1)/5; oyProfileTag_Release( &psid ); oyStringListRelease_( &texts, texts_n, oyDeAllocateFunc_ ); oyImage_SetCritical( image, 0, p, 0, -1,-1 ); t = oyProfile_GetFileName( p, count - 1 ); if(t) { output_profile = dln = strdup( t ); dl = oyProfile_FromName(t, icc_profile_flags, 0); } if(dl && strcmp(t,dln) != 0) { oyProfile_Release( &p ); WARNc2_S("Set output profile %s from %s", t,dln); p = dl; } else if(!output_profile) { fprintf( stderr, "No output profile found in: %s - use the -p option", t ); printfHelp( argc, argv ); exit(1); } else oyProfile_Release( &p ); } } if(!p) p = oyProfile_FromName(output_profile, icc_profile_flags, 0); if(!p) { WARNc1_S("Could not open output profile: %s", output_profile); error = 1; } data_type = oyToDataType_m(pixel_layout); cc = oyConversion_CreateFromImage ( image, module_options, p, data_type, flags, 0 ); oyImage_Release( &image ); error = oyConversion_RunPixels( cc, 0 ); image = oyConversion_GetImage( cc, OY_OUTPUT ); oyConversion_Release( &cc ); STRING_ADD( comment, "source image was " ); STRING_ADD( comment, input ); oyOptions_SetFromString( &opts, "//" OY_TYPE_STD "/file_write/comment", comment, OY_CREATE_NEW ); error = oyImage_ToFile( image, output, opts ); oyImage_Release( &image ); oyFree_m_( comment ); } } else if(format && strcmp(format,"icc") == 0) { oyProfile_s * prof = 0; size_t size = 0; char * data = 0; fprintf(stderr, "%s\n", input); error = oyImage_FromFile( input, icc_profile_flags, &image, NULL ); prof = oyImage_GetProfile( image ); data = oyProfile_GetMem( prof, &size, 0, oyAllocateFunc_); if(size) { if(output) { error = oyWriteMemToFile_ ( output, data, size ); if(error) { WARNc_S("Could not write to profile"); } } else { fwrite( data, sizeof(char), size, stdout ); } oyDeAllocateFunc_(data); size = 0; data = 0; } else WARNc_S("No profile found"); oyImage_Release( &image ); oyProfile_Release( &prof ); } else if(format && (strcmp(format,"hald") == 0 || strcmp(format,"slice") == 0 || strcmp(format,"lab") == 0)) { int width = levels, size = width*width, l,a,b,j; uint16_t * buf = 0; uint16_t in[3]; char comment[80]; if(!output) WARNc_S("No output file name provided"); p = oyProfile_FromStd( oyEDITING_LAB, icc_profile_flags, 0 ); if(strcmp(format,"hald") == 0) { if(!width) width = 8; buf = calloc(sizeof(uint16_t), size*width*size*width*3); #pragma omp parallel for private(in,a,b,j) for(l = 0; l < size; ++l) { in[0] = floor((double) l / (size - 1) * 65535.0 + 0.5); for(a = 0; a < size; ++a) { in[1] = floor((double) a / (size - 1) * 65535.0 + 0.5); for(b = 0; b < size; ++b) { in[2] = floor((double) b / (size - 1) * 65535.0 + 0.5); for(j = 0; j < 3; ++j) buf[l*size*size*3+b*size*3+a*3+j] = in[j]; } } } image = oyImage_Create( size*width, size*width, buf, OY_TYPE_123_16, p, 0 ); sprintf( comment, "CIE*Lab Hald with %d levels", width ); } else if(strcmp(format,"lab") == 0) { if(!width) width = 64; buf = calloc(sizeof(uint16_t), size*width*3); #pragma omp parallel for private(in,a,b,j) for(l = 0; l < width; ++l) { in[0] = floor((double) l / (width - 1) * 65535.0 + 0.5); for(a = 0; a < width; ++a) { in[1] = floor((double) a / (width - 1) * 65535.0 + 0.5); for(b = 0; b < width; ++b) { in[2] = floor((double) b / (width - 1) * 65535.0 + 0.5); for(j = 0; j < 3; ++j) buf[a*size*3+b*+width*3+l*3+j] = in[j]; } } } image = oyImage_Create( width,width*width, buf, OY_TYPE_123_16, p, 0 ); sprintf( comment, "CIE*Lab LUT with %d levels", width ); } else if(strcmp(format,"slice") == 0) { if(!width) width = 17; buf = calloc(sizeof(uint16_t), size*width*3); #pragma omp parallel for private(in,a,b,j) for(l = 0; l < width; ++l) { in[1] = floor((double) l / (width - 1) * 65535.0 + 0.5); for(a = 0; a < width; ++a) { in[0] = floor((double) a / (width - 1) * 65535.0 + 0.5); for(b = 0; b < width; ++b) { in[2] = floor((double) b / (width - 1) * 65535.0 + 0.5); for(j = 0; j < 3; ++j) buf[a*size*3+b*+width*3+l*3+j] = in[j]; } } } image = oyImage_Create( width,width*width, buf, OY_TYPE_123_16, p, 0 ); sprintf( comment, "CIE*Lab slice with %d levels", width ); } else WARNc1_S("format is not supported %s", format); error = oyImage_WritePPM( image, output, comment); if(error) { WARNc_S("Could not write to file"); } } /* format conversion */ else if(input && output) { char * comment = NULL; STRING_ADD( comment, "source image was " ); STRING_ADD( comment, input ); oyOptions_SetFromString( &opts, "//" OY_TYPE_STD "/file_write/comment", comment, OY_CREATE_NEW ); oyFree_m_( comment ); error = oyImage_FromFile( input, icc_profile_flags, &image, NULL ); error = oyImage_ToFile( image, output, opts ); oyImage_Release( &image ); } else { printfHelp(argc, argv); exit (0); } oyProfile_Release( &p ); oyProfiles_Release( &effects ); oyProfiles_Release( &proofing ); oyOptions_Release( &opts ); oyFinish_( FINISH_IGNORE_I18N | FINISH_IGNORE_CACHES ); return error; }
data.h
/*! * Copyright (c) 2015 by Contributors * \file data.h * \brief The input data structure of xgboost. * \author Tianqi Chen */ #ifndef XGBOOST_DATA_H_ #define XGBOOST_DATA_H_ #include <dmlc/base.h> #include <dmlc/data.h> #include <dmlc/serializer.h> #include <xgboost/base.h> #include <xgboost/span.h> #include <xgboost/host_device_vector.h> #include <memory> #include <numeric> #include <algorithm> #include <string> #include <utility> #include <vector> namespace xgboost { // forward declare dmatrix. class DMatrix; /*! \brief data type accepted by xgboost interface */ enum class DataType : uint8_t { kFloat32 = 1, kDouble = 2, kUInt32 = 3, kUInt64 = 4, kStr = 5 }; enum class FeatureType : uint8_t { kNumerical }; /*! * \brief Meta information about dataset, always sit in memory. */ class MetaInfo { public: /*! \brief number of data fields in MetaInfo */ static constexpr uint64_t kNumField = 11; /*! \brief number of rows in the data */ uint64_t num_row_{0}; // NOLINT /*! \brief number of columns in the data */ uint64_t num_col_{0}; // NOLINT /*! \brief number of nonzero entries in the data */ uint64_t num_nonzero_{0}; // NOLINT /*! \brief label of each instance */ HostDeviceVector<bst_float> labels_; // NOLINT /*! * \brief the index of begin and end of a group * needed when the learning task is ranking. */ std::vector<bst_group_t> group_ptr_; // NOLINT /*! \brief weights of each instance, optional */ HostDeviceVector<bst_float> weights_; // NOLINT /*! * \brief initialized margins, * if specified, xgboost will start from this init margin * can be used to specify initial prediction to boost from. */ HostDeviceVector<bst_float> base_margin_; // NOLINT /*! * \brief lower bound of the label, to be used for survival analysis (censored regression) */ HostDeviceVector<bst_float> labels_lower_bound_; // NOLINT /*! * \brief upper bound of the label, to be used for survival analysis (censored regression) */ HostDeviceVector<bst_float> labels_upper_bound_; // NOLINT /*! * \brief Name of type for each feature provided by users. Eg. "int"/"float"/"i"/"q" */ std::vector<std::string> feature_type_names; /*! * \brief Name for each feature. */ std::vector<std::string> feature_names; /* * \brief Type of each feature. Automatically set when feature_type_names is specifed. */ HostDeviceVector<FeatureType> feature_types; /* * \brief Weight of each feature, used to define the probability of each feature being * selected when using column sampling. */ HostDeviceVector<float> feature_weigths; /*! \brief default constructor */ MetaInfo() = default; MetaInfo(MetaInfo&& that) = default; MetaInfo& operator=(MetaInfo&& that) = default; MetaInfo& operator=(MetaInfo const& that) = delete; /*! * \brief Validate all metainfo. */ void Validate(int32_t device) const; MetaInfo Slice(common::Span<int32_t const> ridxs) const; /*! * \brief Get weight of each instances. * \param i Instance index. * \return The weight. */ inline bst_float GetWeight(size_t i) const { return weights_.Size() != 0 ? weights_.HostVector()[i] : 1.0f; } /*! \brief get sorted indexes (argsort) of labels by absolute value (used by cox loss) */ inline const std::vector<size_t>& LabelAbsSort() const { if (label_order_cache_.size() == labels_.Size()) { return label_order_cache_; } label_order_cache_.resize(labels_.Size()); std::iota(label_order_cache_.begin(), label_order_cache_.end(), 0); const auto& l = labels_.HostVector(); XGBOOST_PARALLEL_SORT(label_order_cache_.begin(), label_order_cache_.end(), [&l](size_t i1, size_t i2) {return std::abs(l[i1]) < std::abs(l[i2]);}); return label_order_cache_; } /*! \brief clear all the information */ void Clear(); /*! * \brief Load the Meta info from binary stream. * \param fi The input stream */ void LoadBinary(dmlc::Stream* fi); /*! * \brief Save the Meta info to binary stream * \param fo The output stream. */ void SaveBinary(dmlc::Stream* fo) const; /*! * \brief Set information in the meta info. * \param key The key of the information. * \param dptr The data pointer of the source array. * \param dtype The type of the source data. * \param num Number of elements in the source array. */ void SetInfo(const char* key, const void* dptr, DataType dtype, size_t num); /*! * \brief Set information in the meta info with array interface. * \param key The key of the information. * \param interface_str String representation of json format array interface. * * [ column_0, column_1, ... column_n ] * * Right now only 1 column is permitted. */ void SetInfo(const char* key, std::string const& interface_str); void GetInfo(char const* key, bst_ulong* out_len, DataType dtype, const void** out_dptr) const; void SetFeatureInfo(const char *key, const char **info, const bst_ulong size); void GetFeatureInfo(const char *field, std::vector<std::string>* out_str_vecs) const; /* * \brief Extend with other MetaInfo. * * \param that The other MetaInfo object. * * \param accumulate_rows Whether rows need to be accumulated in this function. If * client code knows number of rows in advance, set this parameter to false. */ void Extend(MetaInfo const& that, bool accumulate_rows); private: /*! \brief argsort of labels */ mutable std::vector<size_t> label_order_cache_; }; /*! \brief Element from a sparse vector */ struct Entry { /*! \brief feature index */ bst_feature_t index; /*! \brief feature value */ bst_float fvalue; /*! \brief default constructor */ Entry() = default; /*! * \brief constructor with index and value * \param index The feature or row index. * \param fvalue The feature value. */ XGBOOST_DEVICE Entry(bst_feature_t index, bst_float fvalue) : index(index), fvalue(fvalue) {} /*! \brief reversely compare feature values */ inline static bool CmpValue(const Entry& a, const Entry& b) { return a.fvalue < b.fvalue; } inline bool operator==(const Entry& other) const { return (this->index == other.index && this->fvalue == other.fvalue); } }; /*! * \brief Parameters for constructing batches. */ struct BatchParam { /*! \brief The GPU device to use. */ int gpu_id; /*! \brief Maximum number of bins per feature for histograms. */ int max_bin{0}; /*! \brief Page size for external memory mode. */ size_t gpu_page_size; BatchParam() = default; BatchParam(int32_t device, int32_t max_bin, size_t gpu_page_size = 0) : gpu_id{device}, max_bin{max_bin}, gpu_page_size{gpu_page_size} {} inline bool operator!=(const BatchParam& other) const { return gpu_id != other.gpu_id || max_bin != other.max_bin || gpu_page_size != other.gpu_page_size; } }; struct HostSparsePageView { using Inst = common::Span<Entry const>; common::Span<bst_row_t const> offset; common::Span<Entry const> data; Inst operator[](size_t i) const { auto size = *(offset.data() + i + 1) - *(offset.data() + i); return {data.data() + *(offset.data() + i), static_cast<Inst::index_type>(size)}; } size_t Size() const { return offset.size() == 0 ? 0 : offset.size() - 1; } }; /*! * \brief In-memory storage unit of sparse batch, stored in CSR format. */ class SparsePage { public: // Offset for each row. HostDeviceVector<bst_row_t> offset; /*! \brief the data of the segments */ HostDeviceVector<Entry> data; size_t base_rowid{}; /*! \brief an instance of sparse vector in the batch */ using Inst = common::Span<Entry const>; /*! \brief get i-th row from the batch */ inline Inst operator[](size_t i) const { const auto& data_vec = data.HostVector(); const auto& offset_vec = offset.HostVector(); size_t size = offset_vec[i + 1] - offset_vec[i]; return {data_vec.data() + offset_vec[i], static_cast<Inst::index_type>(size)}; } HostSparsePageView GetView() const { return {offset.ConstHostSpan(), data.ConstHostSpan()}; } /*! \brief constructor */ SparsePage() { this->Clear(); } /*! \return Number of instances in the page. */ inline size_t Size() const { return offset.Size() == 0 ? 0 : offset.Size() - 1; } /*! \return estimation of memory cost of this page */ inline size_t MemCostBytes() const { return offset.Size() * sizeof(size_t) + data.Size() * sizeof(Entry); } /*! \brief clear the page */ inline void Clear() { base_rowid = 0; auto& offset_vec = offset.HostVector(); offset_vec.clear(); offset_vec.push_back(0); data.HostVector().clear(); } /*! \brief Set the base row id for this page. */ inline void SetBaseRowId(size_t row_id) { base_rowid = row_id; } SparsePage GetTranspose(int num_columns) const; void SortRows() { auto ncol = static_cast<bst_omp_uint>(this->Size()); #pragma omp parallel for default(none) shared(ncol) schedule(dynamic, 1) for (bst_omp_uint i = 0; i < ncol; ++i) { if (this->offset.HostVector()[i] < this->offset.HostVector()[i + 1]) { std::sort( this->data.HostVector().begin() + this->offset.HostVector()[i], this->data.HostVector().begin() + this->offset.HostVector()[i + 1], Entry::CmpValue); } } } /*! * \brief Push row block into the page. * \param batch the row batch. */ void Push(const dmlc::RowBlock<uint32_t>& batch); /** * \brief Pushes external data batch onto this page * * \tparam AdapterBatchT * \param batch * \param missing * \param nthread * * \return The maximum number of columns encountered in this input batch. Useful when pushing many adapter batches to work out the total number of columns. */ template <typename AdapterBatchT> uint64_t Push(const AdapterBatchT& batch, float missing, int nthread); /*! * \brief Push a sparse page * \param batch the row page */ void Push(const SparsePage &batch); /*! * \brief Push a SparsePage stored in CSC format * \param batch The row batch to be pushed */ void PushCSC(const SparsePage& batch); }; class CSCPage: public SparsePage { public: CSCPage() : SparsePage() {} explicit CSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class SortedCSCPage : public SparsePage { public: SortedCSCPage() : SparsePage() {} explicit SortedCSCPage(SparsePage page) : SparsePage(std::move(page)) {} }; class EllpackPageImpl; /*! * \brief A page stored in ELLPACK format. * * This class uses the PImpl idiom (https://en.cppreference.com/w/cpp/language/pimpl) to avoid * including CUDA-specific implementation details in the header. */ class EllpackPage { public: /*! * \brief Default constructor. * * This is used in the external memory case. An empty ELLPACK page is constructed with its content * set later by the reader. */ EllpackPage(); /*! * \brief Constructor from an existing DMatrix. * * This is used in the in-memory case. The ELLPACK page is constructed from an existing DMatrix * in CSR format. */ explicit EllpackPage(DMatrix* dmat, const BatchParam& param); /*! \brief Destructor. */ ~EllpackPage(); EllpackPage(EllpackPage&& that); /*! \return Number of instances in the page. */ size_t Size() const; /*! \brief Set the base row id for this page. */ void SetBaseRowId(size_t row_id); const EllpackPageImpl* Impl() const { return impl_.get(); } EllpackPageImpl* Impl() { return impl_.get(); } private: std::unique_ptr<EllpackPageImpl> impl_; }; template<typename T> class BatchIteratorImpl { public: virtual ~BatchIteratorImpl() = default; virtual T& operator*() = 0; virtual const T& operator*() const = 0; virtual void operator++() = 0; virtual bool AtEnd() const = 0; }; template<typename T> class BatchIterator { public: using iterator_category = std::forward_iterator_tag; // NOLINT explicit BatchIterator(BatchIteratorImpl<T>* impl) { impl_.reset(impl); } void operator++() { CHECK(impl_ != nullptr); ++(*impl_); } T& operator*() { CHECK(impl_ != nullptr); return *(*impl_); } const T& operator*() const { CHECK(impl_ != nullptr); return *(*impl_); } bool operator!=(const BatchIterator& rhs) const { CHECK(impl_ != nullptr); return !impl_->AtEnd(); } bool AtEnd() const { CHECK(impl_ != nullptr); return impl_->AtEnd(); } private: std::shared_ptr<BatchIteratorImpl<T>> impl_; }; template<typename T> class BatchSet { public: explicit BatchSet(BatchIterator<T> begin_iter) : begin_iter_(std::move(begin_iter)) {} BatchIterator<T> begin() { return begin_iter_; } // NOLINT BatchIterator<T> end() { return BatchIterator<T>(nullptr); } // NOLINT private: BatchIterator<T> begin_iter_; }; struct XGBAPIThreadLocalEntry; /*! * \brief Internal data structured used by XGBoost during training. */ class DMatrix { public: /*! \brief default constructor */ DMatrix() = default; /*! \brief meta information of the dataset */ virtual MetaInfo& Info() = 0; virtual void SetInfo(const char *key, const void *dptr, DataType dtype, size_t num) { this->Info().SetInfo(key, dptr, dtype, num); } virtual void SetInfo(const char* key, std::string const& interface_str) { this->Info().SetInfo(key, interface_str); } /*! \brief meta information of the dataset */ virtual const MetaInfo& Info() const = 0; /*! \brief Get thread local memory for returning data from DMatrix. */ XGBAPIThreadLocalEntry& GetThreadLocal() const; /** * \brief Gets batches. Use range based for loop over BatchSet to access individual batches. */ template<typename T> BatchSet<T> GetBatches(const BatchParam& param = {}); template <typename T> bool PageExists() const; // the following are column meta data, should be able to answer them fast. /*! \return Whether the data columns single column block. */ virtual bool SingleColBlock() const = 0; /*! \brief virtual destructor */ virtual ~DMatrix(); /*! \brief Whether the matrix is dense. */ bool IsDense() const { return Info().num_nonzero_ == Info().num_row_ * Info().num_col_; } /*! * \brief Load DMatrix from URI. * \param uri The URI of input. * \param silent Whether print information during loading. * \param load_row_split Flag to read in part of rows, divided among the workers in distributed mode. * \param file_format The format type of the file, used for dmlc::Parser::Create. * By default "auto" will be able to load in both local binary file. * \param page_size Page size for external memory. * \return The created DMatrix. */ static DMatrix* Load(const std::string& uri, bool silent, bool load_row_split, const std::string& file_format = "auto", size_t page_size = kPageSize); /** * \brief Creates a new DMatrix from an external data adapter. * * \tparam AdapterT Type of the adapter. * \param [in,out] adapter View onto an external data. * \param missing Values to count as missing. * \param nthread Number of threads for construction. * \param cache_prefix (Optional) The cache prefix for external memory. * \param page_size (Optional) Size of the page. * * \return a Created DMatrix. */ template <typename AdapterT> static DMatrix* Create(AdapterT* adapter, float missing, int nthread, const std::string& cache_prefix = "", size_t page_size = kPageSize); /** * \brief Create a new Quantile based DMatrix used for histogram based algorithm. * * \tparam DataIterHandle External iterator type, defined in C API. * \tparam DMatrixHandle DMatrix handle, defined in C API. * \tparam DataIterResetCallback Callback for reset, prototype defined in C API. * \tparam XGDMatrixCallbackNext Callback for next, prototype defined in C API. * * \param iter External data iterator * \param proxy A hanlde to ProxyDMatrix * \param reset Callback for reset * \param next Callback for next * \param missing Value that should be treated as missing. * \param nthread number of threads used for initialization. * \param max_bin Maximum number of bins. * * \return A created quantile based DMatrix. */ template <typename DataIterHandle, typename DMatrixHandle, typename DataIterResetCallback, typename XGDMatrixCallbackNext> static DMatrix *Create(DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback *reset, XGDMatrixCallbackNext *next, float missing, int nthread, int max_bin); virtual DMatrix *Slice(common::Span<int32_t const> ridxs) = 0; /*! \brief page size 32 MB */ static const size_t kPageSize = 32UL << 20UL; protected: virtual BatchSet<SparsePage> GetRowBatches() = 0; virtual BatchSet<CSCPage> GetColumnBatches() = 0; virtual BatchSet<SortedCSCPage> GetSortedColumnBatches() = 0; virtual BatchSet<EllpackPage> GetEllpackBatches(const BatchParam& param) = 0; virtual bool EllpackExists() const = 0; virtual bool SparsePageExists() const = 0; }; template<> inline BatchSet<SparsePage> DMatrix::GetBatches(const BatchParam&) { return GetRowBatches(); } template<> inline bool DMatrix::PageExists<EllpackPage>() const { return this->EllpackExists(); } template<> inline bool DMatrix::PageExists<SparsePage>() const { return this->SparsePageExists(); } template<> inline BatchSet<CSCPage> DMatrix::GetBatches(const BatchParam&) { return GetColumnBatches(); } template<> inline BatchSet<SortedCSCPage> DMatrix::GetBatches(const BatchParam&) { return GetSortedColumnBatches(); } template<> inline BatchSet<EllpackPage> DMatrix::GetBatches(const BatchParam& param) { return GetEllpackBatches(param); } } // namespace xgboost namespace dmlc { DMLC_DECLARE_TRAITS(is_pod, xgboost::Entry, true); namespace serializer { template <> struct Handler<xgboost::Entry> { inline static void Write(Stream* strm, const xgboost::Entry& data) { strm->Write(data.index); strm->Write(data.fvalue); } inline static bool Read(Stream* strm, xgboost::Entry* data) { return strm->Read(&data->index) && strm->Read(&data->fvalue); } }; } // namespace serializer } // namespace dmlc #endif // XGBOOST_DATA_H_
GrB_Type_wait.c
//------------------------------------------------------------------------------ // GrB_Type_wait: wait for a user-defined GrB_Type to complete //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // In SuiteSparse:GraphBLAS, a user-defined GrB_Type has no pending operations // to wait for. All this method does is verify that the type is properly // initialized, and then it does an OpenMP flush. #include "GB.h" GrB_Info GrB_Type_wait // no work, just check if the GrB_Type is valid ( GrB_Type *type ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- #pragma omp flush GB_WHERE1 ("GrB_Type_wait (&type)") ; GB_RETURN_IF_NULL (type) ; GB_RETURN_IF_NULL_OR_FAULTY (*type) ; //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- #pragma omp flush return (GrB_SUCCESS) ; }
edgebased_levelset.h
/* * File: edgebased_levelset.h * Author: rrossi * * Created on July 31, 2009, 10:51 AM */ /* ============================================================================== KratosPFEMApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: antonia $ // Date: $Date: 2009-01-14 16:24:38 $ // Revision: $Revision: 1.11 $ // // #if !defined(KRATOS_EDGEBASED_LEVELSET_FLUID_SOLVER_H_INCLUDED) #define KRATOS_EDGEBASED_LEVELSET_FLUID_SOLVER_H_INCLUDED //#define SPLIT_OSS // #define SYMM_PRESS // System includes #include <string> #include <iostream> #include <algorithm> // #include <omp.h> // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/deprecated_variables.h" #include "includes/node.h" #include "includes/cfd_variables.h" //#include "geometries/geometry.h" #include "utilities/geometry_utilities.h" #include "incompressible_fluid_application.h" namespace Kratos { template<unsigned int TDim, class MatrixContainer, class TSparseSpace, class TLinearSolver> class EdgeBasedLevelSet { public: //name for the self defined structure typedef EdgesStructureType<TDim> CSR_Tuple; typedef vector<CSR_Tuple> EdgesVectorType; //name for row start and column index vectors typedef vector<unsigned int> IndicesVectorType; //defining matrix type for test calculations typedef vector< array_1d<double, TDim> > CalcVectorType; //defining type for local storage of nodal values typedef vector<double> ValuesVectorType; //defining types for matrix operations typedef typename TSparseSpace::MatrixType TSystemMatrixType; typedef typename TSparseSpace::VectorType TSystemVectorType; typedef std::size_t SizeType; //constructor and destructor EdgeBasedLevelSet(MatrixContainer& mr_matrix_container, ModelPart& mr_model_part, const double viscosity, const double density, const Vector body_force, bool use_mass_correction, double edge_detection_angle, double stabdt_pressure_factor, double stabdt_convection_factor, double tau2_factor, bool assume_constant_dp ) : mr_matrix_container(mr_matrix_container), mr_model_part(mr_model_part), mstabdt_pressure_factor(stabdt_pressure_factor), mstabdt_convection_factor(stabdt_convection_factor), medge_detection_angle(edge_detection_angle), mtau2_factor(tau2_factor), massume_constant_dp(assume_constant_dp) { for (ModelPart::NodesContainerType::iterator it=mr_model_part.NodesBegin(); it!=mr_model_part.NodesEnd(); it++) it->FastGetSolutionStepValue (VISCOSITY) = viscosity; mMolecularViscosity = viscosity; for(unsigned int i = 0; i<TDim; i++) mBodyForce[i] = body_force[i]; mRho = density; mdelta_t_avg = 1000.0; max_dt = 1.0; muse_mass_correction = use_mass_correction; mshock_coeff = 0.7; mWallLawIsActive = false; }; ~EdgeBasedLevelSet() { }; //*********************************** //function to initialize fluid solver void Initialize( ) { KRATOS_TRY //get number of nodes unsigned int n_nodes = mr_model_part.Nodes().size(); unsigned int n_edges = mr_matrix_container.GetNumberEdges(); //size data vectors mViscosity.resize (n_nodes); mr_matrix_container.SetToZero (mViscosity); mWork.resize(n_nodes); mr_matrix_container.SetToZero(mWork); mvel_n.resize(n_nodes); mr_matrix_container.SetToZero(mvel_n); mvel_n1.resize(n_nodes); mr_matrix_container.SetToZero(mvel_n1); mPn.resize(n_nodes); mr_matrix_container.SetToZero(mPn); mPn1.resize(n_nodes); mr_matrix_container.SetToZero(mPn1); mHmin.resize(n_nodes); mr_matrix_container.SetToZero(mHmin); mHavg.resize(n_nodes); mr_matrix_container.SetToZero(mHavg); mNodalFlag.resize(n_nodes); mr_matrix_container.SetToZero(mNodalFlag); mdistances.resize(n_nodes); mr_matrix_container.SetToZero(mdistances); mTauPressure.resize(n_nodes); mr_matrix_container.SetToZero(mTauPressure); mTauConvection.resize(n_nodes); mr_matrix_container.SetToZero(mTauConvection); mTau2.resize(n_nodes); mr_matrix_container.SetToZero(mTau2); mPi.resize(n_nodes); mr_matrix_container.SetToZero(mPi); mXi.resize(n_nodes); mr_matrix_container.SetToZero(mXi); mx.resize(n_nodes); mr_matrix_container.SetToZero(mx); mEdgeDimensions.resize(n_edges); mr_matrix_container.SetToZero(mEdgeDimensions); //convection variables mBeta.resize(n_nodes); mr_matrix_container.SetToZero(mBeta); mPiConvection.resize(n_nodes); mr_matrix_container.SetToZero(mPiConvection); mphi_n.resize(n_nodes); mr_matrix_container.SetToZero(mphi_n); mphi_n1.resize(n_nodes); mr_matrix_container.SetToZero(mphi_n1); mEps.resize(n_nodes); mr_matrix_container.SetToZero(mEps); //mD.resize(n_nodes); mr_matrix_container.SetToZero(mD); mA.resize(n_nodes); mr_matrix_container.SetToZero(mA); mB.resize(n_nodes); mr_matrix_container.SetToZero(mB); mStrVel.resize(n_nodes); mr_matrix_container.SetToZero(mStrVel); mdiv_error.resize(n_nodes); mr_matrix_container.SetToZero(mdiv_error); mdiag_stiffness.resize (n_nodes); mr_matrix_container.SetToZero (mdiag_stiffness); mis_slip.resize (n_nodes); // ValuesVectorType external_pressure; // external_pressure.resize(n_nodes); //read velocity and pressure data from Kratos mr_matrix_container.FillScalarFromDatabase (VISCOSITY, mViscosity, mr_model_part.Nodes() ); mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(PRESSURE, mPn1, mr_model_part.Nodes()); mr_matrix_container.FillOldScalarFromDatabase(PRESSURE, mPn, mr_model_part.Nodes()); mr_matrix_container.FillOldVectorFromDatabase(VELOCITY, mvel_n, mr_model_part.Nodes()); mr_matrix_container.FillCoordinatesFromDatabase(mx, mr_model_part.Nodes()); //set flag for first time step mFirstStep = true; //loop to categorize boundary nodes std::vector< unsigned int> tempFixedVelocities; std::vector< array_1d<double,TDim> > tempFixedVelocitiesValues; std::vector< unsigned int> tempPressureOutletList; for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { int index = inode->FastGetSolutionStepValue(AUX_INDEX); if (inode->IsFixed(VELOCITY_X)) //note that the variables can be either all fixed or no one fixed { if (inode->IsFixed(VELOCITY_Y) == false || inode->IsFixed(VELOCITY_Z) == false) { std::cout << "error found on the fixity of node " << inode->Id() << std::endl; KRATOS_THROW_ERROR(std::logic_error, "velocities can be either all fixed or none fixed", "") } tempFixedVelocities.push_back(index); tempFixedVelocitiesValues.push_back(mvel_n1[index]); } if (inode->IsFixed(PRESSURE)) { tempPressureOutletList.push_back(index); // mPressureOutlet.push_back(external_pressure[index]); } } mFixedVelocities.resize(tempFixedVelocities.size(),false); mFixedVelocitiesValues.resize(tempFixedVelocitiesValues.size(),false); mPressureOutletList.resize(tempPressureOutletList.size(),false); #pragma omp parallel for for(int i=0; i< static_cast<int>(tempFixedVelocities.size()); i++) { mFixedVelocities[i] = tempFixedVelocities[i]; mFixedVelocitiesValues[i] = tempFixedVelocitiesValues[i]; } #pragma omp parallel for for(int i=0; i< static_cast<int>(tempPressureOutletList.size()); i++) { mPressureOutletList[i] = tempPressureOutletList[i]; } //compute slip normals and fill SlipList CalculateNormals(mr_model_part.Conditions()); mr_matrix_container.WriteVectorToDatabase(NORMAL, mSlipNormal, mr_model_part.Nodes()); if(TDim == 3) DetectEdges3D(mr_model_part.Conditions()); //determine number of edges and entries //// not implemented in ublas yet !!! //unsigned int n_nonzero_entries = 2 * n_edges + n_nodes; //allocate memory for variables mL.resize(n_nodes, n_nodes, false); int number_of_threads= OpenMPUtils::GetNumThreads(); std::vector<int> row_partition(number_of_threads); OpenMPUtils::DivideInPartitions(n_nodes,number_of_threads,row_partition); for (int k = 0; k < number_of_threads; k++) { #pragma omp parallel if (OpenMPUtils::ThisThread() == k) { for (int i_node = static_cast<int> (row_partition[k]); i_node < static_cast<int> (row_partition[k + 1]); i_node++) { //loop over all nodes // for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { //flag for considering diagonal matrix elements bool flag = 0; //loop over all neighbours for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; //define matrix structure row by row (the order does matter!) if ((static_cast<int>(j_neighbour) > i_node) && (flag == 0)) { //add diagonal/nodal contribution mL.push_back(i_node, i_node, 0.0); flag = 1; } //add non-diagonal/edge contribution mL.push_back(i_node, j_neighbour, 0.0); } //if diagonal element is the last non-zero element of the row if (flag == 0) mL.push_back(i_node, i_node, 0.0); } } } //compute minimum length of the surrounding edges CalculateEdgeLengths(mr_model_part.Nodes()); //set the pressure projection to the body force value array_1d<double,3> temp = ZeroVector(3); for(unsigned int i = 0 ; i < TDim; i++) temp[i]= mRho * mBodyForce[i]; for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { array_1d<double, 3> & press_proj = inode->FastGetSolutionStepValue(PRESS_PROJ); for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) press_proj[l_comp] = temp[l_comp]; } KRATOS_CATCH("") } void SetShockCapturingCoefficient(double coeff) { mshock_coeff = coeff; } //*************************************** //function to set adequate time step size double ComputeTimeStep(const double CFLNumber, const double MaxDt) { KRATOS_TRY //save the maximum time step max_dt = MaxDt; //local variable for time step size double delta_t = 1e10;//max_dt; mdelta_t_avg = 1e10;//max_dt; //getting value of current velocity and of viscosity mr_matrix_container.FillScalarFromDatabase (VISCOSITY, mViscosity, mr_model_part.Nodes() ); mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(POROSITY, mEps, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(LIN_DARCY_COEF, mA, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(NONLIN_DARCY_COEF, mB, mr_model_part.Nodes()); mr_matrix_container.FillVectorFromDatabase(STRUCTURE_VELOCITY, mStrVel, mr_model_part.Nodes()); //******************* //loop over all nodes unsigned int n_nodes = mvel_n1.size(); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { const array_1d<double, TDim>& v_i = mvel_n1[i_node]; const double havg_i = mHavg[i_node]; const double hmin_i = mHmin[i_node]; const double eps_i = mEps[i_node]; //const double d_i = mD[i_node]; const double nu = mViscosity[i_node]; // const double lindarcy_i = mA[i_node]; // const double nonlindarcy_i = mB[i_node]; // const array_1d<double, TDim>& str_v_i = mStrVel[i_node]; // array_1d<double, TDim> rel_vel_i; // rel_vel_i[0] = v_i[0] - str_v_i[0]; // rel_vel_i[1] = v_i[1] - str_v_i[1]; // rel_vel_i[2] = v_i[2] - str_v_i[2]; // double rel_vel_norm = norm_2(rel_vel_i); // double vel_norm = norm_2(v_i); double vel_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { vel_norm += v_i[l_comp]*v_i[l_comp]; } vel_norm = sqrt(vel_norm); // double porosity_coefficient = ComputePorosityCoefficient( rel_vel_norm, eps_i, lindarcy_i, nonlindarcy_i); vel_norm /= eps_i; //use CFL condition to compute time step size double delta_t_i = CFLNumber * 1.0 / (2.0 * vel_norm /hmin_i + 4.0 * nu / (hmin_i * hmin_i)/*+ porosity_coefficient*/); double delta_t_i_avg = 1.0 / (2.0 * vel_norm /havg_i + 4.0 * nu / (havg_i * havg_i) /*+ porosity_coefficient*/); // double delta_t_i = 1.0 / ( vel_norm /hmin_i + nu / (hmin_i * hmin_i)/*+ porosity_coefficient*/); // double delta_t_i_avg = 1.0 / ( vel_norm /havg_i + nu / (havg_i * havg_i) /*+ porosity_coefficient*/); //considering the most restrictive case of neighbor's velocities with similar direction but opposite sense. //loop over all neighbours for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const array_1d<double, TDim>& v_j = mvel_n1[j_neighbour]; double v_diff_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { double temp = v_i[l_comp] - v_j[l_comp]; v_diff_norm += temp*temp; } v_diff_norm = sqrt(v_diff_norm); v_diff_norm /= eps_i; double delta_t_j = CFLNumber * 1.0 / (2.0 * v_diff_norm /hmin_i + 4.0 * nu / (hmin_i * hmin_i)); // double delta_t_j = 1.0 / ( v_diff_norm /hmin_i + nu / (hmin_i * hmin_i)); if (delta_t_j < delta_t_i) delta_t_i = delta_t_j; } //choose the overall minimum of delta_t_i if (delta_t_i < delta_t) delta_t = delta_t_i; if(delta_t_i_avg < mdelta_t_avg) mdelta_t_avg = delta_t_i_avg; } //******************* //perform MPI syncronization of the dt (minimum should be kept) return delta_t; KRATOS_CATCH("") } void ApplySmagorinsky (double MolecularViscosity, double Cs) { if (Cs != 0) { if (TDim == 3) ApplySmagorinsky3D (MolecularViscosity, Cs); else ApplySmagorinsky2D (MolecularViscosity, Cs); } } void UpdateFixedVelocityValues() { KRATOS_TRY //read velocity and pressure data from Kratos ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, rNodes); int fixed_size = mFixedVelocities.size(); #pragma omp parallel for firstprivate(fixed_size) for (int i_velocity = 0; i_velocity < fixed_size; i_velocity++) { unsigned int i_node = mFixedVelocities[i_velocity]; array_1d<double, TDim>& u_i_fix = mFixedVelocitiesValues[i_velocity]; const array_1d<double, TDim>& u_i = mvel_n1[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) u_i_fix[comp] = u_i[comp]; } KRATOS_CATCH(""); } //********************************************************************************** //function to solve fluid equations - fractional step 1: compute fractional momentum void SolveStep1() { KRATOS_TRY //PREREQUISITES //variables for node based data handling ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //storage of nodal values in local variables CalcVectorType rhs; rhs.resize(n_nodes); //read velocity and pressure data from Kratos mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, rNodes); mr_matrix_container.FillOldVectorFromDatabase(VELOCITY, mvel_n, rNodes); mr_matrix_container.FillScalarFromDatabase (VISCOSITY, mViscosity, rNodes); mr_matrix_container.FillScalarFromDatabase(PRESSURE, mPn1, rNodes); mr_matrix_container.FillOldScalarFromDatabase(PRESSURE, mPn, rNodes); mr_matrix_container.FillScalarFromDatabase(DISTANCE, mdistances, mr_model_part.Nodes()); //mr_matrix_container.FillScalarFromDatabase(DIAMETER, mD, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(POROSITY, mEps, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(LIN_DARCY_COEF, mA, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(NONLIN_DARCY_COEF, mB, mr_model_part.Nodes()); mr_matrix_container.FillVectorFromDatabase(STRUCTURE_VELOCITY, mStrVel, rNodes); //read time step size from Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double delta_t = CurrentProcessInfo[DELTA_TIME]; //compute intrinsic time double time_inv_avg = 1.0/mdelta_t_avg; double stabdt_pressure_factor = mstabdt_pressure_factor; double stabdt_convection_factor = mstabdt_convection_factor; double tau2_factor = mtau2_factor; #pragma omp parallel for firstprivate(time_inv_avg,stabdt_pressure_factor,stabdt_convection_factor,tau2_factor) for (int i_node = 0; i_node < n_nodes; i_node++) { double& h_avg_i = mHavg[i_node]; array_1d<double, TDim>& a_i = mvel_n1[i_node]; const double nu_i = mViscosity[i_node]; const double eps_i = mEps[i_node]; const double lindarcy_i = mA[i_node]; const double nonlindarcy_i = mB[i_node]; double vel_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { vel_norm += a_i[l_comp]*a_i[l_comp]; } vel_norm = sqrt(vel_norm); const array_1d<double, TDim>& str_v_i = mStrVel[i_node]; array_1d<double, TDim> rel_vel_i; double rel_vel_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { rel_vel_i[l_comp] = a_i[l_comp] - str_v_i[l_comp]; rel_vel_norm += rel_vel_i[l_comp]*rel_vel_i[l_comp]; } rel_vel_norm = sqrt(rel_vel_norm); double porosity_coefficient = ComputePorosityCoefficient(rel_vel_norm, eps_i, lindarcy_i, nonlindarcy_i); vel_norm /= eps_i; // double tau = 1.0 / (2.0 * vel_norm / h_avg_i + time_inv_avg + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); // double denom = (2.0 * vel_norm / h_avg_i + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); // double tau = 0.0; // if(denom > max_dt_inv_coeff) // tau = max_dt_coeff; // else // tau = 1.0/denom; // double tau = 1.0 / (2.0 * vel_norm / h_avg_i + max_dt_inv + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); double tau = 1.0 / (2.0 * vel_norm / h_avg_i + stabdt_pressure_factor*time_inv_avg + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); // double tau = 1.0 / (2.0 * vel_norm / h_avg_i + 0.01*time_inv_avg + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); double tau_conv = 1.0 / (2.0 * vel_norm / h_avg_i + stabdt_convection_factor*time_inv_avg + (4.0*nu_i) / (h_avg_i * h_avg_i) + porosity_coefficient); mTauPressure[i_node] = tau; mTauConvection[i_node] = tau_conv; mTau2[i_node] = (nu_i + h_avg_i*vel_norm*0.5)*tau2_factor; // mTauPressure[i_node] = 1.0 / (2.0 * vel_norm / mHavg[i_node] + (4.0*nu_i) / (mHavg[i_node] * mHavg[i_node])); // mTauConvection[i_node] = 1.0 / (2.0 * vel_norm / h_i + time_inv + (4.0*nu_i) / (h_i * h_i)); //// mTauPressure[i_node] = 1.0 / (2.0 * vel_norm / h_i + 0.01 * time_inv + 4.0 * nu_i / (h_i * h_i)); //// // mTauPressure[i_node] = delta_t; //// mTauConvection[i_node] = 1.0 / (2.0 * vel_norm / h_i + 0.01 * time_inv + 4.0 * nu_i / (h_i * h_i)); // if (mTauPressure[i_node] < delta_t) // mTauPressure[i_node] = delta_t; // else if(mTauPressure[i_node] > 100.0*delta_t) // mTauPressure[i_node] = 100.0*delta_t; } //// //the tau is set to 1/dt on the corner nodes //// //apply conditions on corners //// int corner_size = mcorner_nodes.size(); //// for (int i = 0; i < corner_size; i++) //// { //// int i_node = mcorner_nodes[i]; //// mTauPressure[i_node] = mdelta_t_avg; //// mTauConvection[i_node] = mdelta_t_avg; //// } // //laplacian smoothing on the taus // //note here that we use mTau2 as a temporary vector // LaplacianSmooth(mTauConvection, mTau2); // LaplacianSmooth(mTauPressure, mTau2); // #pragma omp parallel for // for (int i_node = 0; i_node < n_nodes; i_node++) // mTau2[i_node] = 0.0; // mr_matrix_container.AssignVectorToVector(mTauPressure, mTauConvection); //calculating the convective projection #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, TDim>& pi_i = mPi[i_node]; //****************** //setting to zero for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] = 0.0; array_1d<double, TDim> a_i = mvel_n1[i_node]; const array_1d<double, TDim>& U_i = mvel_n1[i_node]; // const double& p_i = mPn1[i_node]; const double& eps_i = mEps[i_node]; /*convective velocity == fluid velocity (not darcy velocity)*/ a_i /= eps_i; /*convective front velocity == fluid velocity - structural velocity*/ // // ****************************************rel_vel_modifications_b // const array_1d<double, TDim>& str_v_i = mStrVel[i_node]; // for(unsigned int comp = 0; comp < TDim; comp++) // {a_i[comp] -= str_v_i[comp];} // // ****************************************rel_vel_modifications_e //const double& p_i = pressure[i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; array_1d<double, TDim> a_j = mvel_n1[j_neighbour]; const array_1d<double, TDim>& U_j = mvel_n1[j_neighbour]; const double& eps_j = mEps[j_neighbour]; /*convective velocity == fluid velocity (not darcy velocity)*/ a_j /= eps_j; /*convective front velocity == fluid velocity - structural velocity*/ // // ****************************************rel_vel_modifications_b // const array_1d<double, TDim>& str_v_j = mStrVel[j_neighbour]; // for(unsigned int comp = 0; comp < TDim; comp++) // {a_j[comp] -= str_v_j[comp];} // // ****************************************rel_vel_modifications_e CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_ConvectiveContribution(pi_i, a_i, U_i, a_j, U_j); // edge_ij.Add_grad_p(pi_i, p_i, p_j); } const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] *= m_inv; } //std::cout << "substep " << substep+1 << " of " << n_substeps << std::endl; mr_matrix_container.AssignVectorToVector (mvel_n, mWork); //mWork = mvel_n //first step of Runge Kutta mr_matrix_container.AssignVectorToVector (mvel_n, mvel_n1); //mvel_n1 = mvel_n mr_matrix_container.SetToZero (rhs); CalculateRHS (mvel_n1, mPn, mvel_n1, rhs,mdiag_stiffness); Add_Effective_Inverse_Multiply (mWork, mWork, delta_t / 6.0, mr_matrix_container.GetLumpedMass(),mdiag_stiffness,rhs); Add_Effective_Inverse_Multiply (mvel_n1, mvel_n, 0.5 * delta_t, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); ApplyVelocityBC (mvel_n1); //second step mr_matrix_container.SetToZero (rhs); CalculateRHS (mvel_n1, mPn, mvel_n1, rhs,mdiag_stiffness); Add_Effective_Inverse_Multiply (mWork, mWork, delta_t / 3.0, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); Add_Effective_Inverse_Multiply (mvel_n1, mvel_n, 0.5 * delta_t, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); ApplyVelocityBC (mvel_n1); //third step mr_matrix_container.SetToZero (rhs); CalculateRHS (mvel_n1, mPn, mvel_n1, rhs,mdiag_stiffness); Add_Effective_Inverse_Multiply (mWork, mWork, delta_t / 3.0, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); Add_Effective_Inverse_Multiply (mvel_n1, mvel_n, delta_t, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); ApplyVelocityBC (mvel_n1); //fourth step mr_matrix_container.SetToZero (rhs); CalculateRHS (mvel_n1, mPn, mvel_n1, rhs,mdiag_stiffness); Add_Effective_Inverse_Multiply (mWork, mWork, delta_t / 6.0, mr_matrix_container.GetLumpedMass(),mdiag_stiffness, rhs); //compute right-hand side mr_matrix_container.AssignVectorToVector (mWork, mvel_n1); ApplyVelocityBC (mvel_n1); //prepare for next step //mr_matrix_container.AssignVectorToVector (mvel_n1, mvel_n);//??????????????????????????????????????? KRATOS_CATCH("") } //********************************************************************* //function to calculate right-hand side of fractional momentum equation void CalculateRHS( const CalcVectorType& vel, const ValuesVectorType& pressure, const CalcVectorType& convective_velocity, CalcVectorType& rhs, ValuesVectorType& diag_stiffness) { KRATOS_TRY int n_nodes = vel.size(); //perform MPI syncronization //calculating the RHS array_1d<double, TDim> stab_low; array_1d<double, TDim> stab_high; double inverse_rho = 1.0 / mRho; #pragma omp parallel for private(stab_low,stab_high) for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; if (dist <= 0.0) //node is inside domain ---- if outside do nothing { const double nu_i = mViscosity[i_node]; const double nu_j = nu_i; array_1d<double, TDim>& rhs_i = rhs[i_node]; const array_1d<double, TDim>& f_i = mBodyForce; array_1d<double, TDim> a_i = convective_velocity[i_node]; // const double& beta_i = mBeta[i_node]; const array_1d<double, TDim>& U_i = vel[i_node]; const array_1d<double, TDim>& pi_i = mPi[i_node]; const double& p_i = pressure[i_node]; const double& eps_i = mEps[i_node]; // //const double& d_i = mD[i_node]; const double lindarcy_i = mA[i_node]; const double nonlindarcy_i = mB[i_node]; const array_1d<double, TDim>& str_v_i = mStrVel[i_node]; array_1d<double, TDim> rel_vel_i; double rel_vel_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { rel_vel_i[l_comp] = U_i[l_comp] - str_v_i[l_comp]; rel_vel_norm += rel_vel_i[l_comp]*rel_vel_i[l_comp]; } rel_vel_norm = sqrt(rel_vel_norm); //const double& tau2_i = mTau2[i_node]; double edge_tau = mTauConvection[i_node]; /*convective velocity == fluid velocity (not darcy velocity)*/ a_i /= eps_i; /*convective front velocity == fluid velocity - structural velocity*/ // // ****************************************rel_vel_modifications_b // for(unsigned int comp = 0; comp < TDim; comp++) // {a_i[comp] -= str_v_i[comp];} // // ****************************************rel_vel_modifications_e // //double& h_i = mHmin[i_node]; //initializing with the external forces (e.g. gravity) double& m_i = mr_matrix_container.GetLumpedMass()[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) rhs_i[comp] = m_i * eps_i * f_i[comp] ; //applying the effect of the porosity // double porosity_coefficient = ComputePorosityCoefficient(mViscosity,norm_2(U_i),eps_i, d_i); // double porosity_coefficient = ComputePorosityCoefficient( norm_2(U_i), eps_i, lindarcy_i, nonlindarcy_i); double porosity_coefficient = ComputePorosityCoefficient( rel_vel_norm, eps_i, lindarcy_i, nonlindarcy_i); diag_stiffness[i_node]= m_i * porosity_coefficient; // /**************************************************rel_vel_modifications_b*/ for (unsigned int comp = 0; comp < TDim; comp++) { // rhs_i[comp] -= m_i * porosity_coefficient * U_i[comp]; rhs_i[comp] += m_i * porosity_coefficient * str_v_i[comp]; } // /*************************************************rel_vel_modifications_e*/ //std::cout << i_node << "rhs =" << rhs_i << "after adding body force" << std::endl; //convective term for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; array_1d<double, TDim> a_j = convective_velocity[j_neighbour]; const array_1d<double, TDim>& U_j = vel[j_neighbour]; const array_1d<double, TDim>& pi_j = mPi[j_neighbour]; const double& p_j = pressure[j_neighbour]; const double& eps_j = mEps[j_neighbour]; // const double& beta_j = mBeta[j_neighbour]; /*convective velocity == fluid velocity (not darcy velocity)*/ a_j /= eps_j; /*convective front velocity == fluid velocity - structural velocity*/ // ****************************************rel_vel_modifications_b // const array_1d<double, TDim>& str_v_j = mStrVel[j_neighbour]; // for(unsigned int comp = 0; comp < TDim; comp++) // {a_j[comp] -= str_v_j[comp];} // ****************************************/*rel_vel_modifications*/_e CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Sub_ConvectiveContribution(rhs_i, a_i, U_i, a_j, U_j); // std::cout << i_node << "rhs =" << rhs_i << "after convective contrib" << std::endl; //take care! we miss including a B.C. for the external pressure // edge_ij.Add_Gp(rhs_i,p_i*inverse_rho,p_j*inverse_rho); edge_ij.Sub_grad_p(rhs_i, p_i*inverse_rho*eps_i, p_j * inverse_rho*eps_i); // edge_ij.Add_grad_p(rhs_i, p_i*inverse_rho, p_j * inverse_rho); // std::cout << i_node << "rhs =" << rhs_i << "after Gp" << std::endl; edge_ij.Sub_ViscousContribution(rhs_i, U_i, nu_i, U_j, nu_j); // std::cout << i_node << "rhs =" << rhs_i << "after viscous" << std::endl; //add stabilization edge_ij.CalculateConvectionStabilization_LOW(stab_low, a_i, U_i, a_j, U_j); // edge_ij.CalculateConvectionStabilization_LOW(stab_low, a_i, U_i,p_i, a_j, U_j,p_j); edge_ij.CalculateConvectionStabilization_HIGH(stab_high, a_i, pi_i, a_j, pi_j); // double beta = 1.0; // double beta = beta_i; // if(beta_j > beta) // beta = beta_j; // beta = 1.0; // edge_ij.Sub_StabContribution(rhs_i, edge_tau*beta, 1.0, stab_low, stab_high); // edge_ij.Sub_StabContribution(rhs_i, edge_tau, (1.0-beta), stab_low, stab_high); edge_ij.Sub_StabContribution(rhs_i, edge_tau, 1.0, stab_low, stab_high); // std::cout << i_node << "rhs =" << rhs_i << "after stab" << std::endl; //add tau2 term // boost::numeric::ublas::bounded_matrix<double,TDim,TDim>& LL = edge_ij.LaplacianIJ; // for (unsigned int k_comp = 0; k_comp < TDim; k_comp++) // { // double aaa = 0.0; // for (unsigned int m_comp = 0; m_comp < TDim; m_comp++) // aaa += LL(k_comp,m_comp) * (U_j[m_comp] - U_i[m_comp]); // rhs_i[k_comp] -= tau2_i*aaa; // } } // std::cout << i_node << "rhs =" << rhs_i << std::endl; } } //apply wall resistance if (mWallLawIsActive == true) ComputeWallResistance (vel,diag_stiffness); ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); mr_matrix_container.WriteVectorToDatabase(VELOCITY, mvel_n1, rNodes); KRATOS_CATCH("") } //************************************************************************* //function to solve fluid equations - fractional step 2: calculate pressure void SolveStep2(typename TLinearSolver::Pointer pLinearSolver) { KRATOS_TRY typedef Node < 3 > PointType; typedef PointerVector<PointType > PointVector; typedef PointVector::iterator PointIterator; //reset is visited flag for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->GetValue(IS_VISITED) = 0.0; } //Re-generate a container with LAYER 0 and LAYER 1 after convection of the free surface std::vector< PointVector > layers(2); //detect the nodes inside the fluid surface LAYER_0 for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { if (inode->FastGetSolutionStepValue(DISTANCE) < 0.0) //candidates are only the ones inside the fluid domain { GlobalPointersVector< Node < 3 > >& neighb_nodes = inode->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->FastGetSolutionStepValue(DISTANCE) >= 0.0) //add the node as free surface if one of its neighb is outside { if (inode->GetValue(IS_VISITED) == 0.0) { layers[0].push_back(*(inode.base())); inode->GetValue(IS_VISITED) = 1.0; } } } } else inode->FastGetSolutionStepValue(PRESSURE) = 0.0; } //fill layer 1 by neighbour relationships for (PointIterator iii = (layers[0]).begin(); iii != (layers[0]).end(); iii++) { GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator jjj = neighb_nodes.begin(); jjj != neighb_nodes.end(); jjj++) //destination = origin1 + value * Minv*origin { if (jjj->FastGetSolutionStepValue(DISTANCE) >= 0 && jjj->GetValue(IS_VISITED) == 0.0) { layers[1].push_back(Node < 3 > ::Pointer(*(jjj.base()))); jjj->GetValue(IS_VISITED) = 2.0; } } } /* for (PointIterator iii = layers[il].begin(); iii != layers[il].end(); iii++) { // std::cout << iii->Id() << " " << std::endl; const array_1d<double, 3 > & coords_top = iii->Coordinates(); //extrapolate the average velocity noalias(aux) = ZeroVector(3); noalias(aux_proj) = ZeroVector(3); double avg_number = 0.0; double pavg = 0.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->GetValue(IS_VISITED) < (il + 1) && i->GetValue(IS_VISITED) != 0.0) {*/ //on the first layer outside the pressure is set to a value such that on the free surface the pressure is approx 0 for (PointIterator iii = layers[1].begin(); iii != layers[1].end(); iii++) { //get the node unsigned int i_node = iii->FastGetSolutionStepValue(AUX_INDEX); array_1d<double, TDim> grad_d; for (unsigned int comp = 0; comp < TDim; comp++) grad_d[comp] = 0.0; double dist_i = mdistances[i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& dist_j = mdistances[j_neighbour]; //projection of pressure gradients CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_grad_p(grad_d, dist_i, dist_j); } const double& m_inv = mr_matrix_container.GetInvertedMass()[i_node]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) grad_d[l_comp] *= m_inv; double norm_grad = norm_2(grad_d); if(norm_grad < 100.0) { grad_d /= norm_grad; //this is the direction of the gradient of the distances grad_d *= dist_i; //this is the vector with the distance of node_i from the closest point on the free surface //array_1d<double, TDim> press_grad; double pestimate = 0.0; const array_1d<double, 3> & r_press_proj = iii->FastGetSolutionStepValue(PRESS_PROJ); for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pestimate += r_press_proj[l_comp]*grad_d[l_comp]; // press_grad[l_comp]= r_press_proj[l_comp]; iii->FastGetSolutionStepValue(PRESSURE) = pestimate; } else { std::cout << "attention gradient of distance much greater than 1 on node:" << i_node <<std::endl; double avg_number = 0.0; double pavg = 0.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->GetValue(IS_VISITED) == 1.0) { pavg += i->FastGetSolutionStepValue(PRESSURE); avg_number += 1.0; } } if(avg_number == 0) KRATOS_THROW_ERROR(std::logic_error,"can not happen that the extrapolation node has no neighbours",""); iii->FastGetSolutionStepValue(PRESSURE) = pavg/avg_number; } } //if a node is very close to the free surface (relatively to the element size) fix the pressure on it // for(ModelPart::NodesContainerType::iterator iii = mr_model_part.NodesBegin(); iii!=mr_model_part.NodesEnd(); iii++) // { // unsigned int i_node = iii->FastGetSolutionStepValue(AUX_INDEX); // // double dist = mdistances[i_node]; // if(dist > 0.0 && dist < 0.01*mHavg[i_node]) // iii->FastGetSolutionStepValue(PRESSURE) = 0.0; // // } //PREREQUISITES //allocate memory for variables ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //unknown and right-hand side vector TSystemVectorType dp, rhs; dp.resize(n_nodes,false); rhs.resize(n_nodes,false); array_1d<double, TDim> dU_i, dU_j, work_array; //read time step size from Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double delta_t = CurrentProcessInfo[DELTA_TIME]; #ifdef _OPENMP // double time_inv = 0.0; //1.0/delta_t; //read the pressure projection from the database #endif mr_matrix_container.FillOldScalarFromDatabase(PRESSURE, mPn, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(PRESSURE, mPn1, mr_model_part.Nodes()); mr_matrix_container.FillVectorFromDatabase(PRESS_PROJ, mXi, rNodes); mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, rNodes); //for (int i_node = 0; i_node < n_nodes; i_node++) // std::cout << mvel_n1[i_node] << std::endl; //loop over all nodes // double rho_inv = 1.0 / mRho; #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { double& rhs_i = rhs[i_node]; rhs_i = 0.0; const double& p_i = mPn1[i_node]; const double& p_old_i = mPn[i_node]; const array_1d<double, TDim>& U_i_curr = mvel_n1[i_node]; // const double& eps_i = mEps[i_node]; array_1d<double, TDim>& xi_i = mXi[i_node]; double l_ii = 0.0; // double div_i = 0.0; //loop over all neighbours for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& p_j = mPn1[j_neighbour]; const double& p_old_j = mPn[j_neighbour]; const array_1d<double, TDim>& U_j_curr = mvel_n1[j_neighbour]; const array_1d<double, TDim>& xi_j = mXi[j_neighbour]; // const double& eps_j = mEps[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; #ifdef SYMM_PRESS double edge_tau = 0.25*(mTauPressure[i_node] + mTauPressure[j_neighbour]); #else double edge_tau = 0.5*mTauPressure[i_node]; #endif // double edge_tau = CalculateEdgeTau(time_inv,h_i,a_i,h_j,a_j); // if(edge_tau < delta_t) edge_tau=delta_t; //compute laplacian operator double sum_l_ikjk; edge_ij.CalculateScalarLaplacian(sum_l_ikjk); // double sum_l_ikjk_onlystab = sum_l_ikjk * (edge_tau); double sum_l_ikjk_onlydt = sum_l_ikjk * (delta_t); sum_l_ikjk *= (delta_t + edge_tau); //assemble right-hand side //pressure contribution // rhs_i -= sum_l_ikjk_onlystab * (p_j - p_i); rhs_i -= sum_l_ikjk * (p_j - p_i); rhs_i += sum_l_ikjk_onlydt * (p_old_j - p_old_i); //calculating the divergence of the fract vel // edge_ij.Sub_D_v(div_i, U_i_curr*mRho*eps_i, U_j_curr * mRho*eps_j); edge_ij.Sub_D_v(rhs_i, U_i_curr*mRho, U_j_curr * mRho); // edge_ij.Sub_D_v(rhs_i,a_i*rho_i,a_j*rho_i); //high order stabilizing term double temp = 0.0; // edge_ij.Add_div_v(temp,mTauPressure[i_node]*xi_i,mTauPressure[j_neighbour]*xi_j); edge_ij.Add_div_v(temp, xi_i, xi_j); rhs_i += edge_tau * temp; //assemble laplacian matrix mL(i_node, j_neighbour) = sum_l_ikjk; l_ii -= sum_l_ikjk; } // //area correction to prevent mass loss // rhs_i -= mdiv_error[i_node]; // rhs_i += div_i * eps_i; mL(i_node, i_node) = l_ii; } if(muse_mass_correction == true) { #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { double& rhs_i = rhs[i_node]; rhs_i -= mdiv_error[i_node]; } } //find the max diagonal term double max_diag = 0.0; for (int i_node = 0; i_node < n_nodes; i_node++) { double L_diag = mL(i_node, i_node); if (fabs(L_diag) > fabs(max_diag)) max_diag = L_diag; } if(max_diag < 1e20) max_diag=1e20; //respect pressure boundary conditions by penalization // double huge = max_diag * 1e6; // for (unsigned int i_pressure = 0; i_pressure < mPressureOutletList.size(); i_pressure++) { // unsigned int i_node = mPressureOutletList[i_pressure]; // mL(i_node, i_node) = huge; // rhs[i_node] = 0.0; // } for (unsigned int i_pressure = 0; i_pressure < mPressureOutletList.size(); i_pressure++) { unsigned int i_node = mPressureOutletList[i_pressure]; mL(i_node, i_node) = max_diag; rhs[i_node] = 0.0; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; mL(i_node, j_neighbour) = 0.0; } } //modification for level_set // mr_matrix_container.FillScalarFromDatabase(DISTANCE, mdistances, mr_model_part.Nodes()); // for (unsigned int i_dist = 0; i_dist < mdistances.size(); i_dist++) // { // if(mdistances[i_dist] >= 0) // { // mL(i_dist, i_dist) = huge; // rhs[i_dist] = 0.0; // } // } #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { if (mdistances[i_node] >= 0) { mL(i_node, i_node) = max_diag; rhs[i_node] = 0.0; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; mL(i_node, j_neighbour) = 0.0; } } else { for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; if (mdistances[j_neighbour] >= 0) mL(i_node, j_neighbour) = 0.0; } } } // for (int i_node = 0; i_node < n_nodes; i_node++) // { // if( fabs(mL(i_node, i_node)) < 1e-20) // { // mL(i_node, i_node)=max_diag; // rhs[i_node] = 0.0; // KRATOS_WATCH("arghhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"); // } // } //compute row scaling factors TSystemVectorType scaling_factors(n_nodes); double* Lvalues = mL.value_data().begin(); SizeType* Lrow_indices = mL.index1_data().begin(); SizeType* Lcol_indices = mL.index2_data().begin(); #pragma omp parallel for for (int k = 0; k < static_cast< int>(mL.size1()); k++) { double t = 0.0; SizeType col_begin = Lrow_indices[k]; SizeType col_end = Lrow_indices[k+1]; for (SizeType j=col_begin; j<col_end; j++) if( static_cast<int>(Lcol_indices[j]) == k) { t = fabs(Lvalues[j]); break; } // t += Lvalues[j]*Lvalues[j]; // t = sqrt(t); scaling_factors[k] = 1.0/sqrt(t); } #pragma omp parallel for for (int k = 0; k < static_cast<int>(mL.size1()); k++) { SizeType col_begin = Lrow_indices[k]; SizeType col_end = Lrow_indices[k+1]; double k_factor = scaling_factors[k]; rhs[k] *= k_factor; for (SizeType j=col_begin; j<col_end; j++) { Lvalues[j] *= scaling_factors[Lcol_indices[j]] * k_factor; } } //set starting vector for iterative solvers #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) dp[i_node] = 0.0; pLinearSolver->Solve(mL, dp, rhs); //update pressure #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) mPn1[i_node] += dp[i_node]*scaling_factors[i_node]; // for (unsigned int i_pressure = 0; i_pressure < mPressureOutletList.size(); i_pressure++) // { // unsigned int i_node = mPressureOutletList[i_pressure]; // mPn1[i_node] = mPressureOutlet[i_pressure]; // } //write pressure and density to Kratos mr_matrix_container.WriteScalarToDatabase(PRESSURE, mPn1, rNodes); //compute pressure proj for the next step #pragma omp parallel for private(work_array) for (int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, TDim>& xi_i = mXi[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) xi_i[comp] = 0.0; double dist = mdistances[i_node]; if (dist <= 0.0) //node is inside domain ---- if outside do nothing { const double& p_i = mPn1[i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& p_j = mPn1[j_neighbour]; //projection of pressure gradients CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_grad_p(xi_i, p_i, p_j); } const double& m_inv = mr_matrix_container.GetInvertedMass()[i_node]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) xi_i[l_comp] *= m_inv; } } mr_matrix_container.WriteVectorToDatabase(PRESS_PROJ, mXi, rNodes); KRATOS_CATCH("") } //********************************************************************************** //function to solve fluid equations - fractional step 3: correct fractional momentum void SolveStep3() { KRATOS_TRY //get number of nodes ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //define work array array_1d<double, TDim> correction; //read time step size from Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double delta_t = CurrentProcessInfo[DELTA_TIME]; double factor = 0.5; if(massume_constant_dp == true) factor = 1.0; //compute end of step momentum double rho_inv = 1.0 / mRho; #pragma omp parallel for private(correction) firstprivate(delta_t,rho_inv,factor) for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; if (dist < 0.0) //node is inside domain ---- if outside do nothing { array_1d<double, TDim>& U_i_curr = mvel_n1[i_node]; double delta_p_i = (mPn1[i_node] - mPn[i_node]) * rho_inv*factor; // const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; //setting to zero for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) correction[l_comp] = 0.0; //compute edge contributions dt*M^(-1)Gp for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; double delta_p_j = (mPn1[j_neighbour] - mPn[j_neighbour]) * rho_inv*factor; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; // edge_ij.Sub_grad_p(correction,delta_p_i,delta_p_j); edge_ij.Sub_grad_p(correction, delta_p_i, delta_p_j); // edge_ij.Add_grad_p(correction, delta_p_i, delta_p_j); // edge_ij.Add_Gp(correction,delta_p_i,delta_p_j); // edge_ij.Sub_Gp(correction,delta_p_i,delta_p_j); } //compute prefactor // double coefficient = delta_t * m_inv; const double m = mr_matrix_container.GetLumpedMass() [i_node]; const double& d = mdiag_stiffness[i_node]; //correct fractional momentum for (unsigned int comp = 0; comp < TDim; comp++) { U_i_curr[comp] += delta_t / (m + delta_t*d) * correction[comp]; } } } ApplyVelocityBC(mvel_n1); //write velocity of time step n+1 to Kratos mr_matrix_container.WriteVectorToDatabase(VELOCITY, mvel_n1, rNodes); //calculate the error on the divergence if(muse_mass_correction == true) { #pragma omp parallel for private(correction) firstprivate(delta_t,rho_inv) for (int i_node = 0; i_node < n_nodes; i_node++) { const double dist = mdistances[i_node]; double& div_i_err = mdiv_error[i_node]; div_i_err = 0.0; if (dist < 0.0) //node is inside domain ---- if outside do nothing { const array_1d<double, TDim>& U_i_curr = mvel_n1[i_node]; //compute edge contributions dt*M^(-1)Gp for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; array_1d<double, TDim>& U_j_curr = mvel_n1[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_D_v(div_i_err, U_i_curr*mRho, U_j_curr * mRho); } } } } KRATOS_CATCH("") } //************************************ void ApplyVelocityBC(CalcVectorType& VelArray) { KRATOS_TRY if(mWallLawIsActive == false) { //apply conditions on corner edges int edge_size = medge_nodes_direction.size(); #pragma omp parallel for firstprivate(edge_size) for (int i = 0; i < edge_size; i++) { int i_node = medge_nodes[i]; const array_1d<double, TDim>& direction = medge_nodes_direction[i]; double dist = mdistances[i_node]; if(dist <= 0.0) { array_1d<double, TDim>& U_i = VelArray[i_node]; double temp=0.0; for (unsigned int comp = 0; comp < TDim; comp++) temp += U_i[comp] * direction[comp]; for (unsigned int comp = 0; comp < TDim; comp++) U_i[comp] = direction[comp]*temp; } } //apply conditions on corners int corner_size = mcorner_nodes.size(); for (int i = 0; i < corner_size; i++) { int i_node = mcorner_nodes[i]; array_1d<double, TDim>& U_i = VelArray[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) U_i[comp] = 0.0; } } //slip condition int slip_size = mSlipBoundaryList.size(); #pragma omp parallel for firstprivate(slip_size) for (int i_slip = 0; i_slip < slip_size; i_slip++) { unsigned int i_node = mSlipBoundaryList[i_slip]; double dist = mdistances[i_node]; if(dist <= 0.0) { array_1d<double, TDim>& U_i = VelArray[i_node]; array_1d<double, TDim>& an_i = mSlipNormal[i_node]; double projection_length = 0.0; double normalization = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) { projection_length += U_i[comp] * an_i[comp]; normalization += an_i[comp] * an_i[comp]; } projection_length /= normalization; //tangential momentum as difference between original and normal momentum for (unsigned int comp = 0; comp < TDim; comp++) U_i[comp] -= projection_length * an_i[comp]; } } //fixed condition int fixed_size = mFixedVelocities.size(); #pragma omp parallel for firstprivate(fixed_size) for (int i_velocity = 0; i_velocity < fixed_size; i_velocity++) { unsigned int i_node = mFixedVelocities[i_velocity]; double dist = mdistances[i_node]; if(dist <= 0.0) { const array_1d<double, TDim>& u_i_fix = mFixedVelocitiesValues[i_velocity]; array_1d<double, TDim>& u_i = VelArray[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) u_i[comp] = u_i_fix[comp]; } } KRATOS_CATCH("") } //******************************** //function to compute coefficients void ExtrapolateValues(unsigned int extrapolation_layers) { KRATOS_TRY //ensure that corner nodes are wet if all of the nodes around them have a negative distance typedef Node < 3 > PointType; typedef PointerVector<PointType > PointVector; typedef PointVector::iterator PointIterator; mr_matrix_container.FillScalarFromDatabase(DISTANCE, mdistances,mr_model_part.Nodes()); // mr_matrix_container.FillVectorFromDatabase(PRESS_PROJ, mXi,mr_model_part.Nodes()); // // //loop on all the slip nodes and Set the pressure projection to -BodyForce if it has neighbours with distance greater than 0 // int slip_size = mSlipBoundaryList.size(); // #pragma omp parallel for firstprivate(slip_size) // for (int i_slip = 0; i_slip < slip_size; i_slip++) // { // unsigned int i_node = mSlipBoundaryList[i_slip]; // double dist = mdistances[i_node]; // // // if(dist <= 0.0) // { // int nout = 0; // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // //get global index of neighbouring node j // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // const double& dist_j = mdistances[j_neighbour]; // // if(dist_j > 0) // nout++; // } // // if(nout > 0) mXi[i_node] += mRho*mBodyForce; // } // } // // mr_matrix_container.WriteVectorToDatabase(PRESS_PROJ, mXi,mr_model_part.Nodes()); //reset is visited flag for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->GetValue(IS_VISITED) = 0.0; } //generate a container with the layers to be extrapolated std::vector< PointVector > layers(extrapolation_layers); //detect the nodes inside the fluid surface for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { if (inode->FastGetSolutionStepValue(DISTANCE) < 0.0) //candidates are only the ones inside the fluid domain { GlobalPointersVector< Node < 3 > >& neighb_nodes = inode->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->FastGetSolutionStepValue(DISTANCE) >= 0.0) //add the node as free surface if one of its neighb is outside { if (inode->GetValue(IS_VISITED) == 0.0) { layers[0].push_back(*(inode.base())); inode->GetValue(IS_VISITED) = 1.0; } } } } else { //set everything to zero noalias(inode->FastGetSolutionStepValue(VELOCITY)) = ZeroVector(3); inode->FastGetSolutionStepValue(PRESSURE) = 0.0; noalias(inode->FastGetSolutionStepValue(VELOCITY, 1)) = ZeroVector(3); inode->FastGetSolutionStepValue(PRESSURE, 1) = 0.0; noalias(inode->FastGetSolutionStepValue(PRESS_PROJ)) = ZeroVector(3); noalias(inode->FastGetSolutionStepValue(PRESS_PROJ, 1)) = ZeroVector(3); } } //fill the following layers by neighbour relationships //each layer fills the following for (unsigned int il = 0; il < extrapolation_layers - 1; il++) { for (PointIterator iii = (layers[il]).begin(); iii != (layers[il]).end(); iii++) { GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator jjj = neighb_nodes.begin(); jjj != neighb_nodes.end(); jjj++) //destination = origin1 + value * Minv*origin { if (jjj->FastGetSolutionStepValue(DISTANCE) >= 0 && jjj->GetValue(IS_VISITED) == 0.0) { layers[il + 1].push_back(Node < 3 > ::Pointer(*(jjj.base()))); jjj->GetValue(IS_VISITED) = double(il + 2.0); } } } } array_1d<double, 3 > aux, aux_proj; //TESTING!!! //fill the pressure projection on the first layer inside the fluid //by extrapolating from the pressure projection on the layer -1 (the first layer completely inside the domain) for (PointIterator iii = (layers[0]).begin(); iii != (layers[0]).end(); iii++) { noalias(aux_proj) = ZeroVector(3); double avg_number = 0.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->GetValue(IS_VISITED) == 0.0) //the node will be considered for extrapolation only if completely inside { const array_1d<double, 3 > & inside_press_grad = i->FastGetSolutionStepValue(PRESS_PROJ); noalias(aux_proj) += inside_press_grad; avg_number += 1.0; } } if (avg_number != 0.0) //this case means that it has some neighbours that are completely internal { aux_proj /= avg_number; noalias(iii->FastGetSolutionStepValue(PRESS_PROJ)) = aux_proj; } else //case in which there is not a layer of nodes completely internal { array_1d<double,3>& pproj = iii->FastGetSolutionStepValue(PRESS_PROJ); for(unsigned int i=0; i<TDim; i++) pproj[i] = mRho*mBodyForce[i]; // noalias(iii->FastGetSolutionStepValue(PRESS_PROJ)) = mRho*mBodyForce; } } //perform extrapolation layer by layer by making an average //of the neighbours of lower order for (unsigned int il = 1; il < extrapolation_layers; il++) { // std::cout << "layer " << il << std::endl; for (PointIterator iii = layers[il].begin(); iii != layers[il].end(); iii++) { // std::cout << iii->Id() << " " << std::endl; const array_1d<double, 3 > & coords_top = iii->Coordinates(); //extrapolate the average velocity noalias(aux) = ZeroVector(3); noalias(aux_proj) = ZeroVector(3); double avg_number = 0.0; double pavg = 0.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { if (i->GetValue(IS_VISITED) < (il + 1) && i->GetValue(IS_VISITED) != 0.0) { const array_1d<double, 3 > & coords_bottom = i->Coordinates(); array_1d<double, 3 > direction_vec = coords_top; noalias(direction_vec) -= coords_bottom; const array_1d<double, 3 > & press_grad = i->FastGetSolutionStepValue(PRESS_PROJ); double temp = inner_prod(direction_vec, press_grad); double pestimate = i->FastGetSolutionStepValue(PRESSURE,1) + temp; pavg += pestimate; noalias(aux_proj) += press_grad; noalias(aux) += i->FastGetSolutionStepValue(VELOCITY); avg_number += 1.0; } } if (avg_number != 0.0) { aux /= avg_number; pavg /= avg_number; aux_proj /= avg_number; } else { KRATOS_THROW_ERROR(std::runtime_error, "error in extrapolation:: no neighbours find on a extrapolation layer -- impossible", ""); // KRATOS_THROW_ERROR(std:logic_error,"error in extrapolation:: no neighbours find on a extrapolation layer -- impossible",""); } noalias(iii->FastGetSolutionStepValue(VELOCITY)) = aux; noalias(iii->FastGetSolutionStepValue(VELOCITY, 1)) = aux; iii->FastGetSolutionStepValue(PRESSURE, 1) = pavg; noalias(iii->FastGetSolutionStepValue(PRESS_PROJ)) = aux_proj; noalias(iii->FastGetSolutionStepValue(PRESS_PROJ, 1)) = aux_proj; } } mr_matrix_container.FillVectorFromDatabase(PRESS_PROJ, mXi, mr_model_part.Nodes()); // //on the first layer outside the pressure is set to a value such that on the free surface the pressure is approx 0 // for (PointIterator iii = layers[1].begin(); iii != layers[1].end(); iii++) // { // //get the node // unsigned int i_node = iii->FastGetSolutionStepValue(AUX_INDEX); // // array_1d<double, TDim> grad_d; // for (unsigned int comp = 0; comp < TDim; comp++) // grad_d[comp] = 0.0; // // double dist_i = mdistances[i_node]; // // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // //get global index of neighbouring node j // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // // const double& dist_j = mdistances[j_neighbour]; // // //projection of pressure gradients // CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; // // edge_ij.Add_grad_p(grad_d, dist_i, dist_j); // } // // const double& m_inv = mr_matrix_container.GetInvertedMass()[i_node]; // for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) // grad_d[l_comp] *= m_inv; // // double norm_grad = norm_2(grad_d); // // if(norm_grad < 100.0) // { // grad_d /= norm_grad; //this is the direction of the gradient of the distances // // grad_d *= dist_i; //this is the vector with the distance of node_i from the closest point on the free surface // // const array_1d<double, TDim> press_grad = iii->FastGetSolutionStepValue(PRESS_PROJ); // double pestimate = inner_prod(press_grad,grad_d); // // iii->FastGetSolutionStepValue(PRESSURE) = pestimate; // } // else // { // std::cout << "attention gradient of distance much greater than 1 on node:" << i_node <<std::endl; // double avg_number = 0.0; // // double pavg = 0.0; // // GlobalPointersVector< Node < 3 > >& neighb_nodes = iii->GetValue(NEIGHBOUR_NODES); // for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) // { // if (i->GetValue(IS_VISITED) == 1) { // pavg += i->FastGetSolutionStepValue(PRESSURE); // avg_number += 1.0; // } // } // // if(avg_number == 0) // KRATOS_THROW_ERROR(std::logic_error,"can not happen that the extrapolation node has no neighbours",""); // // iii->FastGetSolutionStepValue(PRESSURE) = pavg/avg_number; // // } // // } // // // //set the pressure to zero on the outer layers (>2) // for (unsigned int il = 2; il < extrapolation_layers; il++) // { // for (PointIterator iii = layers[il].begin(); iii != layers[il].end(); iii++) // // { // iii->FastGetSolutionStepValue(PRESSURE) = 0.0; // } // } //mark nodes on which we will have to solve for convection //mark all of internal nodes ModelPart::NodesContainerType::iterator it_begin = mr_model_part.NodesBegin(); for (unsigned int i_node = 0; i_node < mr_model_part.Nodes().size(); i_node++) { ModelPart::NodesContainerType::iterator it = it_begin+i_node; if(it->FastGetSolutionStepValue(DISTANCE) <= 0.0) it->GetValue(IS_VISITED) = 1.0; else it->GetValue(IS_VISITED) = 0.0; } //now mark all of the nodes up to the extrapolation layers - 1 for (unsigned int il = 0; il < extrapolation_layers-1; il++) for (PointIterator iii = layers[il].begin(); iii != layers[il].end(); iii++) iii->GetValue(IS_VISITED) = 1.0; mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); ApplyVelocityBC(mvel_n1); mr_matrix_container.WriteVectorToDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); KRATOS_CATCH("") } void ChangeSignToDistance() { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { double dist = inode->FastGetSolutionStepValue(DISTANCE); inode->FastGetSolutionStepValue(DISTANCE) = -dist; } KRATOS_CATCH("") } void MarkNodesByDistance(double min, double max) { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { double dist = inode->FastGetSolutionStepValue(DISTANCE); if (dist > min && dist < max) inode->GetValue(IS_VISITED) = 1.0; else inode->GetValue(IS_VISITED) = 0.0; } KRATOS_CATCH("") } void SaveScalarVariableToOldStep(Variable<double>& rVar) { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->FastGetSolutionStepValue(rVar, 1) = inode->FastGetSolutionStepValue(rVar); } KRATOS_CATCH("") } void MarkExternalAndMixedNodes() { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->GetValue(IS_VISITED) = 0.0; } //detect the nodes inside the fluid surface for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { if (inode->FastGetSolutionStepValue(DISTANCE) > 0.0) //candidates are only the ones inside the fluid domain { inode->GetValue(IS_VISITED) = 1.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = inode->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { i->GetValue(IS_VISITED) = 1.0; } } } KRATOS_CATCH("") } void MarkInternalAndMixedNodes() { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->GetValue(IS_VISITED) = 0.0; } //detect the nodes inside the fluid surface for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { if (inode->FastGetSolutionStepValue(DISTANCE) <= 0.0) //candidates are only the ones inside the fluid domain { inode->GetValue(IS_VISITED) = 1.0; GlobalPointersVector< Node < 3 > >& neighb_nodes = inode->GetValue(NEIGHBOUR_NODES); for (GlobalPointersVector< Node < 3 > >::iterator i = neighb_nodes.begin(); i != neighb_nodes.end(); i++) { i->GetValue(IS_VISITED) = 1.0; } } } KRATOS_CATCH("") } void MarkInternalNodes() { KRATOS_TRY for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { inode->GetValue(IS_VISITED) = 0.0; } //detect the nodes inside the fluid surface for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { if (inode->FastGetSolutionStepValue(DISTANCE) <= 0.0) //candidates are only the ones inside the fluid domain { inode->GetValue(IS_VISITED) = 1.0; } } KRATOS_CATCH("") } //************************************** //function to calculate the area normals void CalculateNormals(ModelPart::ConditionsContainerType& rConditions) { KRATOS_TRY //calculate area normals face-by-face array_1d<double, 3 > area_normal; //2D case if (TDim == 2) { for (ModelPart::ConditionsContainerType::iterator cond_it = rConditions.begin(); cond_it != rConditions.end(); cond_it++) CalculateNormal2D(cond_it, area_normal); }//3D case else if (TDim == 3) { //help vectors for cross product array_1d<double, 3 > v1; array_1d<double, 3 > v2; for (ModelPart::ConditionsContainerType::iterator cond_it = rConditions.begin(); cond_it != rConditions.end(); cond_it++) CalculateNormal3D(cond_it, area_normal, v1, v2); } //(re)initialize normals unsigned int n_nodes = mNodalFlag.size(); mInOutNormal.resize(n_nodes); mSlipNormal.resize(n_nodes); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { noalias(mSlipNormal[i_node]) = ZeroVector(TDim); mis_slip[i_node] = false; noalias(mInOutNormal[i_node]) = ZeroVector(TDim); } //loop over all faces const double node_factor = 1.0 / TDim; for (ModelPart::ConditionsContainerType::iterator cond_it = rConditions.begin(); cond_it != rConditions.end(); cond_it++) { //get geometry data of the face Geometry<Node < 3 > >& face_geometry = cond_it->GetGeometry(); //reference for area normal of the face array_1d<double, 3 > & face_normal = cond_it->GetValue(NORMAL); //slip condition if (static_cast<bool>(cond_it->GetValue(IS_STRUCTURE)) == true) for (unsigned int if_node = 0; if_node < TDim; if_node++) { unsigned int i_node = static_cast<unsigned int> (face_geometry[if_node].FastGetSolutionStepValue(AUX_INDEX)); array_1d<double, TDim>& slip_normal = mSlipNormal[i_node]; mis_slip[i_node] = true; for (unsigned int comp = 0; comp < TDim; comp++) { slip_normal[comp] += node_factor * face_normal[comp]; } } } //fill the list of slip nodes std::vector< unsigned int> tempmSlipBoundaryList; for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { if (mis_slip[i_node] == true) tempmSlipBoundaryList.push_back(i_node); mis_slip[i_node] = false; } mSlipBoundaryList.resize(tempmSlipBoundaryList.size(),false); #pragma omp parallel for for(int i=0; i<static_cast<int>(tempmSlipBoundaryList.size()); i++) mSlipBoundaryList[i] = tempmSlipBoundaryList[i]; //loop over all faces to fill inlet outlet for (ModelPart::ConditionsContainerType::iterator cond_it = rConditions.begin(); cond_it != rConditions.end(); cond_it++) { //get geometry data of the face Geometry<Node < 3 > >& face_geometry = cond_it->GetGeometry(); //reference for area normal of the face array_1d<double, 3 > & face_normal = cond_it->GetValue(NORMAL); //inlet or outlet condition bool is_inlet_or_outlet = false; if (cond_it->GetValue (IS_STRUCTURE) != true) is_inlet_or_outlet = true; else { for (unsigned int if_node = 0; if_node < TDim; if_node++) if (face_geometry[if_node].IsFixed (VELOCITY_X) ) is_inlet_or_outlet = true; } //slip condition if (is_inlet_or_outlet) //the opposite of the loop before for (unsigned int if_node = 0; if_node < TDim; if_node++) { unsigned int i_node = static_cast<unsigned int> (face_geometry[if_node].FastGetSolutionStepValue(AUX_INDEX)); array_1d<double, TDim>& inout_normal = mInOutNormal[i_node]; mis_slip[i_node] = true; //reutilize it! for (unsigned int comp = 0; comp < TDim; comp++) { inout_normal[comp] += node_factor * face_normal[comp]; } } } //fill the list of inlet outlet nodes nodes std::vector< unsigned int> tempmInOutBoundaryList; for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { if (mis_slip[i_node] == true) tempmInOutBoundaryList.push_back(i_node); } mInOutBoundaryList.resize(tempmInOutBoundaryList.size(),false); #pragma omp parallel for for(int i=0; i<static_cast<int>(tempmInOutBoundaryList.size()); i++) mInOutBoundaryList[i] = tempmInOutBoundaryList[i]; KRATOS_CATCH("") } //******************************* //function to free dynamic memory void Clear() { KRATOS_TRY mViscosity.clear(); mWork.clear(); mvel_n.clear(); mvel_n1.clear(); mPn.clear(); mPn1.clear(); mHmin.clear(); mHavg.clear(); mSlipNormal.clear(); mNodalFlag.clear(); mFixedVelocities.clear(); mFixedVelocitiesValues.clear(); mPressureOutletList.clear(); // mPressureOutlet.clear(); mSlipBoundaryList.clear(); mL.clear(); mTauPressure.clear(); mTauConvection.clear(); mTau2.clear(); mBeta.clear(); mPiConvection.clear(); mphi_n.clear(); mphi_n1.clear(); mEps.clear(); mA.clear(); mB.clear(); mStrVel.clear(); mdiv_error.clear(); mdiag_stiffness.clear(); mis_slip.clear(); KRATOS_CATCH ("") } void ConvectDistance() { KRATOS_TRY //variables for node based data handling ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //storage of nodal values in local variables ValuesVectorType rhs, WorkConvection; rhs.resize(n_nodes); WorkConvection.resize(n_nodes); ValuesVectorType active_nodes; active_nodes.resize(n_nodes); mr_matrix_container.FillScalarFromDatabase(POROSITY, mEps, mr_model_part.Nodes()); //read variables from Kratos mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); mr_matrix_container.FillOldVectorFromDatabase(VELOCITY, mvel_n, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(DISTANCE, mphi_n1, mr_model_part.Nodes()); mr_matrix_container.FillOldScalarFromDatabase(DISTANCE, mphi_n, mr_model_part.Nodes()); //mr_matrix_container.AssignVectorToVector(mphi_n1, mphi_n); //mWork = mphi_n // //chapuza // //set the distance to zero when it tries to go out of the pressure boundary // int pressure_size = mPressureOutletList.size(); // #pragma omp parallel for firstprivate(pressure_size) // for (int iii = 0; iii < pressure_size; iii++) // { // unsigned int i_node = mPressureOutletList[iii]; // mphi_n1[i_node] = fabs(mphi_n1[i_node]); // mphi_n[i_node] = fabs(mphi_n[i_node]); // } //create and fill a vector of nodes for which we want to convect the velocity for (int i_node = 0; i_node < n_nodes; i_node++) { ModelPart::NodesContainerType::iterator it_begin = mr_model_part.NodesBegin(); active_nodes[i_node] = (it_begin + i_node)->GetValue(IS_VISITED); } // //calculating the convective projection // array_1d<double, TDim> a_i; // array_1d<double, TDim> a_j; // #pragma omp parallel for private(a_i,a_j) // for (int i_node = 0; i_node < n_nodes; i_node++) // { // double& pi_i = mPiConvection[i_node]; // const double& phi_i = mphi_n1[i_node]; // //set to zero the projection // pi_i = 0.0; // if (active_nodes[i_node] != 0.0) // { // a_i = mvel_n1[i_node]; // a_i /= mEps[i_node]; // // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // // if (active_nodes[j_neighbour] != 0.0) // { // noalias(a_j) = mvel_n1[j_neighbour]; // a_j /= mEps[j_neighbour]; // // const double& phi_j = mphi_n1[j_neighbour]; // CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; // edge_ij.Add_ConvectiveContribution(pi_i, a_i, phi_i, a_j, phi_j); // } // } // //apply inverted mass matrix // const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; // pi_i *= m_inv; // } // } //calculating the convective projection array_1d<double, TDim> a_i; array_1d<double, TDim> a_j; #pragma omp parallel for private(a_i,a_j) for (int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, TDim>& pi_i = mPiConvection[i_node]; // setting to zero the projection for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] = 0.0; /* if (active_nodes[i_node] != 0.0) {*/ const double& phi_i = mphi_n1[i_node]; noalias(a_i) = mvel_n1[i_node]; a_i /= mEps[i_node]; // loop to all the edges surrounding node I for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; noalias(a_j) = mvel_n1[j_neighbour]; a_j /= mEps[j_neighbour]; const double& phi_j = mphi_n1[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_grad_p(pi_i, phi_i, phi_j); } // apply inverted mass matrix const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) pi_i[l_comp] *= m_inv; // } } //calculating limitor #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { const array_1d<double, TDim>& pi_i = mPiConvection[i_node]; const double& p_i = mphi_n1[i_node]; double& beta_i = mBeta[i_node]; beta_i = 0.0; double n = 0.0; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& p_j = mphi_n1[j_neighbour]; const array_1d<double, TDim>& l_k = mEdgeDimensions[csr_index]; const array_1d<double, TDim>& pi_j = mPiConvection[j_neighbour]; // double proj = 0.0; // for (unsigned int comp = 0; comp < TDim; comp++) // proj += 0.5*l_k[comp]*(pi_i[comp]+pi_j[comp]); // double beta = fabs((p_i - p_j - proj)/(fabs(p_i-p_j)+fabs(proj)+1e-4)); double proj = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) proj += 0.5 * l_k[comp]*(pi_i[comp] + pi_j[comp]); // proj += dir[comp]*pi_i[comp]; double numerator = fabs(fabs(p_j - p_i) - fabs(proj)); double denom = fabs(fabs(p_j - p_i) + 1e-6); beta_i += numerator / denom; n += 1.0; } beta_i /= n; if (beta_i > 1.0) beta_i = 1.0; } // mr_matrix_container.WriteScalarToDatabase(TEMPERATURE, active_nodes, rNodes); //read time step size from Kratos ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double delta_t = CurrentProcessInfo[DELTA_TIME]; mr_matrix_container.AssignVectorToVector(mphi_n, WorkConvection); //mWork = mphi_n //first step of Runge Kutta // mr_matrix_container.AssignVectorToVector(mphi_n,mphi_n1); //mphi_n1 = mphi_n mr_matrix_container.SetToZero(rhs); CalculateRHS_convection(mphi_n1, mvel_n1, rhs, active_nodes); mr_matrix_container.Add_Minv_value(WorkConvection, WorkConvection, delta_t / 6.0, mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, 0.5 * delta_t, mr_matrix_container.GetInvertedMass(), rhs); //second step mr_matrix_container.SetToZero(rhs); CalculateRHS_convection(mphi_n1, mvel_n1, rhs, active_nodes); mr_matrix_container.Add_Minv_value(WorkConvection, WorkConvection, delta_t / 3.0, mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, 0.5 * delta_t, mr_matrix_container.GetInvertedMass(), rhs); //third step mr_matrix_container.SetToZero(rhs); CalculateRHS_convection(mphi_n1, mvel_n1, rhs, active_nodes); mr_matrix_container.Add_Minv_value(WorkConvection, WorkConvection, delta_t / 3.0, mr_matrix_container.GetInvertedMass(), rhs); mr_matrix_container.Add_Minv_value(mphi_n1, mphi_n, delta_t, mr_matrix_container.GetInvertedMass(), rhs); //fourth step mr_matrix_container.SetToZero(rhs); CalculateRHS_convection(mphi_n1, mvel_n1, rhs, active_nodes); mr_matrix_container.Add_Minv_value(WorkConvection, WorkConvection, delta_t / 6.0, mr_matrix_container.GetInvertedMass(), rhs); //compute right-hand side mr_matrix_container.AssignVectorToVector(WorkConvection, mphi_n1); // // make sure that boundary nodes that are very close to the free surface get wet // int slip_size = mSlipBoundaryList.size(); // #pragma omp parallel for firstprivate(slip_size) // for (int i_slip = 0; i_slip < slip_size; i_slip++) { // unsigned int i_node = mSlipBoundaryList[i_slip]; // const double& h_i = mHmin[i_node]; // double& dist_i = mphi_n1[i_node]; // // if(dist_i > 0.0 && dist_i < 0.5*h_i) // { // //loop to all the edges surrounding node I // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // if(mphi_n1[j_neighbour] <= 0.0) // dist_i = -0.01 * h_i; // } // } // // } // int fixed_size = mFixedVelocities.size(); // #pragma omp parallel for firstprivate(fixed_size) // for (int i_velocity = 0; i_velocity < fixed_size; i_velocity++) { // unsigned int i_node = mFixedVelocities[i_velocity]; // const double& h_i = mHmin[i_node]; // double& dist_i = mphi_n1[i_node]; // // if(dist_i > 0.0 && dist_i < 0.5*h_i) // { // //loop to all the edges surrounding node I // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // if(mphi_n1[j_neighbour] <= 0.0) // dist_i = -0.01 * h_i; // } // } // } //wetten corner nodes if needed int corner_size = mcorner_nodes.size(); for (int i = 0; i < corner_size; i++) { int i_node = mcorner_nodes[i]; bool to_be_wettened = true; double min_dist = 0.0; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; double neighb_dist = mphi_n1[j_neighbour]; if(min_dist > neighb_dist) min_dist = neighb_dist; if(neighb_dist >= 0.0) { to_be_wettened=false; } } if(to_be_wettened==true) mphi_n1[i_node] = min_dist; } mr_matrix_container.WriteScalarToDatabase(DISTANCE, mphi_n1, mr_model_part.Nodes()); KRATOS_CATCH("") } void ReduceTimeStep(ModelPart& rModelPart, double NewTime) { KRATOS_TRY /* double current_time = rModelPart.GetProcessInfo()[TIME]; double current_delta_time = rModelPart.GetProcessInfo()[DELTA_TIME]; double old_time = current_time - current_delta_time; double new_reduced_time = NewTtime; double new_delta_time = new_reduced_time - old_time; rModelPart.GetProcessInfo()[TIME] = new_reduced_time; rModelPart.GetProcessInfo()[DELTA_TIME] = new_delta_time; //now copy the database from the old step on the top of the current step int step_data_size = ThisModelPart.GetNodalSolutionStepDataSize(); double* current_data = (pnode)->SolutionStepData().Data(0); double* old_data = (pnode)->SolutionStepData().Data(1); for (int j = 0; j < step_data_size; j++) current_data[j] = old_data[j]; */ rModelPart.OverwriteSolutionStepData(1, 0); rModelPart.GetProcessInfo().SetCurrentTime(NewTime); KRATOS_CATCH("error in reducing the time step") } bool CheckDistanceConvection() { int n_large_distance_gradient = 0; array_1d<double, TDim> grad_d; ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); //calculate gradient of distance on the nodes and count occurrences of large gradients (that indicate a failure) for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; if (dist <= 0.0) { for (unsigned int comp = 0; comp < TDim; comp++) grad_d[comp] = 0.0; double dist_i = mdistances[i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& dist_j = mdistances[j_neighbour]; //projection of pressure gradients CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; edge_ij.Add_grad_p(grad_d, dist_i, dist_j); } const double& m_inv = mr_matrix_container.GetInvertedMass()[i_node]; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) grad_d[l_comp] *= m_inv; double norm_grad = norm_2(grad_d); if (norm_grad > 1.5) //large gradient found n_large_distance_gradient += 1; } } if (n_large_distance_gradient != 0) { bool success = false; return success; } else { bool success = true; return success; } } void ActivateWallResistance(double Ywall) { mWallLawIsActive = true; mY_wall = Ywall; } double ComputeVolumeVariation() { ProcessInfo& CurrentProcessInfo = mr_model_part.GetProcessInfo(); double dt = CurrentProcessInfo[DELTA_TIME]; //slip condition int inout_size = mInOutBoundaryList.size(); double vol_var = 0.0; //#pragma omp parallel for firstprivate(slip_size) for (int i = 0; i < inout_size; i++) { unsigned int i_node = mInOutBoundaryList[i]; double dist = mdistances[i_node]; if (dist <= 0.0) { const array_1d<double, TDim>& U_i = mvel_n1[i_node]; const array_1d<double, TDim>& an_i = mInOutNormal[i_node]; double projection_length = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) { projection_length += U_i[comp] * an_i[comp]; } vol_var += projection_length; } } return vol_var * dt; } double ComputeWetVolume() { KRATOS_TRY mr_matrix_container.FillScalarFromDatabase(DISTANCE, mdistances, mr_model_part.Nodes()); //slip condition double wet_volume = 0.0; //#pragma omp parallel for firstprivate(slip_size) for (int i = 0; i < static_cast<int>(mdistances.size()); i++) { double dist = mdistances[i]; const double m_inv = mr_matrix_container.GetInvertedMass()[i]; if (dist <= 0.0) { wet_volume += 1.0 / m_inv; } } return wet_volume; KRATOS_CATCH(""); } void DiscreteVolumeCorrection(double expected_volume, double measured_volume) { // std::cout << "measured_volume: " << measured_volume << ", expected_volume: " << expected_volume << std::endl; double volume_error = expected_volume - measured_volume; if (measured_volume < expected_volume) { double layer_volume = 0.0; std::vector<unsigned int> first_outside; int n_nodes = mdistances.size(); // find list of the first nodes outside of the fluid and compute their volume for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; if (dist > 0.0) //node is outside domain { for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; if(mdistances[j_neighbour] <= 0.0) { const double nodal_mass = 1.0 / mr_matrix_container.GetInvertedMass()[i_node]; if(nodal_mass < volume_error - layer_volume) { first_outside.push_back(i_node); layer_volume += nodal_mass; } //const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; //layer_volume += 1.0/m_inv; } } } } // std::cout << ", layer_volume: " << layer_volume << std::endl; // if (measured_volume + layer_volume <= expected_volume) { // mark the nodes in the outside layer with a small negative distance for(unsigned int i=0; i<first_outside.size(); i++) { unsigned int i_node = first_outside[i]; mdistances[i_node] = -mHavg[i_node]; } } } mr_matrix_container.WriteScalarToDatabase(DISTANCE, mdistances, mr_model_part.Nodes()); } void PushFreeSurface() { //double layer_volume = 0.0; std::vector<unsigned int> first_outside; int n_nodes = mdistances.size(); //find list of the first nodes outside of the fluid and compute their volume for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; if (dist > 0.0) //node is outside domain { for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; if(mdistances[j_neighbour] <= 0.0) { //mark the nodes in the outside layer with a small negative distance mdistances[i_node] = -mHavg[i_node]; } } } } mr_matrix_container.WriteScalarToDatabase(DISTANCE, mdistances, mr_model_part.Nodes()); } //*************************************** //function to set adequate time step size double ComputeBoundedTimeStep(const double CFLNumber, const double MaxDt) { KRATOS_TRY //save the maximum time step max_dt = MaxDt; //local variable for time step size double delta_t = 1e10;//max_dt; mdelta_t_avg = 1e10;//max_dt; //getting value of current velocity and of viscosity mr_matrix_container.FillVectorFromDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(VISCOSITY, mViscosity, mr_model_part.Nodes()); // mr_matrix_container.FillVectorFromDatabase(PRESS_PROJ, mXi, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(POROSITY, mEps, mr_model_part.Nodes()); // mr_matrix_container.FillScalarFromDatabase(DIAMETER, mD, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(LIN_DARCY_COEF, mA, mr_model_part.Nodes()); mr_matrix_container.FillScalarFromDatabase(NONLIN_DARCY_COEF, mB, mr_model_part.Nodes()); mr_matrix_container.FillVectorFromDatabase(STRUCTURE_VELOCITY, mStrVel, mr_model_part.Nodes()); // double delta_t_i = delta_t; //******************* //loop over all nodes double n_nodes = mvel_n1.size(); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, TDim>& v_i = mvel_n1[i_node]; const double havg_i = mHavg[i_node]; const double hmin_i = mHmin[i_node]; const double eps_i = mEps[i_node]; const double nu_i = mViscosity[i_node]; // const double d_i = mD[i_node]; // const double lindarcy_i = mA[i_node]; // const double nonlindarcy_i = mB[i_node]; // double vel_norm = norm_2(v_i); double vel_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { vel_norm += v_i[l_comp]*v_i[l_comp]; } vel_norm = sqrt(vel_norm); // const array_1d<double, TDim>& str_v_i = mStrVel[i_node]; // array_1d<double, TDim> rel_vel_i; // for(unsigned int comp = 0; comp < TDim; comp++) // {rel_vel_i[comp] = v_i[comp] - str_v_i[comp];} // double rel_vel_norm = norm_2(rel_vel_i); //// double porosity_coefficient = ComputePorosityCoefficient(mViscosity, vel_norm, eps_i, d_i); // double porosity_coefficient = ComputePorosityCoefficient(rel_vel_norm, eps_i, lindarcy_i, nonlindarcy_i); /*KRATOS_WATCH("porosity_coefficient ----------- Timestep") KRATOS_WATCH(porosity_coefficient)*/ vel_norm /= eps_i; //use CFL condition to compute time step size double delta_t_i = CFLNumber * 1.0 / (2.0 * vel_norm /hmin_i + 4.0 * nu_i / (hmin_i * hmin_i) /*+ porosity_coefficient*/); double delta_t_i_avg = 1.0 / (2.0 * vel_norm /havg_i + 4.0 * nu_i / (havg_i * havg_i) /*+ porosity_coefficient*/); if(delta_t_i < 10e-8) //NO PHYSICS AT ALL!!!!! bounding the delata_t to 10e-08 by reducing the velocity!! { //std::cout << "NO PHYSICS AT ALL!!!!! bounding the delata_t to 10e-08 by reducing the velocity!!" << std::endl; //KRATOS_WATCH(delta_t_i) v_i *= delta_t_i / 10e-8; delta_t_i = 10e-8; } if(delta_t_i_avg < 10e-8) //NO PHYSICS AT ALL!!!!! bounding the delta_t_i_avg to 10e-08 by reducing the velocity!! { //std::cout << "NO PHYSICS AT ALL!!!!! bounding the delta_t_i_avg to 10e-08 by reducing the velocity!!" << std::endl; //KRATOS_WATCH(delta_t_i_avg) v_i *= delta_t_i_avg / 10e-8; delta_t_i_avg = 10e-8; } //considering the most restrictive case of neighbor's velocities with similar direction but opposite sense. //loop over all neighbours for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { //get global index of neighbouring node j unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; array_1d<double, TDim>& v_j = mvel_n1[j_neighbour]; double v_diff_norm = 0.0; for (unsigned int l_comp = 0; l_comp < TDim; l_comp++) { double temp = v_i[l_comp] - v_j[l_comp]; v_diff_norm += temp*temp; } v_diff_norm = sqrt(v_diff_norm); v_diff_norm /= eps_i; double delta_t_j = CFLNumber * 1.0 / (2.0 * v_diff_norm /hmin_i + 4.0 * nu_i / (hmin_i * hmin_i)); if(delta_t_j < 10e-8) //NO PHYSICS AT ALL!!!!! bounding the delata_t to 10e-08 by reducing the velocity!! { //std::cout << "NO PHYSICS AT ALL!!!!! bounding the delta_t_j to 10e-08 by reducing the velocity!!" << std::endl; //KRATOS_WATCH(delta_t_j) v_j *= delta_t_j / 10e-8; delta_t_j = 10e-8; } if (delta_t_j < delta_t_i) delta_t_i = delta_t_j; // if ((v_i_par >= 0.0 && v_j_par <= 0.0) || (v_i_par <= 0.0 && v_j_par >= 0.0)) // { // double delta_t_j = CFLNumber * 1.0 / (2.0 * norm_2(v_diff) /hmin_i + 4.0 * mViscosity / (hmin_i * hmin_i)); //// double delta_t_j = CFLNumber / ((fabs(v_i_par) + fabs(v_j_par)) / mHmin[i_node] + 2.0 * mViscosity / (mHmin[i_node] * mHmin[i_node])); // // KRATOS_WATCH(delta_t_j); // // KRATOS_WATCH(delta_t_i); // if (delta_t_j < delta_t_i) // delta_t_i = delta_t_j; // } } //choose the overall minimum of delta_t_i if (delta_t_i < delta_t) delta_t = delta_t_i; if(delta_t_i_avg < mdelta_t_avg) mdelta_t_avg = delta_t_i_avg; } //******************* //perform MPI syncronization of the dt (minimum should be kept) if(delta_t <= 10-7) // writing back the changed velocities mr_matrix_container.WriteVectorToDatabase(VELOCITY, mvel_n1, mr_model_part.Nodes()); return delta_t; KRATOS_CATCH("") } void CalculatePorousResistanceLaw(unsigned int res_law) { // const double nu_i = mViscosity; if(res_law == 1) { /* if the chosen resistance law is ERGUN calculate Ergun A and B*/ for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { const double eps = inode->FastGetSolutionStepValue(POROSITY);/*reading from kratos database*/ const double d = inode->FastGetSolutionStepValue(DIAMETER);/*reading from kratos database*/ const double nu = inode->FastGetSolutionStepValue(VISCOSITY);/*reading from kratos database*/ double& a = inode-> FastGetSolutionStepValue(LIN_DARCY_COEF);/*changing kratos database*/ double& b = inode-> FastGetSolutionStepValue(NONLIN_DARCY_COEF);/*changing kratos database*/ if(eps < 1.0) { double k_inv = 150.0 * (1.0 - eps)*(1.0 - eps) / (eps * eps * eps * d * d); a = nu * k_inv; b = (1.75 / eps) * sqrt(k_inv / (150.0 * eps)); } else { a = 0.0; b = 0.0; } } } else { /* whether it is a Custom Resistance law or NO resistance law is present ---> set to zero A and B for non porous nodes*/ for (ModelPart::NodesContainerType::iterator inode = mr_model_part.NodesBegin(); inode != mr_model_part.NodesEnd(); inode++) { const double eps = inode->FastGetSolutionStepValue(POROSITY); /*reading from kratos database*/ double& a = inode-> FastGetSolutionStepValue(LIN_DARCY_COEF); /*changing kratos database*/ double& b = inode-> FastGetSolutionStepValue(NONLIN_DARCY_COEF); /*changing kratos database*/ if(eps == 1.0) { a = 0.0; b = 0.0; } } } mr_matrix_container.FillScalarFromDatabase(LIN_DARCY_COEF, mA, mr_model_part.Nodes()); /*filling edgebased database reading from kratos database*/ mr_matrix_container.FillScalarFromDatabase(NONLIN_DARCY_COEF, mB, mr_model_part.Nodes()); /*filling edgebased database reading from kratos database*/ } private: double mMolecularViscosity; MatrixContainer& mr_matrix_container; ModelPart& mr_model_part; bool muse_mass_correction; //parameters controlling the wall law bool mWallLawIsActive; double mY_wall; //parameters for controlling the usage of the delta time in the stabilization double mstabdt_pressure_factor; double mstabdt_convection_factor; double medge_detection_angle; double mtau2_factor; bool massume_constant_dp; //nodal values ValuesVectorType mViscosity; //velocity vector U at time steps n and n+1 CalcVectorType mWork, mvel_n, mvel_n1, mx; //pressure vector p at time steps n and n+1 ValuesVectorType mPn, mPn1; //coefficients ValuesVectorType mdistances; //minimum length of the edges surrounding edges surrounding each nodal point ValuesVectorType mHmin; ValuesVectorType mHavg; CalcVectorType mEdgeDimensions; //area normal CalcVectorType mSlipNormal; CalcVectorType mInOutNormal; //projection terms CalcVectorType mPi, mXi; //flag for first time step bool mFirstStep; //flag to differentiate interior and boundary nodes ValuesVectorType mNodalFlag; //lists of nodes with different types of boundary conditions IndicesVectorType mSlipBoundaryList, mPressureOutletList, mFixedVelocities, mInOutBoundaryList; CalcVectorType mFixedVelocitiesValues; // ValuesVectorType mPressureOutlet; //intrinsic time step size ValuesVectorType mTauPressure; ValuesVectorType mTauConvection; ValuesVectorType mTau2; ValuesVectorType mdiv_error; std::vector<bool> mis_slip; //variables for resolving pressure equation //laplacian matrix TSystemMatrixType mL; //constant variables double mRho; //double mViscosity; array_1d<double, TDim> mBodyForce; //variables for convection ValuesVectorType mphi_n; ValuesVectorType mphi_n1; CalcVectorType mPiConvection; ValuesVectorType mBeta; //variables for edge BCs IndicesVectorType medge_nodes; CalcVectorType medge_nodes_direction; IndicesVectorType mcorner_nodes; ValuesVectorType mEps; ValuesVectorType mdiag_stiffness; // ValuesVectorType mD; ValuesVectorType mA; ValuesVectorType mB; CalcVectorType mStrVel; double mdelta_t_avg; double max_dt; double mshock_coeff; //*********************************************************** //functions to calculate area normals for boundary conditions void CalculateNormal2D(ModelPart::ConditionsContainerType::iterator cond_it, array_1d<double, 3 > & area_normal) { Geometry<Node < 3 > >& face_geometry = (cond_it)->GetGeometry(); area_normal[0] = face_geometry[1].Y() - face_geometry[0].Y(); area_normal[1] = -(face_geometry[1].X() - face_geometry[0].X()); area_normal[2] = 0.00; noalias((cond_it)->GetValue(NORMAL)) = area_normal; } void CalculateNormal3D(ModelPart::ConditionsContainerType::iterator cond_it, array_1d<double, 3 > & area_normal, array_1d<double, 3 > & v1, array_1d<double, 3 > & v2) { Geometry<Node < 3 > >& face_geometry = (cond_it)->GetGeometry(); v1[0] = face_geometry[1].X() - face_geometry[0].X(); v1[1] = face_geometry[1].Y() - face_geometry[0].Y(); v1[2] = face_geometry[1].Z() - face_geometry[0].Z(); v2[0] = face_geometry[2].X() - face_geometry[0].X(); v2[1] = face_geometry[2].Y() - face_geometry[0].Y(); v2[2] = face_geometry[2].Z() - face_geometry[0].Z(); MathUtils<double>::CrossProduct(area_normal, v1, v2); area_normal *= -0.5; noalias((cond_it)->GetValue(NORMAL)) = area_normal; } //********************************************************* //function to calculate minimum length of surrounding edges void CalculateEdgeLengths(ModelPart::NodesContainerType& rNodes) { KRATOS_TRY //get number of nodes unsigned int n_nodes = rNodes.size(); //reserve memory for storage of nodal coordinates std::vector< array_1d<double, 3 > > position; position.resize(n_nodes); //get position of all nodes for (typename ModelPart::NodesContainerType::iterator node_it = rNodes.begin(); node_it != rNodes.end(); node_it++) { //get the global index of the node unsigned int i_node = static_cast<unsigned int> (node_it->FastGetSolutionStepValue(AUX_INDEX)); //save its coordinates locally noalias(position[i_node]) = node_it->Coordinates(); //initialize minimum edge length with relatively big values mHmin[i_node] = 1e10; } ValuesVectorType& aaa = mr_matrix_container.GetHmin(); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { mHmin[i_node] = aaa[i_node]; } //take unstructured meshes into account if (TDim == 2) { for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { double& h_i = mHavg[i_node]; double& m_i = mr_matrix_container.GetLumpedMass()[i_node]; // double& rho_i = mRho[i_node]; h_i = sqrt(2.0 * m_i); } } else if (TDim == 3) { for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { double& h_i = mHavg[i_node]; double& m_i = mr_matrix_container.GetLumpedMass()[i_node]; // double& rho_i = mRho[i_node]; h_i = pow(6.0 * m_i, 1.0 / 3.0); } } //compute edge coordinates for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { array_1d<double, 3 > & pos_i = position[i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; array_1d<double, 3 > & pos_j = position[j_neighbour]; array_1d<double, TDim>& l_k = mEdgeDimensions[csr_index]; for (unsigned int comp = 0; comp < TDim; comp++) l_k[comp] = pos_i[comp] - pos_j[comp]; } } KRATOS_CATCH("") } //********************************************************************* //function to calculate right-hand side of fractional momentum equation void CalculateRHS_convection( const ValuesVectorType& mphi, const CalcVectorType& convective_velocity, ValuesVectorType& rhs, ValuesVectorType& active_nodes ) { KRATOS_TRY int n_nodes = mphi.size(); // //calculating the convective projection //#pragma omp parallel for // for (int i_node = 0; i_node < n_nodes; i_node++) // { // // double& pi_i = mPiConvection[i_node]; // const double& phi_i = mphi[i_node]; // // //set to zero the projection // pi_i = 0; // if (active_nodes[i_node] != 0.0) // { // // const array_1d<double, TDim>& a_i = convective_velocity[i_node]; // // //loop to all the edges surrounding node I // for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) // { // unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; // // if (active_nodes[j_neighbour] != 0.0) // { // const array_1d<double, TDim>& a_j = convective_velocity[j_neighbour]; // const double& phi_j = mphi[j_neighbour]; // // CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; // // edge_ij.Add_ConvectiveContribution(pi_i, a_i, phi_i, a_j, phi_j); // } // } // // //apply inverted mass matrix // const double m_inv = mr_matrix_container.GetInvertedMass()[i_node]; // pi_i *= m_inv; // } // // KRATOS_WATCH(pi_i); // // num = fabs(num); // // if(num > norm_vI*0.0001) // // mBeta[i_node] = 1.0 - num/denom; // // else // // mBeta[i_node] = 1.0; // // } //perform MPI syncronization //calculating the RHS double stab_low; double stab_high; array_1d<double, TDim> a_i; array_1d<double, TDim> a_j; #pragma omp parallel for private(stab_low,stab_high,a_i,a_j) for (int i_node = 0; i_node < n_nodes; i_node++) { double& rhs_i = rhs[i_node]; const double& h_i = mHavg[i_node]; const double& phi_i = mphi[i_node]; noalias(a_i) = convective_velocity[i_node]; a_i /= mEps[i_node]; const array_1d<double, TDim>& proj_i = mPiConvection[i_node]; // const double& pi_i = mPiConvection[i_node]; double pi_i = proj_i[0] * a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) pi_i += proj_i[l_comp] * a_i[l_comp]; // double beta = mBeta[i_node]; rhs_i = 0.0; if (active_nodes[i_node] != 0.0) { const double& beta = mBeta[i_node]; double norm_a = a_i[0] * a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) norm_a += a_i[l_comp] * a_i[l_comp]; norm_a = sqrt(norm_a); //loop to all the edges surrounding node I for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; if (active_nodes[j_neighbour] != 0.0) { //double& rhs_j = rhs[j_neighbour]; const double& phi_j = mphi[j_neighbour]; noalias(a_j) = convective_velocity[j_neighbour]; a_j /= mEps[j_neighbour]; // const double& pi_j = mPiConvection[j_neighbour]; const array_1d<double, TDim>& proj_j = mPiConvection[j_neighbour]; double pi_j = proj_j[0] * a_i[0]; for (unsigned int l_comp = 1; l_comp < TDim; l_comp++) pi_j += proj_j[l_comp] * a_i[l_comp]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; //convection operator edge_ij.Sub_ConvectiveContribution(rhs_i, a_i, phi_i, a_j, phi_j); //esto funciona // edge_ij.Sub_D_v(rhs_i, a_i*phi_i, a_i*phi_j); //calculate stabilization part edge_ij.CalculateConvectionStabilization_LOW(stab_low, a_i, phi_i, a_j, phi_j); double edge_tau = mTauConvection[i_node]; edge_ij.CalculateConvectionStabilization_HIGH(stab_high, a_i, pi_i, a_j, pi_j); edge_ij.Sub_StabContribution(rhs_i, edge_tau, 1.0, stab_low, stab_high); double coeff = 0.5 * mshock_coeff; //=0.7*0.5; double laplacian_ij = 0.0; edge_ij.CalculateScalarLaplacian(laplacian_ij); double capturing = laplacian_ij * (phi_j - phi_i); // rhs_i-= coeff*capturing*beta*norm_a*h_i; double aaa = 0.0; for (unsigned int k_comp = 0; k_comp < TDim; k_comp++) for (unsigned int m_comp = 0; m_comp < TDim; m_comp++) aaa += a_i[k_comp] * a_i[m_comp] * edge_ij.LaplacianIJ(k_comp, m_comp); if (norm_a > 1e-10) { aaa /= (norm_a * norm_a); double capturing2 = aaa * (phi_j - phi_i); if (fabs(capturing) > fabs(capturing2)) rhs_i -= coeff * (capturing - capturing2) * beta * norm_a * h_i; } } } } // KRATOS_WATCH(rhs_i); } KRATOS_CATCH("") } //************************************** void CornerDectectionHelper(Geometry< Node < 3 > >& face_geometry, const array_1d<double, 3 > & face_normal, const double An, const GlobalPointersVector<Condition>& neighb, const unsigned int i1, const unsigned int i2, const unsigned int neighb_index, std::vector<unsigned int>& edge_nodes, CalcVectorType& cornern_list ) { double acceptable_angle = 45.0 / 180.0 * 3.1; //angles of less than 45 deg will be accepted double acceptable_cos = cos(acceptable_angle); if (face_geometry[i1].Id() < face_geometry[i2].Id()) //we do this to add the face ones { const array_1d<double, 3 > & neighb_normal = neighb[neighb_index].GetValue(NORMAL); double neighb_An = norm_2(neighb_normal); double cos_normal = 1.0 / (An * neighb_An) * inner_prod(face_normal, neighb_normal); //if the angle is too big between the two normals then the edge in the middle is a corner if (cos_normal < acceptable_cos) { array_1d<double, 3 > edge = face_geometry[i2].Coordinates() - face_geometry[i1].Coordinates(); double temp = norm_2(edge); edge /= temp; int index1 = face_geometry[i1].FastGetSolutionStepValue(AUX_INDEX); int index2 = face_geometry[i2].FastGetSolutionStepValue(AUX_INDEX); edge_nodes[index1] += 1; edge_nodes[index2] += 1; // double sign1 = inner_prod(cornern_list[index1], edge); double sign1 = 0.0; for(unsigned int i = 0 ; i < edge.size() ; i++) {sign1 += cornern_list[index1][i]*edge[i];} if (sign1 >= 0) { for(unsigned int i = 0 ; i < edge.size() ; i++) cornern_list[index1][i] += edge[i]; } else { for(unsigned int i = 0 ; i < edge.size() ; i++) cornern_list[index1][i] -= edge[i]; } double sign2 = inner_prod(cornern_list[index2], edge); if (sign2 >= 0) { for(unsigned int i = 0 ; i < edge.size() ; i++) cornern_list[index2][i] += edge[i]; } else { for(unsigned int i = 0 ; i < edge.size() ; i++) cornern_list[index2][i] -= edge[i]; } } } } //function to calculate the area normals void DetectEdges3D(ModelPart::ConditionsContainerType& rConditions) { KRATOS_TRY //calculate area normals face-by-face array_1d<double, 3 > area_normal; //(re)initialize normals unsigned int n_nodes = mNodalFlag.size(); std::vector<unsigned int> temp_edge_nodes(n_nodes); CalcVectorType temp_cornern_list(n_nodes); for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { temp_edge_nodes[i_node] = 0.0; noalias(temp_cornern_list[i_node]) = ZeroVector(TDim); } //loop over all faces // const double node_factor = 1.0 / TDim; for (ModelPart::ConditionsContainerType::iterator cond_it = rConditions.begin(); cond_it != rConditions.end(); cond_it++) { //get geometry data of the face Geometry<Node < 3 > >& face_geometry = cond_it->GetGeometry(); //reference for area normal of the face const array_1d<double, 3 > & face_normal = cond_it->GetValue(NORMAL); double An = norm_2(face_normal); unsigned int current_id = cond_it->Id(); //slip condition if (cond_it->GetValue(IS_STRUCTURE) == 1.0) //this is a slip face --> now look for its neighbours { const GlobalPointersVector<Condition>& neighb = cond_it->GetValue(NEIGHBOUR_CONDITIONS); //check for neighbour zero if (neighb[0].Id() != current_id) //check if the neighbour exists CornerDectectionHelper(face_geometry, face_normal, An, neighb, 1, 2, 0, temp_edge_nodes, temp_cornern_list); //check for neighbour one if (neighb[1].Id() != current_id) //check if the neighbour exists CornerDectectionHelper(face_geometry, face_normal, An, neighb, 2, 0, 1, temp_edge_nodes, temp_cornern_list); //check for neighbour two if (neighb[2].Id() != current_id) //check if the neighbour exists CornerDectectionHelper(face_geometry, face_normal, An, neighb, 0, 1, 2, temp_edge_nodes, temp_cornern_list); } } // ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); // mr_matrix_container.WriteVectorToDatabase(ACCELERATION, temp_cornern_list, rNodes); //fill the list of edge_nodes std::vector<unsigned int> tempmedge_nodes; std::vector< array_1d<double,TDim> > tempmedge_nodes_direction; std::vector<unsigned int> tempmcorner_nodes; for (unsigned int i_node = 0; i_node < n_nodes; i_node++) { if (temp_edge_nodes[i_node] == 2) //node is a edge_node { tempmedge_nodes.push_back(i_node); array_1d<double, TDim>& node_edge = temp_cornern_list[i_node]; node_edge /= norm_2(node_edge); tempmedge_nodes_direction.push_back(node_edge); } else if (temp_edge_nodes[i_node] > 2) tempmcorner_nodes.push_back(i_node); } medge_nodes.resize(tempmedge_nodes.size(),false); medge_nodes_direction.resize(tempmedge_nodes_direction.size(),false); mcorner_nodes.resize(tempmcorner_nodes.size(),false); #pragma omp parallel for for ( int i = 0; i < static_cast<int>(tempmedge_nodes.size()); i++) { medge_nodes[i] = tempmedge_nodes[i]; medge_nodes_direction[i] = tempmedge_nodes_direction[i]; } #pragma omp parallel for for (int i = 0; i < static_cast<int>(tempmcorner_nodes.size()); i++) { mcorner_nodes[i] = tempmcorner_nodes[i]; } for (int i = 0; i < static_cast<int>(mcorner_nodes.size()); i++) { KRATOS_WATCH(mcorner_nodes[i]); } KRATOS_CATCH("") } // double ComputePorosityCoefficient(const double& viscosity, const double& vel_norm, const double& eps, const double& d) // { // // const double d = 0.01; //to be changed // double linear; // double non_linear; // if (eps < 1.0) // { // double k_inv = 150.0 * (1.0 - eps)*(1.0 - eps) / (eps * eps * eps * d * d); // linear = eps * viscosity * k_inv; // eps * Ai // non_linear = (1.75 * vel_norm) * sqrt(k_inv / (150.0 * eps)); //eps * Bi * vel_norm // // double linear = viscosity * k_inv; // // double non_linear = (1.75 * vel_norm / eps) * sqrt(k_inv / (150.0 * eps)); // } else // { // linear = 0.0; // non_linear = 0.0; // } // return linear + non_linear; // } double ComputePorosityCoefficient(const double& vel_norm, const double& eps, const double& a, const double& b) { double linear; double non_linear; // if (eps < 1.0) /*this check has been already done in calculating the resistance law*/ // { linear = eps * a; non_linear = eps * b * vel_norm; // } else // { // linear = 0.0; // non_linear = 0.0; // } return linear + non_linear; } // double ComputeStructureContributionToPorosityCoefficient(const double& fluid_vel, const double& str_vel, const double& str_vel_norm, const double& eps, const double& a, const double& b) // { // // // } void LaplacianSmooth(ValuesVectorType& to_be_smoothed, ValuesVectorType& aux) { ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); int n_nodes = rNodes.size(); #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) { double dist = mdistances[i_node]; double correction = 0.0; const double& origin_i = to_be_smoothed[i_node]; if (dist <= 0.0) //node is inside domain ---- if outside do nothing { for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex()[i_node]; csr_index != mr_matrix_container.GetRowStartIndex()[i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex()[csr_index]; const double& origin_j = to_be_smoothed[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues()[csr_index]; double l_ikjk; edge_ij.CalculateScalarLaplacian(l_ikjk); correction += l_ikjk * (origin_j - origin_i); } } aux[i_node] = origin_i - correction; } #pragma omp parallel for for (int i_node = 0; i_node < n_nodes; i_node++) to_be_smoothed[i_node] = aux[i_node]; } void ComputeWallResistance( const CalcVectorType& vel, ValuesVectorType& diag_stiffness // CalcVectorType& rhs ) { //parameters: double k = 0.41; double B = 5.1; double toll = 1e-6; double ym = mY_wall; //0.0825877; //0.0093823 double y_plus_incercept = 10.9931899; unsigned int itmax = 100; if (mViscosity[0] == 0) KRATOS_THROW_ERROR(std::logic_error, "it is not possible to use the wall law with 0 viscosity", ""); //slip condition int slip_size = mSlipBoundaryList.size(); #pragma omp parallel for firstprivate(slip_size,B,toll,ym,y_plus_incercept,itmax) for (int i_slip = 0; i_slip < slip_size; i_slip++) { unsigned int i_node = mSlipBoundaryList[i_slip]; double dist = mdistances[i_node]; const double nu = mViscosity[i_node]; if (dist <= 0.0) { //array_1d<double, TDim>& rhs_i = rhs[i_node]; const array_1d<double, TDim>& U_i = vel[i_node]; const array_1d<double, TDim>& an_i = mSlipNormal[i_node]; //compute the modulus of the velocity double mod_vel = 0.0; double area = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) { mod_vel += U_i[comp] * U_i[comp]; area += an_i[comp] * an_i[comp]; } mod_vel = sqrt(mod_vel); area = sqrt(area); diag_stiffness[i_node] += area * mod_vel /pow(1.0/k*log(100.00) + B,2);/* * mWallReductionFactor[ i_node ];*/ //now compute the skin friction double mod_uthaw = sqrt(mod_vel * nu / ym); const double y_plus = ym * mod_uthaw / nu; if (y_plus > y_plus_incercept) { //begin cicle to calculate the real u_thaw's module: unsigned int it = 0; double dx = 1e10; // KRATOS_WATCH(fabs(dx)); while (fabs(dx) > toll * mod_uthaw && it < itmax) { double a = 1.0 / k; double temp = a * log(ym * mod_uthaw / nu) + B; double y = mod_uthaw * (temp) - mod_vel; double y1 = temp + a; dx = y / y1; mod_uthaw -= dx; it = it + 1; } if (it == itmax) std::cout << "attention max number of iterations exceeded in wall law computation" << std::endl; } // else // { // for (unsigned int comp = 0; comp < TDim; comp++) // rhs_i[comp] -= U_i[comp] * area * mu / (density*ym) ; // } /* if (mod_vel > 1e-12) for (unsigned int comp = 0; comp < TDim; comp++) rhs_i[comp] -= U_i[comp] * area * mod_uthaw * mod_uthaw / (mod_vel); */ } else diag_stiffness[i_node] += 0.0; } } void ApplySmagorinsky3D (double MolecularViscosity, double Cs) { KRATOS_TRY ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); //calculating the RHS array_1d<double, TDim> grad_vx; array_1d<double, TDim> grad_vy; array_1d<double, TDim> grad_vz; int n_nodes = rNodes.size(); mr_matrix_container.FillVectorFromDatabase (VELOCITY, mvel_n1, rNodes); array_1d<double, TDim> stab_high; #pragma omp parallel for private(grad_vx,grad_vy,grad_vz) for (int i_node = 0; i_node < n_nodes; i_node++) { //set to zero the gradients for (unsigned int comp = 0; comp < TDim; comp++) { grad_vx[comp] = 0.0 ; grad_vy[comp] = 0.0 ; grad_vz[comp] = 0.0 ; } //compute node by node the gradients const array_1d<double, TDim>& U_i = mvel_n1[i_node]; const double h = mHmin[i_node]; const double m_inv = mr_matrix_container.GetInvertedMass() [i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex() [i_node]; csr_index != mr_matrix_container.GetRowStartIndex() [i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex() [csr_index]; const array_1d<double, TDim>& U_j = mvel_n1[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues() [csr_index]; edge_ij.Add_grad_p (grad_vx, U_i[0], U_j[0]); edge_ij.Add_grad_p (grad_vy, U_i[1], U_j[1]); edge_ij.Add_grad_p (grad_vz, U_i[2], U_j[2]); } //finalize computation of the gradients //set to zero the gradients for (unsigned int comp = 0; comp < TDim; comp++) { grad_vx[comp] *= m_inv ; grad_vy[comp] *= m_inv ; grad_vz[comp] *= m_inv ; } //symmetrize and multiply by 2 grad_vx[0] *= 2.0; grad_vy[1] *= 2.0; grad_vz[2] *= 2.0; grad_vx[1] += grad_vy[0]; grad_vx[2] += grad_vz[0]; grad_vy[2] += grad_vz[1]; grad_vy[0] += grad_vx[1]; grad_vz[0] += grad_vx[2]; grad_vz[1] += grad_vy[2]; //compute smagorinsky term double aux = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) { aux += grad_vx[comp] * grad_vx[comp] ; aux += grad_vy[comp] * grad_vy[comp] ; aux += grad_vz[comp] * grad_vz[comp] ; } aux *= 0.5; if (aux < 0.0 ) aux=0.0; double turbulent_viscosity = Cs*h*h*sqrt (aux) /**MolecularViscosity*/; mViscosity[i_node] = turbulent_viscosity + MolecularViscosity; } mr_matrix_container.WriteScalarToDatabase (VISCOSITY, mViscosity, rNodes); KRATOS_CATCH (""); } void ApplySmagorinsky2D (double MolecularViscosity, double Cs) { KRATOS_TRY ModelPart::NodesContainerType& rNodes = mr_model_part.Nodes(); //calculating the RHS array_1d<double, TDim> grad_vx; array_1d<double, TDim> grad_vy; // array_1d<double, TDim> grad_vz; int n_nodes = rNodes.size(); mr_matrix_container.FillVectorFromDatabase (VELOCITY, mvel_n1, rNodes); array_1d<double, TDim> stab_high; #pragma omp parallel for private(grad_vx,grad_vy) for (int i_node = 0; i_node < n_nodes; i_node++) { //set to zero the gradients for (unsigned int comp = 0; comp < TDim; comp++) { grad_vx[comp] = 0.0 ; grad_vy[comp] = 0.0 ; // grad_vz[comp] = 0.0 ; } //compute node by node the gradients const array_1d<double, TDim>& U_i = mvel_n1[i_node]; const double h = mHmin[i_node]; const double m_inv = mr_matrix_container.GetInvertedMass() [i_node]; for (unsigned int csr_index = mr_matrix_container.GetRowStartIndex() [i_node]; csr_index != mr_matrix_container.GetRowStartIndex() [i_node + 1]; csr_index++) { unsigned int j_neighbour = mr_matrix_container.GetColumnIndex() [csr_index]; const array_1d<double, TDim>& U_j = mvel_n1[j_neighbour]; CSR_Tuple& edge_ij = mr_matrix_container.GetEdgeValues() [csr_index]; edge_ij.Add_grad_p (grad_vx, U_i[0], U_j[0]); edge_ij.Add_grad_p (grad_vy, U_i[1], U_j[1]); } //finalize computation of the gradients //set to zero the gradients for (unsigned int comp = 0; comp < TDim; comp++) { grad_vx[comp] *= m_inv ; grad_vy[comp] *= m_inv ; } //symmetrize and multiply by 2 grad_vx[0] *= 2.0; grad_vy[1] *= 2.0; grad_vx[1] += grad_vy[0]; grad_vy[0] += grad_vx[1]; //compute smagorinsky term double aux = 0.0; for (unsigned int comp = 0; comp < TDim; comp++) { aux += grad_vx[comp] * grad_vx[comp] ; aux += grad_vy[comp] * grad_vy[comp] ; } aux *= 0.5; if (aux < 0.0 ) aux=0.0; double turbulent_viscosity = Cs*h*h*sqrt (aux) /**MolecularViscosity*/; mViscosity[i_node] = turbulent_viscosity + MolecularViscosity; } mr_matrix_container.WriteScalarToDatabase (VISCOSITY, mViscosity, rNodes); KRATOS_CATCH (""); } void Add_Effective_Inverse_Multiply ( CalcVectorType& destination, const CalcVectorType& origin1, const double value, const ValuesVectorType& mass, const ValuesVectorType& diag_stiffness, const CalcVectorType& origin ) { KRATOS_TRY int loop_size = destination.size(); #pragma omp parallel for for (int i_node = 0; i_node < loop_size; i_node++) { array_1d<double, TDim>& dest = destination[i_node]; const double m = mass[i_node]; const double d = diag_stiffness[i_node]; const array_1d<double, TDim>& origin_vec1 = origin1[i_node]; const array_1d<double, TDim>& origin_value = origin[i_node]; for (unsigned int comp = 0; comp < TDim; comp++) dest[comp] = value / (m + value*d) * ( m/value * origin_vec1[comp] + origin_value[comp] ); } KRATOS_CATCH ("") } }; } //namespace Kratos #undef SYMM_PRESS #endif //KRATOS_EDGEBASED_LEVELSET_FLUID_SOLVER_H_INCLUDED defined
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 4; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[(t)%2][i ][j ][k ] + coef[1][i][j][k] * (A[(t)%2][i-1][j ][k ] + A[(t)%2][i+1][j ][k ]) + coef[2][i][j][k] * (A[(t)%2][i ][j-1][k ] + A[(t)%2][i ][j+1][k ]) + coef[3][i][j][k] * (A[(t)%2][i ][j ][k-1] + A[(t)%2][i ][j ][k+1]) + coef[4][i][j][k] * (A[(t)%2][i-2][j ][k ] + A[(t)%2][i+2][j ][k ]) + coef[5][i][j][k] * (A[(t)%2][i ][j-2][k ] + A[(t)%2][i ][j+2][k ]) + coef[6][i][j][k] * (A[(t)%2][i ][j ][k-2] + A[(t)%2][i ][j ][k+2]) + coef[7][i][j][k] * (A[(t)%2][i-3][j ][k ] + A[(t)%2][i+3][j ][k ]) + coef[8][i][j][k] * (A[(t)%2][i ][j-3][k ] + A[(t)%2][i ][j+3][k ]) + coef[9][i][j][k] * (A[(t)%2][i ][j ][k-3] + A[(t)%2][i ][j ][k+3]) + coef[10][i][j][k]* (A[(t)%2][i-4][j ][k ] + A[(t)%2][i+4][j ][k ]) + coef[11][i][j][k]* (A[(t)%2][i ][j-4][k ] + A[(t)%2][i ][j+4][k ]) + coef[12][i][j][k]* (A[(t)%2][i ][j ][k-4] + A[(t)%2][i ][j ][k+4]) ; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
begin_declare_variant_messages.c
// RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp -x c -std=c99 -fms-extensions -Wno-pragma-pack %s // RUN: %clang_cc1 -triple=x86_64-pc-win32 -verify -fopenmp-simd -x c -std=c99 -fms-extensions -Wno-pragma-pack %s #pragma omp begin // expected-error {{expected an OpenMP directive}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp begin declare // expected-error {{expected an OpenMP directive}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp begin variant // expected-error {{expected an OpenMP directive}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp variant begin // expected-error {{expected an OpenMP directive}} #pragma omp declare variant end // expected-error {{function declaration is expected after 'declare variant' directive}} #pragma omp begin declare variant // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp end declare variant // TODO: Issue an error message #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} #pragma omp end declare variant // expected-error {{'#pragma omp end declare variant' with no matching '#pragma omp begin declare variant'}} int foo(void); const int var; #pragma omp begin declare variant // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp end declare variant #pragma omp begin declare variant xxx // expected-error {{expected 'match' clause on 'omp declare variant' directive}} #pragma omp end declare variant #pragma omp begin declare variant match // expected-error {{expected '(' after 'match'}} #pragma omp end declare variant #pragma omp begin declare variant match( // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match() // expected-warning {{expected identifier or string literal describing a context set; set skipped}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx=) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx=yyy) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx=yyy}) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{extra tokens at the end of '#pragma omp begin declare variant' are ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx={) // expected-error {{expected ')'}} expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx={}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx={vvv, vvv}) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx={vvv} xxx) // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(xxx={vvv}) xxx // expected-warning {{'xxx' is not a valid context set in a `declare variant`; set ignored}} expected-warning {{extra tokens at the end of '#pragma omp begin declare variant' are ignored}} expected-note {{context set options are: 'construct' 'device' 'implementation' 'user'}} expected-note {{the ignored set spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'implementation'; selector ignored}} expected-note {{context selector options are: 'vendor' 'extension' 'unified_address' 'unified_shared_memory' 'reverse_offload' 'dynamic_allocators' 'atomic_default_mem_order'}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor}) // expected-warning {{the context selector 'vendor' in context set 'implementation' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score ibm)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score( ibm)}) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score(2 ibm)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'amd' 'arm' 'bsc' 'cray' 'fujitsu' 'gnu' 'ibm' 'intel' 'llvm' 'nec' 'nvidia' 'pgi' 'ti' 'unknown'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score(5): ibm), vendor(llvm)}) // expected-warning {{the context selector 'vendor' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'vendor' used here}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation={vendor(score(5): ibm), kind(cpu)}) // expected-warning {{the context selector 'kind' is not valid for the context set 'implementation'; selector ignored}} expected-note {{the context selector 'kind' can be nested in the context set 'device'; try 'match(device={kind(property)})'}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device={xxx}) // expected-warning {{'xxx' is not a valid context selector for the context set 'device'; selector ignored}} expected-note {{context selector options are: 'kind' 'arch' 'isa'}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind}) // expected-warning {{the context selector 'kind' in context set 'device' requires a context property defined in parentheses; selector ignored}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(}) // expected-error {{expected ')'}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind()}) // expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(score cpu)}) // expected-error {{expected '(' after 'score'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<invalid>'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(ibm) }) // expected-error {{use of undeclared identifier 'ibm'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<recovery-expr>()'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(score(2 gpu)}) // expected-error {{expected ')'}} expected-error {{expected ')'}} expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('2'); score ignored}} expected-warning {{expected identifier or string literal describing a context property; property skipped}} expected-note {{to match this '('}} expected-note {{context property options are: 'host' 'nohost' 'cpu' 'gpu' 'fpga' 'any'}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(score(foo()) ibm)}) // expected-warning {{expected '':'' after the score expression; '':'' assumed}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-warning {{'ibm' is not a valid context property for the context selector 'kind' and the context set 'device'; property ignored}} expected-note {{try 'match(implementation={vendor(ibm)})'}} expected-note {{the ignored property spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(score(5): host), kind(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'kind' was used already in the same 'omp declare variant' directive; selector ignored}} expected-note {{the previous context selector 'kind' used here}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(score(5): nohost), vendor(llvm)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('5'); score ignored}} expected-warning {{the context selector 'vendor' is not valid for the context set 'device'; selector ignored}} expected-note {{the context selector 'vendor' can be nested in the context set 'implementation'; try 'match(implementation={vendor(property)})'}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(foo()): cpu}) // expected-error {{expected ')'}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(foo()): cpu)) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-warning {{expected '}' after the context selectors for the context set "device"; '}' assumed}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(foo()): cpu)} // expected-error {{expected ')'}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} expected-note {{to match this '('}} #pragma omp end declare variant #pragma omp begin declare variant match(implementation = {vendor(score(foo) :llvm)}) #pragma omp end declare variant #pragma omp begin declare variant match(implementation = {vendor(score(foo()) :llvm)}) #pragma omp end declare variant #pragma omp begin declare variant match(implementation = {vendor(score(<expr>) :llvm)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} #pragma omp end declare variant #pragma omp begin declare variant match(user = {condition(foo)}) #pragma omp end declare variant #pragma omp begin declare variant match(user = {condition(foo())}) #pragma omp end declare variant #pragma omp begin declare variant match(user = {condition(<expr>)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} expected-note {{the ignored selector spans until here}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(&var): cpu)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('&var'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(var): cpu)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('var'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(foo): cpu)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(foo()): cpu)}) // expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('foo()'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device = {kind(score(<expr>): cpu)}) // expected-error {{expected expression}} expected-error {{use of undeclared identifier 'expr'}} expected-error {{expected expression}} expected-warning {{the context selector 'kind' in the context set 'device' cannot have a score ('<invalid>'); score ignored}} #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(cpu)}) static int defined_twice_a(void) { // expected-note {{previous definition is here}} return 0; } int defined_twice_b(void) { // expected-note {{previous definition is here}} return 0; } inline int defined_twice_c(void) { // expected-note {{previous definition is here}} return 0; } #pragma omp end declare variant #pragma omp begin declare variant match(device={kind(cpu)}) static int defined_twice_a(void) { // expected-error {{redefinition of 'defined_twice_a[device={kind(cpu)}]'}} return 1; } int defined_twice_b(void) { // expected-error {{redefinition of 'defined_twice_b[device={kind(cpu)}]'}} return 1; } inline int defined_twice_c(void) { // expected-error {{redefinition of 'defined_twice_c[device={kind(cpu)}]'}} return 1; } #pragma omp end declare variant // TODO: Issue an error message #pragma omp begin declare variant match(device={kind(cpu)}) // The matching end is missing. Since the device clause is matching we will // emit and error. int also_before(void) { return 0; } #pragma omp begin declare variant match(device={kind(gpu)}) // expected-note {{to match this '#pragma omp begin declare variant'}} // The matching end is missing. Since the device clause is not matching we will // cause us to elide the rest of the file and emit and error. int also_after(void) { return 2; } int also_before(void) { return 2; } #pragma omp begin declare variant match(device={kind(fpga)}) This text is never parsed! #pragma omp end declare variant This text is also not parsed! // expected-error {{expected '#pragma omp end declare variant'}}